From bb1caaba111699be1855588e6d053a10dc84b658 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Tue, 10 Mar 2026 17:30:04 +0000 Subject: [PATCH] feat: add ACP agent variants for Claude, Codex, Copilot, and Amp (#387) --- apps/backend/cmd/kandev/adapters.go | 20 +- apps/backend/cmd/kandev/helpers.go | 45 ++ apps/backend/cmd/mock-agent/emitter.go | 90 +++ apps/backend/cmd/mock-agent/handler.go | 194 +++---- apps/backend/cmd/mock-agent/main.go | 184 ++++--- apps/backend/cmd/mock-agent/mcp_client.go | 15 + apps/backend/cmd/mock-agent/permission.go | 48 -- apps/backend/cmd/mock-agent/scenarios.go | 492 ++++++----------- apps/backend/cmd/mock-agent/script.go | 51 +- apps/backend/cmd/mock-agent/script_test.go | 515 ++++++++---------- apps/backend/cmd/mock-agent/sequences.go | 514 ++++------------- apps/backend/cmd/mock-agent/types.go | 192 ------- apps/backend/internal/agent/agents/amp_acp.go | 121 ++++ .../internal/agent/agents/claude_acp.go | 140 +++++ .../internal/agent/agents/codex_acp.go | 132 +++++ apps/backend/internal/agent/agents/copilot.go | 4 +- .../internal/agent/agents/copilot_acp.go | 126 +++++ apps/backend/internal/agent/agents/mock.go | 4 +- .../internal/agent/agents/mock_test.go | 79 +-- .../internal/agent/agents/opencode_acp.go | 28 +- .../internal/agent/lifecycle/event_types.go | 93 +++- .../internal/agent/lifecycle/events.go | 46 +- .../agent/lifecycle/manager_events.go | 17 + .../agent/lifecycle/manager_interaction.go | 161 ++++++ .../agent/lifecycle/manager_lifecycle_test.go | 28 + .../agent/lifecycle/manager_profile.go | 16 +- .../internal/agent/lifecycle/session.go | 21 + .../internal/agent/lifecycle/session_test.go | 8 +- .../backend/internal/agent/lifecycle/types.go | 49 ++ .../internal/agent/registry/registry.go | 4 + .../backend/internal/agentctl/client/agent.go | 95 +++- .../internal/agentctl/server/acp/client.go | 73 ++- .../internal/agentctl/server/acp/terminal.go | 232 ++++++++ .../agentctl/server/adapter/adapter.go | 25 + .../agentctl/server/adapter/amp_adapter.go | 35 +- .../server/adapter/copilot_adapter.go | 29 +- .../server/adapter/e2e/mock_agent_test.go | 424 +++++++++++++- .../server/adapter/transport/acp/adapter.go | 237 +++++++- .../adapter/transport/acp/meta_convert.go | 229 ++++++++ .../server/adapter/transport/codex/adapter.go | 10 +- .../adapter/transport/codex/codex_prompt.go | 77 +-- .../adapter/transport/codex/codex_session.go | 2 + .../adapter/transport/opencode/adapter.go | 39 +- .../adapter/transport/shared/attachments.go | 171 ++++++ .../transport/shared/attachments_test.go | 381 +++++++++++++ .../adapter/transport/streamjson/adapter.go | 10 +- .../transport/streamjson/streamjson_prompt.go | 99 +--- .../streamjson/streamjson_session.go | 2 + .../internal/agentctl/server/api/agent.go | 110 ++++ .../server/process/workspace_tracker.go | 43 +- .../internal/agentctl/types/streams/agent.go | 138 +++++ apps/backend/internal/events/types.go | 55 ++ .../websocket/session_notifications.go | 4 + .../simulated_agent_manager_test.go | 8 + .../internal/integration/test_server_test.go | 1 + .../orchestrator/event_handlers_streaming.go | 160 +++++- .../event_handlers_streaming_test.go | 25 +- .../orchestrator/event_handlers_test.go | 6 + .../orchestrator/event_handlers_workflow.go | 2 +- .../orchestrator/executor/executor.go | 9 + .../executor/executor_interaction.go | 39 +- .../orchestrator/executor/executor_test.go | 7 + .../orchestrator/scheduler/scheduler_test.go | 7 + apps/backend/internal/orchestrator/service.go | 3 + .../internal/orchestrator/task_operations.go | 10 +- .../orchestrator/task_operations_test.go | 1 + .../task/handlers/process_handlers.go | 69 +++ apps/backend/internal/task/models/models.go | 2 + apps/backend/pkg/api/v1/task.go | 11 +- apps/backend/pkg/websocket/actions.go | 5 + apps/web/components/combobox.tsx | 100 +++- .../task/auth-methods-indicator.tsx | 82 +++ .../components/task/chat/chat-input-area.tsx | 26 +- .../components/task/chat/chat-input-body.tsx | 277 +++++++--- .../task/chat/chat-input-container.tsx | 14 +- .../task/chat/chat-input-toolbar.tsx | 26 + .../task/chat/context-items/context-chip.tsx | 1 + .../context-items/context-item-renderer.tsx | 3 + .../task/chat/context-items/context-zone.tsx | 20 +- .../context-items/file-attachment-item.tsx | 20 + .../task/chat/context-items/image-item.tsx | 3 - .../task/chat/file-attachment-preview.tsx | 72 +++ .../components/task/chat/file-attachment.ts | 101 ++++ .../task/chat/messages/chat-message.tsx | 16 +- .../task/chat/messages/rich-blocks.tsx | 39 +- .../task/chat/messages/todo-message.tsx | 92 ++-- .../components/task/chat/tiptap-helpers.ts | 12 +- .../components/task/chat/todo-indicator.tsx | 92 ++++ .../web/components/task/chat/todo-summary.tsx | 45 -- .../task/chat/use-chat-input-container.ts | 33 +- .../task/chat/use-chat-input-state.ts | 67 ++- .../task/chat/use-chat-panel-state.ts | 24 + .../task/config-options-display.tsx | 49 ++ .../task/dockview-header-actions.tsx | 6 +- apps/web/components/task/mode-selector.tsx | 78 +++ apps/web/components/task/model-selector.tsx | 146 +++-- apps/web/hooks/use-message-handler.ts | 1 + apps/web/lib/api/domains/session-api.ts | 18 + apps/web/lib/local-storage.ts | 37 +- .../session-runtime/session-runtime-slice.ts | 28 +- .../lib/state/slices/session-runtime/types.ts | 104 +++- apps/web/lib/state/store.ts | 58 +- apps/web/lib/types/backend.ts | 115 ++-- apps/web/lib/types/context.ts | 10 +- .../web/lib/types/session-runtime-payloads.ts | 75 +++ apps/web/lib/types/workspace-files.ts | 66 +++ .../web/lib/ws/handlers/agent-capabilities.ts | 33 ++ apps/web/lib/ws/handlers/prompt-usage.ts | 22 + apps/web/lib/ws/handlers/session-mode.ts | 17 +- apps/web/lib/ws/handlers/session-models.ts | 33 ++ apps/web/lib/ws/handlers/session-todos.ts | 26 + apps/web/lib/ws/router.ts | 8 + 112 files changed, 6118 insertions(+), 2299 deletions(-) create mode 100644 apps/backend/cmd/mock-agent/emitter.go delete mode 100644 apps/backend/cmd/mock-agent/permission.go delete mode 100644 apps/backend/cmd/mock-agent/types.go create mode 100644 apps/backend/internal/agent/agents/amp_acp.go create mode 100644 apps/backend/internal/agent/agents/claude_acp.go create mode 100644 apps/backend/internal/agent/agents/codex_acp.go create mode 100644 apps/backend/internal/agent/agents/copilot_acp.go create mode 100644 apps/backend/internal/agentctl/server/acp/terminal.go create mode 100644 apps/backend/internal/agentctl/server/adapter/transport/acp/meta_convert.go create mode 100644 apps/backend/internal/agentctl/server/adapter/transport/shared/attachments.go create mode 100644 apps/backend/internal/agentctl/server/adapter/transport/shared/attachments_test.go create mode 100644 apps/web/components/task/auth-methods-indicator.tsx create mode 100644 apps/web/components/task/chat/context-items/file-attachment-item.tsx create mode 100644 apps/web/components/task/chat/file-attachment-preview.tsx create mode 100644 apps/web/components/task/chat/file-attachment.ts create mode 100644 apps/web/components/task/chat/todo-indicator.tsx delete mode 100644 apps/web/components/task/chat/todo-summary.tsx create mode 100644 apps/web/components/task/config-options-display.tsx create mode 100644 apps/web/components/task/mode-selector.tsx create mode 100644 apps/web/lib/types/session-runtime-payloads.ts create mode 100644 apps/web/lib/types/workspace-files.ts create mode 100644 apps/web/lib/ws/handlers/agent-capabilities.ts create mode 100644 apps/web/lib/ws/handlers/prompt-usage.ts create mode 100644 apps/web/lib/ws/handlers/session-models.ts create mode 100644 apps/web/lib/ws/handlers/session-todos.ts diff --git a/apps/backend/cmd/kandev/adapters.go b/apps/backend/cmd/kandev/adapters.go index fc9349d395..026a4f6afb 100644 --- a/apps/backend/cmd/kandev/adapters.go +++ b/apps/backend/cmd/kandev/adapters.go @@ -213,6 +213,16 @@ func (a *lifecycleAdapter) RestartAgentProcess(ctx context.Context, agentExecuti return a.mgr.RestartAgentProcess(ctx, agentExecutionID) } +// ResetAgentContext resets the agent's context using the fastest available strategy. +func (a *lifecycleAdapter) ResetAgentContext(ctx context.Context, agentExecutionID string) error { + return a.mgr.ResetAgentContext(ctx, agentExecutionID) +} + +// SetSessionModelBySessionID attempts an in-place model switch via ACP session/set_model. +func (a *lifecycleAdapter) SetSessionModelBySessionID(ctx context.Context, sessionID, modelID string) error { + return a.mgr.SetSessionModelBySessionID(ctx, sessionID, modelID) +} + // RespondToPermissionBySessionID sends a response to a permission request for a session func (a *lifecycleAdapter) RespondToPermissionBySessionID(ctx context.Context, sessionID, pendingID, optionID string, cancelled bool) error { return a.mgr.RespondToPermissionBySessionID(sessionID, pendingID, optionID, cancelled) @@ -373,7 +383,7 @@ type messageCreatorAdapter struct { logger *logger.Logger // sessionModelCache caches the resolved model per session to avoid repeated DB lookups. - // The model doesn't change within a session, so caching is safe. + // Invalidated via InvalidateModelCache when the model changes (e.g., model switch). sessionModelMu sync.RWMutex sessionModelCache map[string]string } @@ -407,6 +417,14 @@ func (a *messageCreatorAdapter) getSessionModel(ctx context.Context, sessionID s return model } +// InvalidateModelCache clears the cached model for a session so the next message +// re-reads it from the DB. Called after model switches. +func (a *messageCreatorAdapter) InvalidateModelCache(sessionID string) { + a.sessionModelMu.Lock() + delete(a.sessionModelCache, sessionID) + a.sessionModelMu.Unlock() +} + // CreateAgentMessage creates a message with author_type="agent" func (a *messageCreatorAdapter) CreateAgentMessage(ctx context.Context, taskID, content, agentSessionID, turnID string) error { var metadata map[string]interface{} diff --git a/apps/backend/cmd/kandev/helpers.go b/apps/backend/cmd/kandev/helpers.go index 513d3d03b2..806b92e7bf 100644 --- a/apps/backend/cmd/kandev/helpers.go +++ b/apps/backend/cmd/kandev/helpers.go @@ -63,6 +63,8 @@ func buildSessionDataProvider(taskRepo *sqliterepo.Repository, lifecycleMgr *lif result = appendLiveGitStatusMessage(ctx, taskRepo, lifecycleMgr, sessionID, session, result, log) result = appendContextWindowMessage(sessionID, session, result) result = appendAvailableCommandsMessage(sessionID, session, lifecycleMgr, result) + result = appendSessionModeMessage(sessionID, session, lifecycleMgr, result) + result = appendSessionModelsMessage(sessionID, session, lifecycleMgr, result) return result, nil } } @@ -254,6 +256,49 @@ func appendAvailableCommandsMessage(sessionID string, session *models.TaskSessio return result } +// appendSessionModeMessage adds session mode state notification to result if cached. +func appendSessionModeMessage(sessionID string, session *models.TaskSession, lifecycleMgr *lifecycle.Manager, result []*ws.Message) []*ws.Message { + if lifecycleMgr == nil { + return result + } + modeState := lifecycleMgr.GetModeStateForSession(sessionID) + if modeState == nil || (modeState.CurrentModeID == "" && len(modeState.AvailableModes) == 0) { + return result + } + notification, err := ws.NewNotification(ws.ActionSessionModeChanged, lifecycle.SessionModeEventPayload{ + TaskID: session.TaskID, + SessionID: sessionID, + CurrentModeID: modeState.CurrentModeID, + AvailableModes: modeState.AvailableModes, + }) + if err == nil { + result = append(result, notification) + } + return result +} + +// appendSessionModelsMessage adds session models state notification to result if cached. +func appendSessionModelsMessage(sessionID string, session *models.TaskSession, lifecycleMgr *lifecycle.Manager, result []*ws.Message) []*ws.Message { + if lifecycleMgr == nil { + return result + } + modelState := lifecycleMgr.GetModelStateForSession(sessionID) + if modelState == nil || (modelState.CurrentModelID == "" && len(modelState.Models) == 0) { + return result + } + notification, err := ws.NewNotification(ws.ActionSessionModelsUpdated, lifecycle.SessionModelsEventPayload{ + TaskID: session.TaskID, + SessionID: sessionID, + CurrentModelID: modelState.CurrentModelID, + Models: modelState.Models, + ConfigOptions: modelState.ConfigOptions, + }) + if err == nil { + result = append(result, notification) + } + return result +} + // newMessageAddedHandler returns an event bus handler that broadcasts message.added events // to WebSocket subscribers. func newMessageAddedHandler(gateway *gateways.Gateway, log *logger.Logger) func(context.Context, *bus.Event) error { diff --git a/apps/backend/cmd/mock-agent/emitter.go b/apps/backend/cmd/mock-agent/emitter.go new file mode 100644 index 0000000000..f0464c0ddb --- /dev/null +++ b/apps/backend/cmd/mock-agent/emitter.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "fmt" + + acp "github.com/coder/acp-go-sdk" +) + +// sessionUpdater abstracts the ACP connection methods used by the emitter. +// The real acp.AgentSideConnection satisfies this; tests provide a mock. +type sessionUpdater interface { + SessionUpdate(ctx context.Context, n acp.SessionNotification) error + RequestPermission(ctx context.Context, p acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) +} + +// emitter wraps an ACP connection and session ID to provide +// convenient methods for streaming agent updates. +type emitter struct { + ctx context.Context + conn sessionUpdater + sid acp.SessionId +} + +// text sends an agent text message update. +func (e *emitter) text(msg string) { + _ = e.conn.SessionUpdate(e.ctx, acp.SessionNotification{ + SessionId: e.sid, + Update: acp.UpdateAgentMessageText(msg), + }) +} + +// thought sends an agent thinking/reasoning update. +func (e *emitter) thought(msg string) { + _ = e.conn.SessionUpdate(e.ctx, acp.SessionNotification{ + SessionId: e.sid, + Update: acp.UpdateAgentThoughtText(msg), + }) +} + +// startTool announces a new tool call. +func (e *emitter) startTool(id acp.ToolCallId, title string, kind acp.ToolKind, input any, locs ...acp.ToolCallLocation) { + opts := []acp.ToolCallStartOpt{ + acp.WithStartKind(kind), + acp.WithStartStatus(acp.ToolCallStatusPending), + acp.WithStartRawInput(input), + } + if len(locs) > 0 { + opts = append(opts, acp.WithStartLocations(locs)) + } + _ = e.conn.SessionUpdate(e.ctx, acp.SessionNotification{ + SessionId: e.sid, + Update: acp.StartToolCall(id, title, opts...), + }) +} + +// completeTool marks a tool call as completed with output. +func (e *emitter) completeTool(id acp.ToolCallId, output any) { + _ = e.conn.SessionUpdate(e.ctx, acp.SessionNotification{ + SessionId: e.sid, + Update: acp.UpdateToolCall(id, + acp.WithUpdateStatus(acp.ToolCallStatusCompleted), + acp.WithUpdateRawOutput(output), + ), + }) +} + +// requestPermission asks the client for permission to proceed with a tool call. +// Returns true if permission was granted, false otherwise. +func (e *emitter) requestPermission(toolCallID acp.ToolCallId, title string, kind acp.ToolKind, input any) bool { + resp, err := e.conn.RequestPermission(e.ctx, acp.RequestPermissionRequest{ + SessionId: e.sid, + ToolCall: acp.RequestPermissionToolCall{ + ToolCallId: toolCallID, + Title: acp.Ptr(title), + Kind: acp.Ptr(kind), + Status: acp.Ptr(acp.ToolCallStatusPending), + RawInput: input, + }, + Options: []acp.PermissionOption{ + {Kind: acp.PermissionOptionKindAllowOnce, Name: "Allow", OptionId: "allow"}, + {Kind: acp.PermissionOptionKindRejectOnce, Name: "Reject", OptionId: "reject"}, + }, + }) + if err != nil { + _, _ = fmt.Fprintf(logOutput, "mock-agent: permission request failed: %v\n", err) + return false + } + return resp.Outcome.Selected != nil && string(resp.Outcome.Selected.OptionId) == "allow" +} diff --git a/apps/backend/cmd/mock-agent/handler.go b/apps/backend/cmd/mock-agent/handler.go index d10c2b3e07..d12a671d7c 100644 --- a/apps/backend/cmd/mock-agent/handler.go +++ b/apps/backend/cmd/mock-agent/handler.go @@ -1,8 +1,6 @@ package main import ( - "bufio" - "encoding/json" "fmt" "math/rand" "os" @@ -45,129 +43,68 @@ func stripKandevSystem(prompt string) string { return strings.TrimSpace(prompt[idx+len(endTag):]) } -// handleUserPrompt routes a user prompt to the appropriate sequence generator. -func handleUserPrompt(enc *json.Encoder, scanner *bufio.Scanner, prompt, model string) { +// handlePrompt routes a user prompt to the appropriate sequence generator. +func handlePrompt(e *emitter, prompt, model string) { prompt = strings.TrimSpace(prompt) // Extract the user-facing content for command routing. - // The backend wraps prompts with ... context; - // routing should match the user's actual command regardless of that wrapper. - // The full prompt (including any kandev-system content) is kept available via - // the outer variable so future scenarios can inspect it if needed. cmd := stripKandevSystem(prompt) - // Emit system message at the start of every turn - emitSystemMessage(enc) - // Script mode: each line is a command (e2e:message, e2e:mcp:*, etc.) if isScriptMode(cmd) { - executeScript(enc, prompt, cmd) - emitResult(enc, false, "") + executeScript(e, prompt, cmd) return } - // Some commands emit their own result; track whether we need the default one. - customResult := false - switch { case strings.EqualFold(cmd, "all") || strings.EqualFold(cmd, "/all"): - emitAllTypes(enc, scanner, model) + emitAllTypes(e, model) case strings.EqualFold(cmd, "/error"): - emitError(enc, model) - customResult = true + emitError(e, model) case strings.EqualFold(cmd, "/slow") || strings.HasPrefix(strings.ToLower(cmd), "/slow "): - emitSlowResponse(enc, scanner, cmd, model) + emitSlowResponse(e, cmd, model) case strings.EqualFold(cmd, "/thinking"): - emitThinkingSequence(enc, model) + emitThinkingSequence(e, model) case strings.HasPrefix(cmd, "/tool:"): toolName := strings.TrimPrefix(cmd, "/tool:") - emitSpecificTool(enc, scanner, strings.TrimSpace(toolName), model) + emitSpecificTool(e, strings.TrimSpace(toolName), model) case strings.HasPrefix(cmd, "/subagent"): - emitSubagentSequence(enc, scanner, model) + emitSubagentSequence(e, model) case strings.HasPrefix(cmd, "/e2e:"): rest := strings.TrimPrefix(cmd, "/e2e:") scenarioName, _, _ := strings.Cut(strings.TrimSpace(rest), " ") - emitPredefinedScenario(enc, scanner, scenarioName) - // e2e:error emits its own result - if strings.TrimSpace(scenarioName) == "error" { - customResult = true - } + emitPredefinedScenario(e, scenarioName) case strings.EqualFold(cmd, "/crash"): - emitCrash(enc, model) - return // process exits, no result needed + emitCrash(e, model) case strings.HasPrefix(cmd, "/todo"): - emitTodoSequence(enc, model) + emitTodoSequence(e, model) case strings.EqualFold(cmd, "/mermaid"): - emitMermaidSequence(enc, model) + emitMermaidSequence(e, model) default: - emitRandomResponse(enc, scanner, cmd, model) - } - - if !customResult { - emitResult(enc, false, "") + emitRandomResponse(e, cmd, model) } } -// emitSystemMessage writes the system message to stdout. -func emitSystemMessage(enc *json.Encoder) { - _ = enc.Encode(SystemMsg{ - Type: TypeSystem, - SessionID: sessionID, - SessionStatus: "active", - }) -} - -// emitResult writes the final result message to stdout. -func emitResult(enc *json.Encoder, isError bool, errText string) { - var resultJSON json.RawMessage - if isError { - resultJSON, _ = json.Marshal(errText) - } else { - resultJSON, _ = json.Marshal(ResultData{ - Text: "Mock agent completed successfully.", - SessionID: sessionID, - }) - } - - _ = enc.Encode(ResultMsg{ - Type: TypeResult, - Result: resultJSON, - CostUSD: 0.0042, - DurationMS: 1500, - DurationAPIMS: 1200, - IsError: isError, - NumTurns: 1, - TotalInputTokens: 1500, - TotalOutputTokens: 500, - ModelUsage: map[string]ModelUsageStats{ - "mock-default": {ContextWindow: 200000}, - }, - }) -} - -// emitError emits an error result. -func emitError(enc *json.Encoder, model string) { +// emitError emits an error message. +func emitError(e *emitter, model string) { randomDelay(model) - emitTextBlock(enc, "Simulating an error condition...", "") + e.text("Simulating an error condition...") randomDelay(model) - emitResult(enc, true, "Mock error: something went wrong during processing") - // Return without emitting the normal result (handler skips the final emitResult - // because we already emitted one). We handle this by making the caller check. + e.text("Mock error: something went wrong during processing") } // emitCrash simulates an agent crash by exiting with code 1 after emitting // some output. Useful for testing recovery flows. -func emitCrash(enc *json.Encoder, model string) { +func emitCrash(e *emitter, model string) { randomDelay(model) - emitTextBlock(enc, "Processing your request...", "") + e.text("Processing your request...") randomDelay(model) fmt.Fprintln(os.Stderr, "mock-agent: simulating crash (exit 1)") os.Exit(1) } // emitSlowResponse generates a response with configurable total duration. -// Accepts "/slow" (defaults to 5s) or "/slow " (e.g. "/slow 60s", "/slow 2m"). -func emitSlowResponse(enc *json.Encoder, _ *bufio.Scanner, prompt, model string) { +func emitSlowResponse(e *emitter, prompt, model string) { totalDuration := 5 * time.Second parts := strings.Fields(prompt) if len(parts) >= 2 { @@ -176,38 +113,37 @@ func emitSlowResponse(enc *json.Encoder, _ *bufio.Scanner, prompt, model string) } } - // Divide total duration into steps steps := 5 stepDelay := totalDuration / time.Duration(steps) - emitThinking(enc, model) + emitThinking(e, model) time.Sleep(stepDelay) - emitTextBlock(enc, fmt.Sprintf("Running slow response (%s total)...", totalDuration), "") + e.text(fmt.Sprintf("Running slow response (%s total)...", totalDuration)) time.Sleep(stepDelay) - emitReadFile(enc, model) + emitReadFile(e, model) time.Sleep(stepDelay) - emitCodeSearch(enc, model) + emitCodeSearch(e, model) time.Sleep(stepDelay) - emitTextBlock(enc, fmt.Sprintf("Slow response complete after %s.", totalDuration), "") + e.text(fmt.Sprintf("Slow response complete after %s.", totalDuration)) time.Sleep(stepDelay) } // emitRandomResponse generates a random mix of 2-5 events. -func emitRandomResponse(enc *json.Encoder, _ *bufio.Scanner, prompt, model string) { +func emitRandomResponse(e *emitter, prompt, model string) { generators := []func(){ - func() { emitThinking(enc, model) }, - func() { emitTextBlock(enc, "I'll help you with that. Let me look into it.", "") }, - func() { emitReadFile(enc, model) }, - func() { emitCodeSearch(enc, model) }, - func() { emitWebFetch(enc, model) }, + func() { emitThinking(e, model) }, + func() { e.text("I'll help you with that. Let me look into it.") }, + func() { emitReadFile(e, model) }, + func() { emitCodeSearch(e, model) }, + func() { emitWebFetch(e, model) }, } // Always start with thinking - emitThinking(enc, model) + emitThinking(e, model) randomDelay(model) // Pick 1-4 more random events @@ -219,34 +155,34 @@ func emitRandomResponse(enc *json.Encoder, _ *bufio.Scanner, prompt, model strin } // End with a text summary - emitTextBlock(enc, "I've completed the analysis of your request: \""+prompt+"\". Everything looks good!", "") + e.text("I've completed the analysis of your request: \"" + prompt + "\". Everything looks good!") } // emitAllTypes emits one of every message type. -func emitAllTypes(enc *json.Encoder, scanner *bufio.Scanner, model string) { - emitThinking(enc, model) +func emitAllTypes(e *emitter, model string) { + emitThinking(e, model) randomDelay(model) - emitTextBlock(enc, "Starting comprehensive demonstration of all message types...", "") + e.text("Starting comprehensive demonstration of all message types...") randomDelay(model) - emitReadFile(enc, model) + emitReadFile(e, model) randomDelay(model) - emitEditFile(enc, scanner, model) + emitEditFile(e, model) randomDelay(model) - emitShellExec(enc, scanner, model) + emitShellExec(e, model) randomDelay(model) - emitCodeSearch(enc, model) + emitCodeSearch(e, model) randomDelay(model) - emitSubagent(enc, scanner, model) + emitSubagent(e, model) randomDelay(model) - emitTodo(enc, model) + emitTodo(e, model) randomDelay(model) - emitWebFetch(enc, model) + emitWebFetch(e, model) randomDelay(model) - emitTextBlock(enc, "All message types demonstrated successfully!", "") + e.text("All message types demonstrated successfully!") } // emitThinkingSequence emits extended thinking/reasoning blocks. -func emitThinkingSequence(enc *json.Encoder, model string) { +func emitThinkingSequence(e *emitter, model string) { thoughts := []string{ "Let me analyze this problem step by step...", "First, I need to consider the architecture and how the components interact.", @@ -257,49 +193,49 @@ func emitThinkingSequence(enc *json.Encoder, model string) { for _, thought := range thoughts { randomDelay(model) - emitThinkingBlock(enc, thought, "") + e.thought(thought) } randomDelay(model) - emitTextBlock(enc, "After careful reasoning, here is my analysis:\n\n1. The architecture is sound\n2. Error handling covers edge cases\n3. The implementation follows Go best practices", "") + e.text("After careful reasoning, here is my analysis:\n\n1. The architecture is sound\n2. Error handling covers edge cases\n3. The implementation follows Go best practices") } // emitSpecificTool emits a single specific tool call. -func emitSpecificTool(enc *json.Encoder, scanner *bufio.Scanner, toolName, model string) { +func emitSpecificTool(e *emitter, toolName, model string) { switch strings.ToLower(toolName) { case "read": - emitReadFile(enc, model) + emitReadFile(e, model) case "edit": - emitEditFile(enc, scanner, model) + emitEditFile(e, model) case "exec", "bash": - emitShellExec(enc, scanner, model) + emitShellExec(e, model) case "search", "grep": - emitCodeSearch(enc, model) + emitCodeSearch(e, model) case "webfetch", "web": - emitWebFetch(enc, model) + emitWebFetch(e, model) default: - emitTextBlock(enc, "Unknown tool: "+toolName+". Available: read, edit, exec, search, webfetch", "") + e.text("Unknown tool: " + toolName + ". Available: read, edit, exec, search, webfetch") } } // emitTodoSequence emits a todo management sequence. -func emitTodoSequence(enc *json.Encoder, model string) { - emitThinking(enc, model) +func emitTodoSequence(e *emitter, model string) { + emitThinking(e, model) randomDelay(model) - emitTextBlock(enc, "I'll create a task list for this work.", "") + e.text("I'll create a task list for this work.") randomDelay(model) - emitTodo(enc, model) + emitTodo(e, model) randomDelay(model) - emitTextBlock(enc, "Task list has been updated.", "") + e.text("Task list has been updated.") } // emitSubagentSequence emits a subagent Task sequence. -func emitSubagentSequence(enc *json.Encoder, scanner *bufio.Scanner, model string) { - emitThinking(enc, model) +func emitSubagentSequence(e *emitter, model string) { + emitThinking(e, model) randomDelay(model) - emitTextBlock(enc, "I'll delegate this to a subagent for parallel processing.", "") + e.text("I'll delegate this to a subagent for parallel processing.") randomDelay(model) - emitSubagent(enc, scanner, model) + emitSubagent(e, model) randomDelay(model) - emitTextBlock(enc, "Subagent task completed successfully.", "") + e.text("Subagent task completed successfully.") } diff --git a/apps/backend/cmd/mock-agent/main.go b/apps/backend/cmd/mock-agent/main.go index dce55c0d16..1d41bb1d75 100644 --- a/apps/backend/cmd/mock-agent/main.go +++ b/apps/backend/cmd/mock-agent/main.go @@ -1,21 +1,23 @@ -// Package main implements a mock agent binary that speaks the claude-code -// stream-json protocol over stdin/stdout. It generates simulated responses -// for rapid feature testing and e2e web app tests. +// Package main implements a mock agent binary that speaks the ACP +// (Agent Client Protocol) over stdin/stdout. It generates simulated +// responses for rapid feature testing and e2e web app tests. package main import ( - "bufio" + "context" "encoding/json" "fmt" + "io" "os" "slices" "strings" + "sync" + + acp "github.com/coder/acp-go-sdk" ) -// sessionID is a unique identifier for this mock-agent process instance. -// Each session spawns its own process, so using PID ensures uniqueness -// across parallel sessions. -var sessionID = fmt.Sprintf("mock-session-%d", os.Getpid()) +// logOutput is the writer for log messages (stderr). Tests can override this. +var logOutput io.Writer = os.Stderr // mcpServerDef describes an MCP server endpoint parsed from --mcp-config. type mcpServerDef struct { @@ -26,18 +28,20 @@ type mcpServerDef struct { // mcpServers holds MCP server definitions from --mcp-config. var mcpServers map[string]mcpServerDef +// mockAgent implements the acp.Agent interface for the mock agent. +type mockAgent struct { + conn *acp.AgentSideConnection + model string + sessions map[acp.SessionId]bool + mu sync.Mutex +} + func main() { model := parseModelFlag() - // Override sessionID when resuming a previous session. - resumeID := parseResumeFlag() - if resumeID != "" { - sessionID = resumeID - fmt.Fprintf(os.Stderr, "mock-agent[%d]: resuming session %s\n", os.Getpid(), resumeID) - } - // TUI mode: simple terminal UI for passthrough/PTY testing if parseTUIFlag() { + resumeID := parseResumeFlag() resumed := resumeID != "" || parseContinueFlag() runTUI(model, parsePromptFlag(), resumed) return @@ -46,41 +50,85 @@ func main() { mcpServers = parseMCPConfigFlag() defer closeMCPClients() - scanner := bufio.NewScanner(os.Stdin) - buf := make([]byte, 0, 64*1024) - scanner.Buffer(buf, 10*1024*1024) - - enc := json.NewEncoder(os.Stdout) - - for scanner.Scan() { - line := scanner.Bytes() - if len(line) == 0 { - continue - } - - var msg IncomingMessage - if err := json.Unmarshal(line, &msg); err != nil { - fmt.Fprintf(os.Stderr, "mock-agent[%d]: unmarshal error: %v (line=%s)\n", os.Getpid(), err, string(line[:min(200, len(line))])) - continue - } - - switch msg.Type { - case TypeControlRequest: - fmt.Fprintf(os.Stderr, "mock-agent[%d]: control_request (request_id=%s)\n", os.Getpid(), msg.RequestID) - handleControlRequest(enc, msg) - case TypeUser: - if msg.Message != nil { - handleUserPrompt(enc, scanner, msg.Message.Content, model) - } - } + ag := &mockAgent{ + model: model, + sessions: make(map[acp.SessionId]bool), } + asc := acp.NewAgentSideConnection(ag, os.Stdout, os.Stdin) + ag.conn = asc - if err := scanner.Err(); err != nil { - fmt.Fprintf(os.Stderr, "mock-agent: scanner error: %v\n", err) - os.Exit(1) - } + <-asc.Done() } +// Initialize handles the ACP initialize request, returning agent capabilities. +func (a *mockAgent) Initialize(_ context.Context, _ acp.InitializeRequest) (acp.InitializeResponse, error) { + return acp.InitializeResponse{ + ProtocolVersion: acp.ProtocolVersionNumber, + AgentCapabilities: acp.AgentCapabilities{ + LoadSession: true, + McpCapabilities: acp.McpCapabilities{Sse: true}, + }, + }, nil +} + +// NewSession creates a new conversation session. +// MCP servers from the ACP request are registered so callMCPTool can use them. +func (a *mockAgent) NewSession(_ context.Context, req acp.NewSessionRequest) (acp.NewSessionResponse, error) { + sid := acp.SessionId(fmt.Sprintf("mock-session-%d", os.Getpid())) + a.mu.Lock() + a.sessions[sid] = true + a.mu.Unlock() + + // Register MCP servers from the ACP session request (SSE servers). + // This bridges ACP protocol MCP config to the mock agent's MCP client. + registerACPMcpServers(req.McpServers) + + return acp.NewSessionResponse{SessionId: sid}, nil +} + +// LoadSession restores a previous session for resume. +func (a *mockAgent) LoadSession(_ context.Context, req acp.LoadSessionRequest) (acp.LoadSessionResponse, error) { + a.mu.Lock() + a.sessions[req.SessionId] = true + a.mu.Unlock() + _, _ = fmt.Fprintf(logOutput, "mock-agent[%d]: resumed session %s\n", os.Getpid(), req.SessionId) + return acp.LoadSessionResponse{}, nil +} + +// Prompt processes a user message and streams responses via SessionUpdate. +func (a *mockAgent) Prompt(ctx context.Context, req acp.PromptRequest) (acp.PromptResponse, error) { + prompt := extractPromptText(req.Prompt) + e := &emitter{ctx: ctx, conn: a.conn, sid: req.SessionId} + handlePrompt(e, prompt, a.model) + return acp.PromptResponse{StopReason: acp.StopReasonEndTurn}, nil +} + +// Cancel handles session cancellation. +func (a *mockAgent) Cancel(_ context.Context, _ acp.CancelNotification) error { return nil } + +// Authenticate handles auth requests (no-op for mock). +func (a *mockAgent) Authenticate(_ context.Context, _ acp.AuthenticateRequest) (acp.AuthenticateResponse, error) { + return acp.AuthenticateResponse{}, nil +} + +// SetSessionMode handles mode changes (no-op for mock). +func (a *mockAgent) SetSessionMode(_ context.Context, _ acp.SetSessionModeRequest) (acp.SetSessionModeResponse, error) { + return acp.SetSessionModeResponse{}, nil +} + +// extractPromptText concatenates text content blocks from the prompt. +func extractPromptText(blocks []acp.ContentBlock) string { + var parts []string + for _, b := range blocks { + if b.Text != nil { + parts = append(parts, b.Text.Text) + } + } + return strings.Join(parts, "\n") +} + +// --- Flag parsing (unchanged) --- + // parseModelFlag extracts --model value from command line args. func parseModelFlag() string { return parseModelFromArgs(os.Args) @@ -137,7 +185,7 @@ func parseMCPConfigFlag() map[string]mcpServerDef { } var payload mcpConfigPayload if err := json.Unmarshal([]byte(raw), &payload); err != nil { - fmt.Fprintf(os.Stderr, "mock-agent: failed to parse --mcp-config: %v\n", err) + _, _ = fmt.Fprintf(logOutput, "mock-agent: failed to parse --mcp-config: %v\n", err) return nil } return payload.MCPServers @@ -155,45 +203,3 @@ func parseMCPConfigFromArgs(args []string) string { } return "" } - -// handleControlRequest responds to control requests from the backend. -func handleControlRequest(enc *json.Encoder, msg IncomingMessage) { - // We only handle the initialize request from the backend - if msg.RequestID != "" { - resp := ControlResponseMsg{ - Type: TypeControlResponse, - Response: ControlResponseBody{ - Subtype: "success", - RequestID: msg.RequestID, - Response: &InitializeResponse{ - Commands: []Command{ - {Name: "all", Description: "Demo all message types"}, - {Name: "error", Description: "Simulate an error result"}, - {Name: "slow", Description: "Random response with slow delays", ArgumentHint: ""}, - {Name: "thinking", Description: "Extended thinking/reasoning blocks"}, - {Name: "tool:read", Description: "Single file read"}, - {Name: "tool:edit", Description: "Single file edit (with permission)"}, - {Name: "tool:exec", Description: "Single shell command (with permission)"}, - {Name: "tool:search", Description: "Single code search"}, - {Name: "tool:webfetch", Description: "Single web fetch"}, - {Name: "subagent", Description: "Subagent Task with nested child messages"}, - {Name: "todo", Description: "Todo management sequence"}, - {Name: "mermaid", Description: "Rich markdown with mermaid diagrams"}, - {Name: "e2e:simple-message", Description: "E2E: text only, fixed timing"}, - {Name: "e2e:read-and-edit", Description: "E2E: read + edit + text"}, - {Name: "e2e:permission-flow", Description: "E2E: tool requiring permission"}, - {Name: "e2e:error", Description: "E2E: error result"}, - {Name: "e2e:subagent", Description: "E2E: subagent with child messages"}, - {Name: "e2e:all-tools", Description: "E2E: one of each tool type"}, - {Name: "e2e:multi-turn", Description: "E2E: minimal multi-turn response"}, - {Name: "e2e:clarification", Description: "E2E: ask clarification question via MCP (happy path)"}, - {Name: "e2e:clarification-timeout", Description: "E2E: ask clarification with 5s timeout (fallback path)"}, - {Name: "e2e:*", Description: "E2E: scripted commands (e2e:message, e2e:mcp:*, etc.)"}, - }, - Agents: []string{"Bash", "Read", "Edit", "Grep", "Glob", "Task"}, - }, - }, - } - _ = enc.Encode(resp) - } -} diff --git a/apps/backend/cmd/mock-agent/mcp_client.go b/apps/backend/cmd/mock-agent/mcp_client.go index 9a17f9478b..be00d69dd4 100644 --- a/apps/backend/cmd/mock-agent/mcp_client.go +++ b/apps/backend/cmd/mock-agent/mcp_client.go @@ -6,6 +6,7 @@ import ( "strings" "sync" + acp "github.com/coder/acp-go-sdk" mcpclient "github.com/mark3labs/mcp-go/client" "github.com/mark3labs/mcp-go/mcp" ) @@ -94,6 +95,20 @@ func extractMCPResultText(result *mcp.CallToolResult) string { return strings.Join(parts, "\n") } +// registerACPMcpServers adds SSE MCP servers from an ACP NewSessionRequest +// to the global mcpServers map so callMCPTool can reach them. +func registerACPMcpServers(servers []acp.McpServer) { + for _, s := range servers { + if s.Sse != nil && s.Sse.Name != "" && s.Sse.Url != "" { + if mcpServers == nil { + mcpServers = make(map[string]mcpServerDef) + } + mcpServers[s.Sse.Name] = mcpServerDef{URL: s.Sse.Url, Type: "sse"} + _, _ = fmt.Fprintf(logOutput, "mock-agent: registered ACP MCP server %s at %s\n", s.Sse.Name, s.Sse.Url) + } + } +} + // closeMCPClients closes all open MCP clients (called on shutdown). func closeMCPClients() { mcpClientsMu.Lock() diff --git a/apps/backend/cmd/mock-agent/permission.go b/apps/backend/cmd/mock-agent/permission.go deleted file mode 100644 index 751b179b5d..0000000000 --- a/apps/backend/cmd/mock-agent/permission.go +++ /dev/null @@ -1,48 +0,0 @@ -package main - -import ( - "bufio" - "encoding/json" - "fmt" -) - -// requestPermission sends a control_request for tool permission and waits for the response. -// Returns true if permission was granted, false if denied. -func requestPermission(enc *json.Encoder, scanner *bufio.Scanner, toolName, toolUseID string, input map[string]any) bool { - requestID := fmt.Sprintf("mock-perm-%s-%s", toolName, toolUseID) - - // Emit control_request to stdout - _ = enc.Encode(ControlRequestMsg{ - Type: TypeControlRequest, - RequestID: requestID, - Request: ControlRequestBody{ - Subtype: "can_use_tool", - ToolName: toolName, - Input: input, - ToolUseID: toolUseID, - }, - }) - - // Read stdin for control_response - for scanner.Scan() { - line := scanner.Bytes() - if len(line) == 0 { - continue - } - - var msg IncomingMessage - if err := json.Unmarshal(line, &msg); err != nil { - continue - } - - if msg.Type == TypeControlResponse && msg.Response != nil { - if msg.Response.Result != nil { - return msg.Response.Result.Behavior == "allow" - } - // Error response means denied - return false - } - } - - return false -} diff --git a/apps/backend/cmd/mock-agent/scenarios.go b/apps/backend/cmd/mock-agent/scenarios.go index f23e7b9581..375e9db1a8 100644 --- a/apps/backend/cmd/mock-agent/scenarios.go +++ b/apps/backend/cmd/mock-agent/scenarios.go @@ -1,86 +1,56 @@ package main import ( - "bufio" "context" - "encoding/json" "fmt" "os" "os/exec" "strings" "time" + + acp "github.com/coder/acp-go-sdk" ) // Predefined e2e test scenarios with fixed timing for deterministic test assertions. +// scenarioRegistry maps scenario names to their handler functions. +var scenarioRegistry = map[string]func(e *emitter){ + "simple-message": scenarioSimpleMessage, + "read-and-edit": scenarioReadAndEdit, + "permission-flow": scenarioPermissionFlow, + "error": scenarioError, + "subagent": scenarioSubagent, + "all-tools": scenarioAllTools, + "multi-turn": scenarioMultiTurn, + "diff-expansion-setup": scenarioDiffExpansionSetup, + "diff-update-setup": scenarioDiffUpdateSetup, + "diff-update-modify": scenarioDiffUpdateModify, + "untracked-file-setup": scenarioUntrackedFileSetup, + "untracked-file-modify": scenarioUntrackedFileModify, + "clarification": scenarioClarification, + "clarification-timeout": scenarioClarificationTimeout, +} + // emitPredefinedScenario dispatches to a named e2e scenario. -func emitPredefinedScenario(enc *json.Encoder, scanner *bufio.Scanner, name string) { - switch name { - case "simple-message": - scenarioSimpleMessage(enc) - case "read-and-edit": - scenarioReadAndEdit(enc, scanner) - case "permission-flow": - scenarioPermissionFlow(enc, scanner) - case "error": - scenarioError(enc) - case "subagent": - scenarioSubagent(enc, scanner) - case "all-tools": - scenarioAllTools(enc, scanner) - case "multi-turn": - scenarioMultiTurn(enc) - case "diff-expansion-setup": - scenarioDiffExpansionSetup(enc) - case "diff-update-setup": - scenarioDiffUpdateSetup(enc) - case "diff-update-modify": - scenarioDiffUpdateModify(enc) - case "untracked-file-setup": - scenarioUntrackedFileSetup(enc) - case "untracked-file-modify": - scenarioUntrackedFileModify(enc) - case "clarification": - scenarioClarification(enc) - case "clarification-timeout": - scenarioClarificationTimeout(enc) - default: - emitTextBlock(enc, "Unknown e2e scenario: "+name+". Available: simple-message, read-and-edit, permission-flow, error, subagent, all-tools, multi-turn, diff-expansion-setup, diff-update-setup, diff-update-modify, untracked-file-setup, untracked-file-modify, clarification, clarification-timeout", "") +func emitPredefinedScenario(e *emitter, name string) { + if fn, ok := scenarioRegistry[name]; ok { + fn(e) + } else { + e.text("Unknown e2e scenario: " + name + ". Available: simple-message, read-and-edit, permission-flow, error, subagent, all-tools, multi-turn, diff-expansion-setup, diff-update-setup, diff-update-modify, untracked-file-setup, untracked-file-modify, clarification, clarification-timeout") } } // scenarioSimpleMessage: text only with fixed 100ms delays. -func scenarioSimpleMessage(enc *json.Encoder) { +func scenarioSimpleMessage(e *emitter) { fixedDelay(100) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockThinking, Thinking: "Processing the request..."}, - }, - Model: "mock-default", - Usage: defaultUsage(), - }, - }) + e.thought("Processing the request...") fixedDelay(100) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockText, Text: "This is a simple mock response for e2e testing."}, - }, - Model: "mock-default", - StopReason: "end_turn", - Usage: defaultUsage(), - }, - }) + e.text("This is a simple mock response for e2e testing.") } // scenarioReadAndEdit: read -> edit -> text with fixed delays, using real files. -func scenarioReadAndEdit(enc *json.Encoder, scanner *bufio.Scanner) { +func scenarioReadAndEdit(e *emitter) { f := randomFile() snippet := readFileSnippet(f.absPath, 20) oldStr, newStr := pickEditableFragment(f.absPath) @@ -88,29 +58,11 @@ func scenarioReadAndEdit(enc *json.Encoder, scanner *bufio.Scanner) { // Read file readID := nextToolID() - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockToolUse, ID: readID, Name: ToolRead, Input: map[string]any{"file_path": f.absPath}}, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) - + e.startTool(readID, "Read "+f.relPath, acp.ToolKindRead, + map[string]any{"file_path": f.absPath}, + acp.ToolCallLocation{Path: f.absPath}) fixedDelay(50) - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - {Type: BlockToolResult, ToolUseID: readID, Content: snippet}, - }, - }, - }) + e.completeTool(readID, map[string]any{"content": snippet}) fixedDelay(50) @@ -121,42 +73,25 @@ func scenarioReadAndEdit(enc *json.Encoder, scanner *bufio.Scanner) { "old_string": oldStr, "new_string": newStr, } - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockToolUse, ID: editID, Name: ToolEdit, Input: editInput}, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(editID, "Edit "+f.relPath, acp.ToolKindEdit, editInput, + acp.ToolCallLocation{Path: f.absPath}) - allowed := requestPermission(enc, scanner, ToolEdit, editID, editInput) + allowed := e.requestPermission(editID, "Edit "+f.relPath, acp.ToolKindEdit, editInput) fixedDelay(50) if allowed { - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - {Type: BlockToolResult, ToolUseID: editID, Content: "File edited successfully: " + f.absPath}, - }, - }, - }) + e.completeTool(editID, map[string]any{"result": "File edited successfully: " + f.absPath}) } else { - emitTextBlock(enc, "Edit was denied.", "") + e.completeTool(editID, map[string]any{"result": "Edit was denied"}) + e.text("Edit was denied.") } fixedDelay(50) - emitTextBlock(enc, "Read and edit scenario complete.", "") + e.text("Read and edit scenario complete.") } // scenarioPermissionFlow: tool requiring permission with fixed delays. -func scenarioPermissionFlow(enc *json.Encoder, scanner *bufio.Scanner) { +func scenarioPermissionFlow(e *emitter) { fixedDelay(50) bashID := nextToolID() @@ -165,90 +100,51 @@ func scenarioPermissionFlow(enc *json.Encoder, scanner *bufio.Scanner) { "description": "Test permission flow", } - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockToolUse, ID: bashID, Name: ToolBash, Input: bashInput}, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(bashID, "Test permissions", acp.ToolKindExecute, bashInput) - allowed := requestPermission(enc, scanner, ToolBash, bashID, bashInput) + allowed := e.requestPermission(bashID, "Test permissions", acp.ToolKindExecute, bashInput) fixedDelay(50) if allowed { - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - {Type: BlockToolResult, ToolUseID: bashID, Content: "testing permissions"}, - }, - }, - }) - emitTextBlock(enc, "Permission was granted and command executed.", "") + e.completeTool(bashID, map[string]any{"output": "testing permissions"}) + e.text("Permission was granted and command executed.") } else { - emitTextBlock(enc, "Permission was denied.", "") + e.completeTool(bashID, map[string]any{"output": "Permission denied"}) + e.text("Permission was denied.") } } // scenarioError: error result with fixed delays. -func scenarioError(enc *json.Encoder) { +func scenarioError(e *emitter) { fixedDelay(100) - emitTextBlock(enc, "About to encounter an error...", "") + e.text("About to encounter an error...") fixedDelay(100) - emitResult(enc, true, "E2E test error: simulated failure") + e.text("E2E test error: simulated failure") } // scenarioSubagent: subagent with child messages and fixed delays. -func scenarioSubagent(enc *json.Encoder, scanner *bufio.Scanner) { +func scenarioSubagent(e *emitter) { taskToolID := nextToolID() fixedDelay(50) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockToolUse, ID: taskToolID, Name: ToolTask, Input: map[string]any{ - "description": "E2E subagent test", - "prompt": "Run e2e subagent scenario", - }}, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(taskToolID, "E2E subagent test", acp.ToolKindOther, + map[string]any{ + "description": "E2E subagent test", + "prompt": "Run e2e subagent scenario", + }) fixedDelay(50) - _ = enc.Encode(SystemMsg{Type: TypeSystem, SessionID: sessionID, SessionStatus: "active"}) + e.text("Subagent working on the task...") fixedDelay(50) - emitTextBlock(enc, "Subagent working on the task...", taskToolID) + e.completeTool(taskToolID, map[string]any{"result": "E2E subagent completed"}) fixedDelay(50) - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - {Type: BlockToolResult, ToolUseID: taskToolID, Content: "E2E subagent completed"}, - }, - }, - }) - - fixedDelay(50) - emitTextBlock(enc, "Subagent scenario complete.", "") + e.text("Subagent scenario complete.") } // scenarioAllTools: one of each tool type with fixed delays, using real files. -func scenarioAllTools(enc *json.Encoder, scanner *bufio.Scanner) { +func scenarioAllTools(e *emitter) { used := map[string]bool{} readFile := randomFile() used[readFile.absPath] = true @@ -257,131 +153,97 @@ func scenarioAllTools(enc *json.Encoder, scanner *bufio.Scanner) { editFile := randomFileExcluding(used) fixedDelay(50) - emitThinkingBlock(enc, "Running all tools...", "") + e.thought("Running all tools...") - scenarioAllToolsReadGrep(enc, readFile, grepFile) - scenarioAllToolsEditBash(enc, scanner, editFile) + scenarioAllToolsReadGrep(e, readFile, grepFile) + scenarioAllToolsEditBash(e, editFile) // WebFetch fixedDelay(50) webID := nextToolID() - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{{Type: BlockToolUse, ID: webID, Name: ToolWebFetch, Input: map[string]any{"url": "https://example.com", "prompt": "Summarize"}}}, - Model: "mock-default", StopReason: "tool_use", Usage: defaultUsage(), - }, - }) + e.startTool(webID, "Fetch example.com", acp.ToolKindFetch, + map[string]any{"url": "https://example.com", "prompt": "Summarize"}) fixedDelay(50) - _ = enc.Encode(UserMsg{Type: TypeUser, Message: UserMsgBody{Role: "user", Content: []ContentBlock{{Type: BlockToolResult, ToolUseID: webID, Content: "Example page content"}}}}) + e.completeTool(webID, map[string]any{"content": "Example page content"}) fixedDelay(50) - emitTextBlock(enc, "All tools scenario complete.", "") + e.text("All tools scenario complete.") } -func scenarioAllToolsReadGrep(enc *json.Encoder, readFile, grepFile fileInfo) { +func scenarioAllToolsReadGrep(e *emitter, readFile, grepFile fileInfo) { // Read fixedDelay(50) readID := nextToolID() snippet := readFileSnippet(readFile.absPath, 20) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{{Type: BlockToolUse, ID: readID, Name: ToolRead, Input: map[string]any{"file_path": readFile.absPath}}}, - Model: "mock-default", StopReason: "tool_use", Usage: defaultUsage(), - }, - }) + e.startTool(readID, "Read "+readFile.relPath, acp.ToolKindRead, + map[string]any{"file_path": readFile.absPath}, + acp.ToolCallLocation{Path: readFile.absPath}) fixedDelay(50) - _ = enc.Encode(UserMsg{Type: TypeUser, Message: UserMsgBody{Role: "user", Content: []ContentBlock{{Type: BlockToolResult, ToolUseID: readID, Content: snippet}}}}) + e.completeTool(readID, map[string]any{"content": snippet}) // Grep fixedDelay(50) grepID := nextToolID() - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{{Type: BlockToolUse, ID: grepID, Name: ToolGrep, Input: map[string]any{"pattern": "func ", "path": grepFile.absPath}}}, - Model: "mock-default", StopReason: "tool_use", Usage: defaultUsage(), - }, - }) + e.startTool(grepID, "Search for \"func \"", acp.ToolKindSearch, + map[string]any{"pattern": "func ", "path": grepFile.absPath}) fixedDelay(50) paths := randomFilePaths(3) var grepResults []string for i, p := range paths { grepResults = append(grepResults, fmt.Sprintf("%s:%d: func found here", p, (i+1)*10)) } - _ = enc.Encode(UserMsg{Type: TypeUser, Message: UserMsgBody{Role: "user", Content: []ContentBlock{{Type: BlockToolResult, ToolUseID: grepID, Content: strings.Join(grepResults, "\n")}}}}) + e.completeTool(grepID, map[string]any{"matches": strings.Join(grepResults, "\n")}) } -func scenarioAllToolsEditBash(enc *json.Encoder, scanner *bufio.Scanner, editFile fileInfo) { +func scenarioAllToolsEditBash(e *emitter, editFile fileInfo) { // Edit (with permission) fixedDelay(50) editID := nextToolID() oldStr, newStr := pickEditableFragment(editFile.absPath) editInput := map[string]any{"file_path": editFile.absPath, "old_string": oldStr, "new_string": newStr} - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{{Type: BlockToolUse, ID: editID, Name: ToolEdit, Input: editInput}}, - Model: "mock-default", StopReason: "tool_use", Usage: defaultUsage(), - }, - }) - allowed := requestPermission(enc, scanner, ToolEdit, editID, editInput) + e.startTool(editID, "Edit "+editFile.relPath, acp.ToolKindEdit, editInput, + acp.ToolCallLocation{Path: editFile.absPath}) + allowed := e.requestPermission(editID, "Edit "+editFile.relPath, acp.ToolKindEdit, editInput) fixedDelay(50) if allowed { - _ = enc.Encode(UserMsg{Type: TypeUser, Message: UserMsgBody{Role: "user", Content: []ContentBlock{{Type: BlockToolResult, ToolUseID: editID, Content: "File edited successfully: " + editFile.absPath}}}}) + e.completeTool(editID, map[string]any{"result": "File edited successfully: " + editFile.absPath}) } else { - emitTextBlock(enc, "Edit denied.", "") + e.completeTool(editID, map[string]any{"result": "Edit denied"}) + e.text("Edit denied.") } // Bash (with permission) fixedDelay(50) bashID := nextToolID() bashInput := map[string]any{"command": "echo done", "description": "Print done"} - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{{Type: BlockToolUse, ID: bashID, Name: ToolBash, Input: bashInput}}, - Model: "mock-default", StopReason: "tool_use", Usage: defaultUsage(), - }, - }) - allowed = requestPermission(enc, scanner, ToolBash, bashID, bashInput) + e.startTool(bashID, "Print done", acp.ToolKindExecute, bashInput) + allowed = e.requestPermission(bashID, "Print done", acp.ToolKindExecute, bashInput) fixedDelay(50) if allowed { - _ = enc.Encode(UserMsg{Type: TypeUser, Message: UserMsgBody{Role: "user", Content: []ContentBlock{{Type: BlockToolResult, ToolUseID: bashID, Content: "done"}}}}) + e.completeTool(bashID, map[string]any{"output": "done"}) } else { - emitTextBlock(enc, "Bash denied.", "") + e.completeTool(bashID, map[string]any{"output": "Permission denied"}) + e.text("Bash denied.") } } // scenarioMultiTurn: minimal response for multi-turn test. -func scenarioMultiTurn(enc *json.Encoder) { +func scenarioMultiTurn(e *emitter) { fixedDelay(50) - emitTextBlock(enc, "Multi-turn response ready. Send another message to continue.", "") + e.text("Multi-turn response ready. Send another message to continue.") } // scenarioDiffExpansionSetup: creates a committed file and then modifies it, // leaving an uncommitted diff that the UI can display with expansion enabled. -// -// Uses 200 lines with hunks at lines 50 (mid-top) and 150 (mid-bottom), so the -// diff viewer collapses ~90 lines between hunks and ~45 lines at each end. -// This gives three separate expand handles for the e2e test to interact with. -func scenarioDiffExpansionSetup(enc *json.Encoder) { +func scenarioDiffExpansionSetup(e *emitter) { fixedDelay(50) wd, err := os.Getwd() if err != nil { - emitTextBlock(enc, "diff-expansion-setup: getwd failed: "+err.Error(), "") + e.text("diff-expansion-setup: getwd failed: " + err.Error()) return } - // Build a 200-line file with distinct content per line so assertions can - // target specific line text after expanding collapsed regions. const totalLines = 200 originalLines := make([]string, totalLines) for i := 0; i < totalLines; i++ { @@ -391,58 +253,28 @@ func scenarioDiffExpansionSetup(enc *json.Encoder) { filePath := "expansion_test.go" if err := os.WriteFile(filePath, []byte(original), 0o644); err != nil { - emitTextBlock(enc, "diff-expansion-setup: write failed: "+err.Error(), "") + e.text("diff-expansion-setup: write failed: " + err.Error()) return } - gitEnv := append(os.Environ(), - "GIT_AUTHOR_NAME=Mock Agent", - "GIT_AUTHOR_EMAIL=mock@test.local", - "GIT_COMMITTER_NAME=Mock Agent", - "GIT_COMMITTER_EMAIL=mock@test.local", - ) - - runGitCmd := func(args ...string) error { - cmd := exec.Command("git", append([]string{ - "-c", "commit.gpgsign=false", - "-c", "tag.gpgsign=false", - }, args...)...) - cmd.Dir = wd - cmd.Env = gitEnv - out, cmdErr := cmd.CombinedOutput() - if cmdErr != nil { - fmt.Fprintf(os.Stderr, "mock-agent: git %v failed: %v\nOutput: %s\n", args, cmdErr, out) - } - return cmdErr - } - - // Clean up from any previous test run so the add+commit is never a no-op. - // git rm --force removes the file from both the index and worktree; - // the commit records the deletion. Errors are ignored (file may not exist). + runGitCmd := makeGitRunner(wd) _ = runGitCmd("rm", "--force", filePath) _ = runGitCmd("commit", "-m", "cleanup expansion_test.go") - // Re-write the original content (git rm deleted it from the worktree). if err := os.WriteFile(filePath, []byte(original), 0o644); err != nil { - emitTextBlock(enc, "diff-expansion-setup: re-write failed: "+err.Error(), "") + e.text("diff-expansion-setup: re-write failed: " + err.Error()) return } if err := runGitCmd("add", filePath); err != nil { - emitTextBlock(enc, "diff-expansion-setup: git add failed", "") + e.text("diff-expansion-setup: git add failed") return } if err := runGitCmd("commit", "-m", "add expansion_test.go for e2e diff expansion test"); err != nil { - emitTextBlock(enc, "diff-expansion-setup: git commit failed", "") + e.text("diff-expansion-setup: git commit failed") return } - // Modify line 50 (mid-top, index 49) and line 150 (mid-bottom, index 149). - // With 3 lines of context per hunk, the diff collapses: - // - lines 1-46 (~46 lines) above the first hunk - // - lines 54-146 (~93 lines) between the two hunks - // - lines 154-200 (~47 lines) below the second hunk - // Each collapsed region gets its own expand handle in the diff viewer. modifiedLines := make([]string, totalLines) copy(modifiedLines, originalLines) modifiedLines[49] = "func modified_mid_top() { /* HUNK_TOP - modified line 50 */ }" @@ -450,141 +282,107 @@ func scenarioDiffExpansionSetup(enc *json.Encoder) { modified := strings.Join(modifiedLines, "\n") + "\n" if err := os.WriteFile(filePath, []byte(modified), 0o644); err != nil { - emitTextBlock(enc, "diff-expansion-setup: write modified failed: "+err.Error(), "") + e.text("diff-expansion-setup: write modified failed: " + err.Error()) return } fixedDelay(100) - emitTextBlock(enc, "diff-expansion-setup complete: expansion_test.go has two-hunk uncommitted diff (lines 50 and 150 of 200).", "") + e.text("diff-expansion-setup complete: expansion_test.go has two-hunk uncommitted diff (lines 50 and 150 of 200).") } -// scenarioDiffUpdateSetup creates a simple file, commits it, then modifies it -// to leave an uncommitted diff. This is the first step of the diff-update test. -// The file content is simple so assertions can verify exact diff content. -func scenarioDiffUpdateSetup(enc *json.Encoder) { +// scenarioDiffUpdateSetup creates a simple file, commits it, then modifies it. +func scenarioDiffUpdateSetup(e *emitter) { fixedDelay(50) wd, err := os.Getwd() if err != nil { - emitTextBlock(enc, "diff-update-setup: getwd failed: "+err.Error(), "") + e.text("diff-update-setup: getwd failed: " + err.Error()) return } filePath := "diff_update_test.txt" originalContent := "line 1: original\nline 2: unchanged\nline 3: original\n" - // Write original content if err := os.WriteFile(filePath, []byte(originalContent), 0o644); err != nil { - emitTextBlock(enc, "diff-update-setup: write failed: "+err.Error(), "") + e.text("diff-update-setup: write failed: " + err.Error()) return } - gitEnv := append(os.Environ(), - "GIT_AUTHOR_NAME=Mock Agent", - "GIT_AUTHOR_EMAIL=mock@test.local", - "GIT_COMMITTER_NAME=Mock Agent", - "GIT_COMMITTER_EMAIL=mock@test.local", - ) - - runGitCmd := func(args ...string) error { - cmd := exec.Command("git", append([]string{ - "-c", "commit.gpgsign=false", - "-c", "tag.gpgsign=false", - }, args...)...) - cmd.Dir = wd - cmd.Env = gitEnv - out, cmdErr := cmd.CombinedOutput() - if cmdErr != nil { - fmt.Fprintf(os.Stderr, "mock-agent: git %v failed: %v\nOutput: %s\n", args, cmdErr, out) - } - return cmdErr - } - - // Clean up from any previous test run + runGitCmd := makeGitRunner(wd) _ = runGitCmd("rm", "--force", filePath) _ = runGitCmd("commit", "-m", "cleanup diff_update_test.txt") - // Re-write and commit original content if err := os.WriteFile(filePath, []byte(originalContent), 0o644); err != nil { - emitTextBlock(enc, "diff-update-setup: re-write failed: "+err.Error(), "") + e.text("diff-update-setup: re-write failed: " + err.Error()) return } if err := runGitCmd("add", filePath); err != nil { - emitTextBlock(enc, "diff-update-setup: git add failed", "") + e.text("diff-update-setup: git add failed") return } if err := runGitCmd("commit", "-m", "add diff_update_test.txt"); err != nil { - emitTextBlock(enc, "diff-update-setup: git commit failed", "") + e.text("diff-update-setup: git commit failed") return } - // Modify the file to create an uncommitted diff modifiedContent := "line 1: FIRST_MODIFICATION\nline 2: unchanged\nline 3: original\n" if err := os.WriteFile(filePath, []byte(modifiedContent), 0o644); err != nil { - emitTextBlock(enc, "diff-update-setup: write modified failed: "+err.Error(), "") + e.text("diff-update-setup: write modified failed: " + err.Error()) return } fixedDelay(100) - emitTextBlock(enc, "diff-update-setup complete: diff_update_test.txt has FIRST_MODIFICATION", "") + e.text("diff-update-setup complete: diff_update_test.txt has FIRST_MODIFICATION") } -// scenarioDiffUpdateModify modifies the diff_update_test.txt file again, -// changing the diff content. This tests that the UI updates the diff display -// when files change after the initial diff was shown. -func scenarioDiffUpdateModify(enc *json.Encoder) { +// scenarioDiffUpdateModify modifies the diff_update_test.txt file again. +func scenarioDiffUpdateModify(e *emitter) { fixedDelay(50) filePath := "diff_update_test.txt" - - // Modify the file again with different content modifiedContent := "line 1: SECOND_MODIFICATION\nline 2: unchanged\nline 3: ALSO_CHANGED\n" if err := os.WriteFile(filePath, []byte(modifiedContent), 0o644); err != nil { - emitTextBlock(enc, "diff-update-modify: write failed: "+err.Error(), "") + e.text("diff-update-modify: write failed: " + err.Error()) return } fixedDelay(100) - emitTextBlock(enc, "diff-update-modify complete: diff_update_test.txt now has SECOND_MODIFICATION", "") + e.text("diff-update-modify complete: diff_update_test.txt now has SECOND_MODIFICATION") } -// scenarioUntrackedFileSetup creates a new untracked file (not staged, not committed). -// This tests that the UI shows diffs for untracked files. -func scenarioUntrackedFileSetup(enc *json.Encoder) { +// scenarioUntrackedFileSetup creates a new untracked file. +func scenarioUntrackedFileSetup(e *emitter) { fixedDelay(50) filePath := "untracked_test.txt" content := "line 1: INITIAL_CONTENT\nline 2: some text\n" - // Remove any existing file first _ = os.Remove(filePath) - // Write new untracked file if err := os.WriteFile(filePath, []byte(content), 0o644); err != nil { - emitTextBlock(enc, "untracked-file-setup: write failed: "+err.Error(), "") + e.text("untracked-file-setup: write failed: " + err.Error()) return } fixedDelay(100) - emitTextBlock(enc, "untracked-file-setup complete: untracked_test.txt has INITIAL_CONTENT", "") + e.text("untracked-file-setup complete: untracked_test.txt has INITIAL_CONTENT") } -// scenarioUntrackedFileModify modifies the untracked file created by untracked-file-setup. -// This tests that the UI updates the diff when an untracked file is modified. -func scenarioUntrackedFileModify(enc *json.Encoder) { +// scenarioUntrackedFileModify modifies the untracked file. +func scenarioUntrackedFileModify(e *emitter) { fixedDelay(50) filePath := "untracked_test.txt" content := "line 1: MODIFIED_CONTENT\nline 2: some text\nline 3: NEW_LINE\n" if err := os.WriteFile(filePath, []byte(content), 0o644); err != nil { - emitTextBlock(enc, "untracked-file-modify: write failed: "+err.Error(), "") + e.text("untracked-file-modify: write failed: " + err.Error()) return } fixedDelay(100) - emitTextBlock(enc, "untracked-file-modify complete: untracked_test.txt now has MODIFIED_CONTENT", "") + e.text("untracked-file-modify complete: untracked_test.txt now has MODIFIED_CONTENT") } // clarificationQuestionArgs returns the MCP arguments for the clarification question. @@ -600,41 +398,67 @@ func clarificationQuestionArgs() map[string]any { } // scenarioClarification: happy path — ask a question via MCP and wait for the answer. -func scenarioClarification(enc *json.Encoder) { +func scenarioClarification(e *emitter) { fixedDelay(100) - emitTextBlock(enc, "Let me ask you a question about the project setup.", "") + e.text("Let me ask you a question about the project setup.") result, err := callMCPTool("kandev", "ask_user_question", clarificationQuestionArgs()) if err != nil { - emitTextBlock(enc, fmt.Sprintf("Question failed: %s", err), "") + e.text(fmt.Sprintf("Question failed: %s", err)) return } fixedDelay(50) - emitTextBlock(enc, fmt.Sprintf("You answered: %s", result), "") + e.text(fmt.Sprintf("You answered: %s", result)) } // scenarioClarificationTimeout: ask a question with a short timeout, then continue. -// The MCP call times out after 5s so the agent's turn completes. The user can still -// answer later, which triggers the event fallback path (new turn). -func scenarioClarificationTimeout(enc *json.Encoder) { +func scenarioClarificationTimeout(e *emitter) { fixedDelay(100) - emitTextBlock(enc, "Let me ask you a question about the project setup.", "") + e.text("Let me ask you a question about the project setup.") - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel := contextWithTimeout(5) defer cancel() result, err := callMCPToolCtx(ctx, "kandev", "ask_user_question", clarificationQuestionArgs()) if err != nil { fixedDelay(50) if ctx.Err() != nil { - emitTextBlock(enc, "Question timed out, continuing without answer.", "") + e.text("Question timed out, continuing without answer.") } else { - emitTextBlock(enc, fmt.Sprintf("Question failed: %s", err), "") + e.text(fmt.Sprintf("Question failed: %s", err)) } return } fixedDelay(50) - emitTextBlock(enc, fmt.Sprintf("You answered: %s", result), "") + e.text(fmt.Sprintf("You answered: %s", result)) +} + +// makeGitRunner returns a function that runs git commands in the given directory. +func makeGitRunner(wd string) func(args ...string) error { + gitEnv := append(os.Environ(), + "GIT_AUTHOR_NAME=Mock Agent", + "GIT_AUTHOR_EMAIL=mock@test.local", + "GIT_COMMITTER_NAME=Mock Agent", + "GIT_COMMITTER_EMAIL=mock@test.local", + ) + return func(args ...string) error { + cmd := exec.Command("git", append([]string{ + "-c", "commit.gpgsign=false", + "-c", "tag.gpgsign=false", + }, args...)...) + cmd.Dir = wd + cmd.Env = gitEnv + out, cmdErr := cmd.CombinedOutput() + if cmdErr != nil { + _, _ = fmt.Fprintf(logOutput, "mock-agent: git %v failed: %v\nOutput: %s\n", args, cmdErr, out) + } + return cmdErr + } +} + +// contextWithTimeout creates a context with timeout in seconds. +func contextWithTimeout(seconds int) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.Background(), time.Duration(seconds)*time.Second) } diff --git a/apps/backend/cmd/mock-agent/script.go b/apps/backend/cmd/mock-agent/script.go index a08b6d2ec1..d9307e2550 100644 --- a/apps/backend/cmd/mock-agent/script.go +++ b/apps/backend/cmd/mock-agent/script.go @@ -7,6 +7,8 @@ import ( "regexp" "strconv" "strings" + + acp "github.com/coder/acp-go-sdk" ) // isScriptMode returns true if the command starts with "e2e:" prefix @@ -16,50 +18,50 @@ func isScriptMode(cmd string) bool { } // executeScript processes a multi-line script command. -func executeScript(enc *json.Encoder, fullPrompt, cmd string) { +func executeScript(e *emitter, fullPrompt, cmd string) { lines := strings.Split(cmd, "\n") for _, line := range lines { line = strings.TrimSpace(line) if line == "" || strings.HasPrefix(line, "#") { continue } - executeCommand(enc, fullPrompt, line) + executeCommand(e, fullPrompt, line) } } // executeCommand dispatches a single script command line. -func executeCommand(enc *json.Encoder, fullPrompt, line string) { +func executeCommand(e *emitter, fullPrompt, line string) { switch { case strings.HasPrefix(line, "e2e:message("): text := extractStringArg(line, "e2e:message(") - emitTextBlock(enc, text, "") + e.text(text) case strings.HasPrefix(line, "e2e:thinking("): text := extractStringArg(line, "e2e:thinking(") - emitThinkingBlock(enc, text, "") + e.thought(text) case strings.HasPrefix(line, "e2e:delay("): ms := extractIntArg(line, "e2e:delay(") fixedDelay(ms) case strings.HasPrefix(line, "e2e:mcp:"): - executeMCPCommand(enc, fullPrompt, line) + executeMCPCommand(e, fullPrompt, line) case strings.HasPrefix(line, "e2e:tool_use("): - executeSimulatedToolUse(enc, line) + executeSimulatedToolUse(e, line) case strings.HasPrefix(line, "e2e:tool_result("): - executeSimulatedToolResult(enc, line) + executeSimulatedToolResult(e, line) } } // executeMCPCommand parses and executes: e2e:mcp::() -func executeMCPCommand(enc *json.Encoder, fullPrompt, line string) { +func executeMCPCommand(e *emitter, fullPrompt, line string) { rest := strings.TrimPrefix(line, "e2e:mcp:") colonIdx := strings.Index(rest, ":") if colonIdx < 0 { - emitTextBlock(enc, "Script error: invalid MCP command: "+line, "") + e.text("Script error: invalid MCP command: " + line) return } server := rest[:colonIdx] @@ -67,41 +69,40 @@ func executeMCPCommand(enc *json.Encoder, fullPrompt, line string) { parenIdx := strings.Index(remainder, "(") if parenIdx < 0 { - emitTextBlock(enc, "Script error: missing args in MCP command: "+line, "") + e.text("Script error: missing args in MCP command: " + line) return } toolName := remainder[:parenIdx] closeIdx := strings.LastIndex(remainder, ")") if closeIdx <= parenIdx { - emitTextBlock(enc, "Script error: missing closing paren in MCP command: "+line, "") + e.text("Script error: missing closing paren in MCP command: " + line) return } argsStr := remainder[parenIdx+1 : closeIdx] var args map[string]any if err := json.Unmarshal([]byte(argsStr), &args); err != nil { - emitTextBlock(enc, fmt.Sprintf("Script error: bad MCP args JSON: %v", err), "") + e.text(fmt.Sprintf("Script error: bad MCP args JSON: %v", err)) return } substituteContextPlaceholders(args, fullPrompt) toolID := nextToolID() - state.lastToolID = toolID - emitToolUseBlock(enc, toolID, toolName, args) + e.startTool(toolID, toolName, acp.ToolKindOther, args) result, err := callMCPTool(server, toolName, args) if err != nil { fmt.Fprintf(os.Stderr, "mock-agent: MCP call %s/%s failed: %v\n", server, toolName, err) - emitToolResultBlock(enc, toolID, "MCP error: "+err.Error(), true) + e.completeTool(toolID, map[string]any{"error": "MCP error: " + err.Error()}) } else { - emitToolResultBlock(enc, toolID, result, false) + e.completeTool(toolID, map[string]any{"result": result}) } } -// executeSimulatedToolUse emits a simulated tool_use block (no real execution). +// executeSimulatedToolUse emits a simulated tool call start (no real execution). // Format: e2e:tool_use("name", {"key":"value"}) -func executeSimulatedToolUse(enc *json.Encoder, line string) { +func executeSimulatedToolUse(e *emitter, line string) { inner := extractParenContent(line, "e2e:tool_use(") name, rest := extractFirstStringArg(inner) @@ -111,21 +112,20 @@ func executeSimulatedToolUse(enc *json.Encoder, line string) { rest = strings.TrimPrefix(rest, ",") rest = strings.TrimSpace(rest) if err := json.Unmarshal([]byte(rest), &input); err != nil { - emitTextBlock(enc, fmt.Sprintf("Script error: bad tool_use input JSON: %v", err), "") + e.text(fmt.Sprintf("Script error: bad tool_use input JSON: %v", err)) return } } toolID := nextToolID() - state.lastToolID = toolID - emitToolUseBlock(enc, toolID, name, input) + e.startTool(toolID, name, acp.ToolKindOther, input) } -// executeSimulatedToolResult emits a tool_result for the last tool_use. +// executeSimulatedToolResult emits a tool completion for the last tool_use. // Format: e2e:tool_result("content") -func executeSimulatedToolResult(enc *json.Encoder, line string) { +func executeSimulatedToolResult(e *emitter, line string) { content := extractStringArg(line, "e2e:tool_result(") - emitToolResultBlock(enc, state.lastToolID, content, false) + e.completeTool(acp.ToolCallId(state.lastToolID), map[string]any{"result": content}) } // --- Argument parsing helpers --- @@ -166,7 +166,6 @@ func extractFirstStringArg(s string) (string, string) { if len(s) == 0 || s[0] != '"' { return s, "" } - // Find closing quote (handling escaped quotes) for i := 1; i < len(s); i++ { if s[i] == '\\' { i++ // skip escaped char diff --git a/apps/backend/cmd/mock-agent/script_test.go b/apps/backend/cmd/mock-agent/script_test.go index 1b393e0a71..c152b03b3f 100644 --- a/apps/backend/cmd/mock-agent/script_test.go +++ b/apps/backend/cmd/mock-agent/script_test.go @@ -1,11 +1,12 @@ package main import ( - "bytes" - "encoding/json" + "context" "strings" + "sync" "testing" + acp "github.com/coder/acp-go-sdk" "github.com/mark3labs/mcp-go/mcp" ) @@ -39,48 +40,13 @@ func TestExtractStringArg(t *testing.T) { prefix string want string }{ - { - name: "simple string", - line: `e2e:message("hello world")`, - prefix: "e2e:message(", - want: "hello world", - }, - { - name: "string with escaped quotes", - line: `e2e:message("say \"hi\"")`, - prefix: "e2e:message(", - want: `say "hi"`, - }, - { - name: "string with newline escape", - line: `e2e:message("line1\nline2")`, - prefix: "e2e:message(", - want: "line1\nline2", - }, - { - name: "string with tab escape", - line: `e2e:message("col1\tcol2")`, - prefix: "e2e:message(", - want: "col1\tcol2", - }, - { - name: "string with escaped backslash", - line: `e2e:message("path\\file")`, - prefix: "e2e:message(", - want: `path\file`, - }, - { - name: "thinking command", - line: `e2e:thinking("deep thought")`, - prefix: "e2e:thinking(", - want: "deep thought", - }, - { - name: "tool_result command", - line: `e2e:tool_result("success")`, - prefix: "e2e:tool_result(", - want: "success", - }, + {"simple string", `e2e:message("hello world")`, "e2e:message(", "hello world"}, + {"escaped quotes", `e2e:message("say \"hi\"")`, "e2e:message(", `say "hi"`}, + {"newline escape", `e2e:message("line1\nline2")`, "e2e:message(", "line1\nline2"}, + {"tab escape", `e2e:message("col1\tcol2")`, "e2e:message(", "col1\tcol2"}, + {"escaped backslash", `e2e:message("path\\file")`, "e2e:message(", `path\file`}, + {"thinking command", `e2e:thinking("deep thought")`, "e2e:thinking(", "deep thought"}, + {"tool_result command", `e2e:tool_result("success")`, "e2e:tool_result(", "success"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -121,18 +87,8 @@ func TestExtractParenContent(t *testing.T) { prefix string want string }{ - { - name: "simple content", - line: `e2e:tool_use("Read", {"path":"/tmp"})`, - prefix: "e2e:tool_use(", - want: `"Read", {"path":"/tmp"}`, - }, - { - name: "no trailing paren", - line: `e2e:tool_use("Read"`, - prefix: "e2e:tool_use(", - want: `"Read"`, - }, + {"simple content", `e2e:tool_use("Read", {"path":"/tmp"})`, "e2e:tool_use(", `"Read", {"path":"/tmp"}`}, + {"no trailing paren", `e2e:tool_use("Read"`, "e2e:tool_use(", `"Read"`}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -151,36 +107,11 @@ func TestExtractFirstStringArg(t *testing.T) { wantVal string wantRest string }{ - { - name: "simple string", - input: `"hello", rest`, - wantVal: "hello", - wantRest: ", rest", - }, - { - name: "string with escaped quote", - input: `"say \"hi\"", more`, - wantVal: `say "hi"`, - wantRest: ", more", - }, - { - name: "just a string", - input: `"only"`, - wantVal: "only", - wantRest: "", - }, - { - name: "empty input", - input: "", - wantVal: "", - wantRest: "", - }, - { - name: "non-quoted input", - input: "bare", - wantVal: "bare", - wantRest: "", - }, + {"simple string", `"hello", rest`, "hello", ", rest"}, + {"string with escaped quote", `"say \"hi\"", more`, `say "hi"`, ", more"}, + {"just a string", `"only"`, "only", ""}, + {"empty input", "", "", ""}, + {"non-quoted input", "bare", "bare", ""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -289,21 +220,9 @@ func TestExtractRegexMatch(t *testing.T) { input string want string }{ - { - name: "task ID found", - input: "Kandev Task ID: abc-123", - want: "abc-123", - }, - { - name: "task ID with extra whitespace", - input: "Kandev Task ID: def-456", - want: "def-456", - }, - { - name: "no match", - input: "no task id here", - want: "", - }, + {"task ID found", "Kandev Task ID: abc-123", "abc-123"}, + {"task ID with extra whitespace", "Kandev Task ID: def-456", "def-456"}, + {"no match", "no task id here", ""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -315,153 +234,251 @@ func TestExtractRegexMatch(t *testing.T) { } } -// TestExecuteScriptMessage verifies e2e:message emits an assistant text block. -func TestExecuteScriptMessage(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) +// --- Mock sessionUpdater for testing --- - // Reset global state - resetState() - - executeScript(enc, "", `e2e:message("hello from script")`) - - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 1 { - t.Fatalf("expected 1 message, got %d", len(msgs)) - } - assertMsgType(t, msgs[0], TypeAssistant) - assertContentText(t, msgs[0], "hello from script") +// recordedUpdate stores a captured ACP session notification. +type recordedUpdate struct { + notification acp.SessionNotification } -// TestExecuteScriptThinking verifies e2e:thinking emits a thinking block. -func TestExecuteScriptThinking(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) +// mockUpdater implements sessionUpdater for tests, collecting all updates. +type mockUpdater struct { + mu sync.Mutex + updates []recordedUpdate +} - executeScript(enc, "", `e2e:thinking("deep thought")`) +func (m *mockUpdater) SessionUpdate(_ context.Context, n acp.SessionNotification) error { + m.mu.Lock() + defer m.mu.Unlock() + m.updates = append(m.updates, recordedUpdate{notification: n}) + return nil +} - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 1 { - t.Fatalf("expected 1 message, got %d", len(msgs)) +func (m *mockUpdater) RequestPermission(_ context.Context, _ acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) { + return acp.RequestPermissionResponse{ + Outcome: acp.RequestPermissionOutcome{ + Selected: &acp.RequestPermissionOutcomeSelected{OptionId: "allow"}, + }, + }, nil +} + +func (m *mockUpdater) getUpdates() []recordedUpdate { + m.mu.Lock() + defer m.mu.Unlock() + return append([]recordedUpdate{}, m.updates...) +} + +func newTestEmitter() (*emitter, *mockUpdater) { + mock := &mockUpdater{} + e := &emitter{ + ctx: context.Background(), + conn: mock, + sid: "test-session", + } + return e, mock +} + +// --- Update assertion helpers --- + +func isTextUpdate(u recordedUpdate) bool { + return u.notification.Update.AgentMessageChunk != nil +} + +func isThoughtUpdate(u recordedUpdate) bool { + return u.notification.Update.AgentThoughtChunk != nil +} + +func isToolCallUpdate(u recordedUpdate) bool { + return u.notification.Update.ToolCall != nil +} + +func isToolCallCompleteUpdate(u recordedUpdate) bool { + return u.notification.Update.ToolCallUpdate != nil +} + +func getTextContent(u recordedUpdate) string { + if u.notification.Update.AgentMessageChunk == nil { + return "" + } + if u.notification.Update.AgentMessageChunk.Content.Text == nil { + return "" + } + return u.notification.Update.AgentMessageChunk.Content.Text.Text +} + +func getThoughtContent(u recordedUpdate) string { + if u.notification.Update.AgentThoughtChunk == nil { + return "" + } + if u.notification.Update.AgentThoughtChunk.Content.Text == nil { + return "" + } + return u.notification.Update.AgentThoughtChunk.Content.Text.Text +} + +func getToolCallTitle(u recordedUpdate) string { + if u.notification.Update.ToolCall == nil { + return "" + } + return u.notification.Update.ToolCall.Title +} + +func getToolCallID(u recordedUpdate) acp.ToolCallId { + if u.notification.Update.ToolCall != nil { + return u.notification.Update.ToolCall.ToolCallId + } + if u.notification.Update.ToolCallUpdate != nil { + return u.notification.Update.ToolCallUpdate.ToolCallId + } + return "" +} + +// --- Script execution tests --- + +// TestExecuteScriptMessage verifies e2e:message emits an agent text update. +func TestExecuteScriptMessage(t *testing.T) { + e, mock := newTestEmitter() + resetState() + + executeScript(e, "", `e2e:message("hello from script")`) + + updates := mock.getUpdates() + if len(updates) != 1 { + t.Fatalf("expected 1 update, got %d", len(updates)) + } + if !isTextUpdate(updates[0]) { + t.Fatal("expected text update") + } + if got := getTextContent(updates[0]); got != "hello from script" { + t.Errorf("text = %q, want %q", got, "hello from script") + } +} + +// TestExecuteScriptThinking verifies e2e:thinking emits a thought update. +func TestExecuteScriptThinking(t *testing.T) { + e, mock := newTestEmitter() + resetState() + + executeScript(e, "", `e2e:thinking("deep thought")`) + + updates := mock.getUpdates() + if len(updates) != 1 { + t.Fatalf("expected 1 update, got %d", len(updates)) + } + if !isThoughtUpdate(updates[0]) { + t.Fatal("expected thought update") + } + if got := getThoughtContent(updates[0]); got != "deep thought" { + t.Errorf("thought = %q, want %q", got, "deep thought") } - assertMsgType(t, msgs[0], TypeAssistant) - assertContentThinking(t, msgs[0], "deep thought") } // TestExecuteScriptMultiLine verifies multiple commands are processed sequentially. func TestExecuteScriptMultiLine(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) + e, mock := newTestEmitter() resetState() script := "e2e:thinking(\"step 1\")\ne2e:message(\"step 2\")\ne2e:message(\"step 3\")" - executeScript(enc, "", script) + executeScript(e, "", script) - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 3 { - t.Fatalf("expected 3 messages, got %d", len(msgs)) + updates := mock.getUpdates() + if len(updates) != 3 { + t.Fatalf("expected 3 updates, got %d", len(updates)) + } + if got := getThoughtContent(updates[0]); got != "step 1" { + t.Errorf("thought = %q, want %q", got, "step 1") + } + if got := getTextContent(updates[1]); got != "step 2" { + t.Errorf("text = %q, want %q", got, "step 2") + } + if got := getTextContent(updates[2]); got != "step 3" { + t.Errorf("text = %q, want %q", got, "step 3") } - assertContentThinking(t, msgs[0], "step 1") - assertContentText(t, msgs[1], "step 2") - assertContentText(t, msgs[2], "step 3") } // TestExecuteScriptSkipsEmptyAndComments verifies blank lines and comments are skipped. func TestExecuteScriptSkipsEmptyAndComments(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) + e, mock := newTestEmitter() resetState() script := "e2e:message(\"one\")\n\n# this is a comment\n \ne2e:message(\"two\")" - executeScript(enc, "", script) + executeScript(e, "", script) - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 2 { - t.Fatalf("expected 2 messages, got %d", len(msgs)) + updates := mock.getUpdates() + if len(updates) != 2 { + t.Fatalf("expected 2 updates, got %d", len(updates)) + } + if got := getTextContent(updates[0]); got != "one" { + t.Errorf("text = %q, want %q", got, "one") + } + if got := getTextContent(updates[1]); got != "two" { + t.Errorf("text = %q, want %q", got, "two") } - assertContentText(t, msgs[0], "one") - assertContentText(t, msgs[1], "two") } -// TestExecuteScriptToolUse verifies e2e:tool_use emits a tool_use block. +// TestExecuteScriptToolUse verifies e2e:tool_use emits a tool_call update. func TestExecuteScriptToolUse(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) + e, mock := newTestEmitter() resetState() - executeScript(enc, "", `e2e:tool_use("Read", {"file_path":"/tmp/test.go"})`) + executeScript(e, "", `e2e:tool_use("Read", {"file_path":"/tmp/test.go"})`) - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 1 { - t.Fatalf("expected 1 message, got %d", len(msgs)) + updates := mock.getUpdates() + if len(updates) != 1 { + t.Fatalf("expected 1 update, got %d", len(updates)) } - assertMsgType(t, msgs[0], TypeAssistant) - content := getFirstContent(t, msgs[0]) - if content["type"] != BlockToolUse { - t.Errorf("content type = %q, want %q", content["type"], BlockToolUse) + if !isToolCallUpdate(updates[0]) { + t.Fatal("expected tool_call update") } - if content["name"] != "Read" { - t.Errorf("tool name = %q, want %q", content["name"], "Read") - } - input, ok := content["input"].(map[string]any) - if !ok { - t.Fatal("input is not a map") - } - if input["file_path"] != "/tmp/test.go" { - t.Errorf("file_path = %q, want %q", input["file_path"], "/tmp/test.go") + if got := getToolCallTitle(updates[0]); got != "Read" { + t.Errorf("title = %q, want %q", got, "Read") } } // TestExecuteScriptToolUseAndResult verifies tool_use + tool_result pair. func TestExecuteScriptToolUseAndResult(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) + e, mock := newTestEmitter() resetState() script := "e2e:tool_use(\"Read\", {\"file_path\":\"/tmp/f.go\"})\ne2e:tool_result(\"file contents here\")" - executeScript(enc, "", script) + executeScript(e, "", script) - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 2 { - t.Fatalf("expected 2 messages, got %d", len(msgs)) + updates := mock.getUpdates() + if len(updates) != 2 { + t.Fatalf("expected 2 updates, got %d", len(updates)) } - // First: tool_use - toolUseContent := getFirstContent(t, msgs[0]) - toolID := toolUseContent["id"].(string) + // First: tool_call start + if !isToolCallUpdate(updates[0]) { + t.Fatal("expected tool_call update") + } + toolID := getToolCallID(updates[0]) if toolID == "" { - t.Fatal("tool_use should have an id") + t.Fatal("tool_call should have an id") } - // Second: tool_result referencing same ID - assertMsgType(t, msgs[1], TypeUser) - resultContent := getFirstContent(t, msgs[1]) - if resultContent["type"] != BlockToolResult { - t.Errorf("result type = %q, want %q", resultContent["type"], BlockToolResult) + // Second: tool_call_update (completion) referencing same ID + if !isToolCallCompleteUpdate(updates[1]) { + t.Fatal("expected tool_call_update") } - if resultContent["tool_use_id"] != toolID { - t.Errorf("tool_use_id = %q, want %q", resultContent["tool_use_id"], toolID) - } - if resultContent["content"] != "file contents here" { - t.Errorf("content = %q, want %q", resultContent["content"], "file contents here") + if got := getToolCallID(updates[1]); got != toolID { + t.Errorf("tool_call_update id = %q, want %q", got, toolID) } } // TestExecuteScriptToolUseNoInput verifies tool_use with no input arg. func TestExecuteScriptToolUseNoInput(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) + e, mock := newTestEmitter() resetState() - executeScript(enc, "", `e2e:tool_use("Glob")`) + executeScript(e, "", `e2e:tool_use("Glob")`) - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 1 { - t.Fatalf("expected 1 message, got %d", len(msgs)) + updates := mock.getUpdates() + if len(updates) != 1 { + t.Fatalf("expected 1 update, got %d", len(updates)) } - content := getFirstContent(t, msgs[0]) - if content["name"] != "Glob" { - t.Errorf("tool name = %q, want %q", content["name"], "Glob") + if got := getToolCallTitle(updates[0]); got != "Glob" { + t.Errorf("title = %q, want %q", got, "Glob") } } @@ -471,31 +488,11 @@ func TestParseMCPConfigFromArgs(t *testing.T) { args []string want string }{ - { - name: "no flag", - args: []string{"mock-agent"}, - want: "", - }, - { - name: "separate flag and value", - args: []string{"mock-agent", "--mcp-config", `{"mcpServers":{"kandev":{"url":"http://localhost:10005/sse"}}}`}, - want: `{"mcpServers":{"kandev":{"url":"http://localhost:10005/sse"}}}`, - }, - { - name: "equals syntax", - args: []string{"mock-agent", `--mcp-config={"mcpServers":{}}`}, - want: `{"mcpServers":{}}`, - }, - { - name: "with other flags", - args: []string{"mock-agent", "--model", "fast", "--mcp-config", `{"mcpServers":{}}`}, - want: `{"mcpServers":{}}`, - }, - { - name: "dangling flag", - args: []string{"mock-agent", "--mcp-config"}, - want: "", - }, + {"no flag", []string{"mock-agent"}, ""}, + {"separate flag and value", []string{"mock-agent", "--mcp-config", `{"mcpServers":{"kandev":{"url":"http://localhost:10005/sse"}}}`}, `{"mcpServers":{"kandev":{"url":"http://localhost:10005/sse"}}}`}, + {"equals syntax", []string{"mock-agent", `--mcp-config={"mcpServers":{}}`}, `{"mcpServers":{}}`}, + {"with other flags", []string{"mock-agent", "--model", "fast", "--mcp-config", `{"mcpServers":{}}`}, `{"mcpServers":{}}`}, + {"dangling flag", []string{"mock-agent", "--mcp-config"}, ""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -547,86 +544,20 @@ func TestExtractMCPResultText(t *testing.T) { // TestExecuteScriptToolUseBadJSON verifies that malformed JSON emits a script error. func TestExecuteScriptToolUseBadJSON(t *testing.T) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) + e, mock := newTestEmitter() resetState() - executeScript(enc, "", `e2e:tool_use("Read", {bad json})`) + executeScript(e, "", `e2e:tool_use("Read", {bad json})`) - msgs := decodeJSONLines(t, buf.Bytes()) - if len(msgs) != 1 { - t.Fatalf("expected 1 message (error), got %d", len(msgs)) + updates := mock.getUpdates() + if len(updates) != 1 { + t.Fatalf("expected 1 update (error), got %d", len(updates)) } - assertMsgType(t, msgs[0], TypeAssistant) - content := getFirstContent(t, msgs[0]) - text, _ := content["text"].(string) + if !isTextUpdate(updates[0]) { + t.Fatal("expected text update for error") + } + text := getTextContent(updates[0]) if !strings.Contains(text, "Script error") { t.Errorf("expected script error message, got %q", text) } } - -// --- Test helpers --- - -// decodeJSONLines splits output into JSON-decoded maps. -func decodeJSONLines(t *testing.T, data []byte) []map[string]any { - t.Helper() - var results []map[string]any - dec := json.NewDecoder(bytes.NewReader(data)) - for dec.More() { - var m map[string]any - if err := dec.Decode(&m); err != nil { - t.Fatalf("failed to decode JSON: %v", err) - } - results = append(results, m) - } - return results -} - -func assertMsgType(t *testing.T, msg map[string]any, wantType string) { - t.Helper() - if msg["type"] != wantType { - t.Errorf("message type = %q, want %q", msg["type"], wantType) - } -} - -func getFirstContent(t *testing.T, msg map[string]any) map[string]any { - t.Helper() - message, ok := msg["message"].(map[string]any) - if !ok { - t.Fatal("message field is not a map") - } - contentArr, ok := message["content"].([]any) - if !ok || len(contentArr) == 0 { - t.Fatal("content is not an array or is empty") - } - block, ok := contentArr[0].(map[string]any) - if !ok { - t.Fatal("first content block is not a map") - } - return block -} - -func assertContentText(t *testing.T, msg map[string]any, wantText string) { - t.Helper() - content := getFirstContent(t, msg) - if content["type"] != BlockText { - t.Errorf("content type = %q, want %q", content["type"], BlockText) - } - // emitTextBlock appends a trailing newline to match real agent streaming behavior; - // allow the expected text with or without the trailing newline. - got, _ := content["text"].(string) - if got != wantText && got != wantText+"\n" { - t.Errorf("text = %q, want %q (or with trailing newline)", got, wantText) - } -} - -func assertContentThinking(t *testing.T, msg map[string]any, wantThought string) { - t.Helper() - content := getFirstContent(t, msg) - if content["type"] != BlockThinking { - t.Errorf("content type = %q, want %q", content["type"], BlockThinking) - } - if content["thinking"] != wantThought { - t.Errorf("thinking = %q, want %q", content["thinking"], wantThought) - } -} diff --git a/apps/backend/cmd/mock-agent/sequences.go b/apps/backend/cmd/mock-agent/sequences.go index 0a2fb291d7..6ee089b42d 100644 --- a/apps/backend/cmd/mock-agent/sequences.go +++ b/apps/backend/cmd/mock-agent/sequences.go @@ -1,10 +1,10 @@ package main import ( - "bufio" - "encoding/json" "fmt" "strings" + + acp "github.com/coder/acp-go-sdk" ) // scriptState holds mutable state shared across script commands and sequence emitters. @@ -21,111 +21,38 @@ func resetState() { state = &scriptState{} } -func nextToolID() string { +func nextToolID() acp.ToolCallId { state.toolCallCounter++ - return fmt.Sprintf("mock_tool_%04d", state.toolCallCounter) -} - -func defaultUsage() *Usage { - return &Usage{ - InputTokens: 1200, - OutputTokens: 350, - } + id := fmt.Sprintf("mock_tool_%04d", state.toolCallCounter) + state.lastToolID = id + return acp.ToolCallId(id) } // --- Atomic emitters --- -// emitThinking emits an assistant message with a thinking block. -func emitThinking(enc *json.Encoder, model string) { +// emitThinking emits a thinking block with random delay. +func emitThinking(e *emitter, model string) { randomDelay(model) - emitThinkingBlock(enc, "Analyzing the request and considering the best approach...", "") + e.thought("Analyzing the request and considering the best approach...") } -// emitThinkingBlock emits an assistant message with a thinking content block. -func emitThinkingBlock(enc *json.Encoder, thought, parentToolUseID string) { - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - ParentToolUseID: parentToolUseID, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockThinking, Thinking: thought}, - }, - Model: "mock-default", - Usage: defaultUsage(), - }, - }) -} - -// emitTextBlock emits an assistant message with a text content block. -// Text always ends with a newline to match real agent streaming behavior, -// which allows the lifecycle manager's message buffer to flush immediately -// and publish "message_streaming" events for activity detection. -func emitTextBlock(enc *json.Encoder, text, parentToolUseID string) { - if !strings.HasSuffix(text, "\n") { - text += "\n" - } - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - ParentToolUseID: parentToolUseID, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockText, Text: text}, - }, - Model: "mock-default", - StopReason: "end_turn", - Usage: defaultUsage(), - }, - }) -} - -// emitReadFile emits a Read tool_use followed by a tool_result using a real workspace file. -func emitReadFile(enc *json.Encoder, model string) { +// emitReadFile emits a Read tool call using a real workspace file. +func emitReadFile(e *emitter, model string) { toolID := nextToolID() f := randomFile() snippet := readFileSnippet(f.absPath, 30) randomDelay(model) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: toolID, - Name: ToolRead, - Input: map[string]any{ - "file_path": f.absPath, - }, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(toolID, "Read "+f.relPath, acp.ToolKindRead, + map[string]any{"file_path": f.absPath}, + acp.ToolCallLocation{Path: f.absPath}) randomDelay(model) - - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - { - Type: BlockToolResult, - ToolUseID: toolID, - Content: snippet, - }, - }, - }, - }) + e.completeTool(toolID, map[string]any{"content": snippet}) } -// emitEditFile emits an Edit tool_use with a real file and real content fragment. -func emitEditFile(enc *json.Encoder, scanner *bufio.Scanner, model string) { +// emitEditFile emits an Edit tool call with permission request. +func emitEditFile(e *emitter, model string) { toolID := nextToolID() f := randomFile() oldStr, newStr := pickEditableFragment(f.absPath) @@ -137,47 +64,19 @@ func emitEditFile(enc *json.Encoder, scanner *bufio.Scanner, model string) { "new_string": newStr, } - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: toolID, - Name: ToolEdit, - Input: input, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(toolID, "Edit "+f.relPath, acp.ToolKindEdit, input, + acp.ToolCallLocation{Path: f.absPath}) - allowed := requestPermission(enc, scanner, ToolEdit, toolID, input) - - if allowed { - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - { - Type: BlockToolResult, - ToolUseID: toolID, - Content: "File edited successfully: " + f.absPath, - }, - }, - }, - }) + if e.requestPermission(toolID, "Edit "+f.relPath, acp.ToolKindEdit, input) { + e.completeTool(toolID, map[string]any{"result": "File edited successfully: " + f.absPath}) } else { - emitTextBlock(enc, "Permission denied for Edit, skipping.", "") + e.completeTool(toolID, map[string]any{"result": "Permission denied for Edit"}) + e.text("Permission denied for Edit, skipping.") } } -// emitShellExec emits a Bash tool_use with permission request, then tool_result. -func emitShellExec(enc *json.Encoder, scanner *bufio.Scanner, model string) { +// emitShellExec emits a Bash tool call with permission request. +func emitShellExec(e *emitter, model string) { toolID := nextToolID() randomDelay(model) @@ -186,47 +85,18 @@ func emitShellExec(enc *json.Encoder, scanner *bufio.Scanner, model string) { "description": "Run all tests", } - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: toolID, - Name: ToolBash, - Input: input, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(toolID, "Run tests", acp.ToolKindExecute, input) - allowed := requestPermission(enc, scanner, ToolBash, toolID, input) - - if allowed { - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - { - Type: BlockToolResult, - ToolUseID: toolID, - Content: "ok \tgithub.com/example/project\t0.042s\nPASS", - }, - }, - }, - }) + if e.requestPermission(toolID, "Run tests", acp.ToolKindExecute, input) { + e.completeTool(toolID, map[string]any{"output": "ok \tgithub.com/example/project\t0.042s\nPASS"}) } else { - emitTextBlock(enc, "Permission denied for Bash, skipping.", "") + e.completeTool(toolID, map[string]any{"output": "Permission denied"}) + e.text("Permission denied for Bash, skipping.") } } -// emitCodeSearch emits a Grep tool_use using real workspace file paths. -func emitCodeSearch(enc *json.Encoder, model string) { +// emitCodeSearch emits a Grep tool call using real workspace file paths. +func emitCodeSearch(e *emitter, model string) { toolID := nextToolID() randomDelay(model) @@ -234,299 +104,125 @@ func emitCodeSearch(enc *json.Encoder, model string) { pattern := searchPatterns[state.toolCallCounter%len(searchPatterns)] f := randomFile() - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: toolID, - Name: ToolGrep, - Input: map[string]any{ - "pattern": pattern, - "path": f.absPath, - }, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(toolID, "Search for \""+pattern+"\"", acp.ToolKindSearch, + map[string]any{"pattern": pattern, "path": f.absPath}) randomDelay(model) - // Build realistic search results using real file paths paths := randomFilePaths(3) var results []string for i, p := range paths { results = append(results, fmt.Sprintf("%s:%d:%s found here", p, (i+1)*10, strings.TrimSpace(pattern))) } - - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - { - Type: BlockToolResult, - ToolUseID: toolID, - Content: strings.Join(results, "\n"), - }, - }, - }, - }) + e.completeTool(toolID, map[string]any{"matches": strings.Join(results, "\n")}) } -// emitSubagent emits a Task tool_use with nested child messages using real files. -func emitSubagent(enc *json.Encoder, scanner *bufio.Scanner, model string) { +// emitSubagent emits a Task tool call with child tool calls. +func emitSubagent(e *emitter, model string) { taskToolID := nextToolID() randomDelay(model) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: taskToolID, - Name: ToolTask, - Input: map[string]any{ - "description": "Explore codebase", - "prompt": "Find all files and summarize the project structure", - }, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(taskToolID, "Explore codebase", acp.ToolKindOther, + map[string]any{ + "description": "Explore codebase", + "prompt": "Find all files and summarize the project structure", + }) randomDelay(model) - _ = enc.Encode(SystemMsg{Type: TypeSystem, SessionID: sessionID, SessionStatus: "active"}) - randomDelay(model) - emitThinkingBlock(enc, "Exploring the project structure...", taskToolID) + e.thought("Exploring the project structure...") randomDelay(model) paths := randomFilePaths(5) - emitTextBlock(enc, fmt.Sprintf("Found %d files. The project structure looks well-organized.", len(paths)), taskToolID) + e.text(fmt.Sprintf("Found %d files. The project structure looks well-organized.", len(paths))) randomDelay(model) - emitSubagentChildGlob(enc, taskToolID, model, paths) - emitSubagentCompletion(enc, taskToolID, model, paths) -} -func emitSubagentChildGlob(enc *json.Encoder, taskToolID, model string, paths []string) { + // Child glob tool call childToolID := nextToolID() - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - ParentToolUseID: taskToolID, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: childToolID, - Name: ToolGlob, - Input: map[string]any{"pattern": "**/*"}, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) + e.startTool(childToolID, "Glob **/*", acp.ToolKindSearch, + map[string]any{"pattern": "**/*"}) randomDelay(model) - _ = enc.Encode(UserMsg{ - Type: TypeUser, - ParentToolUseID: taskToolID, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{{Type: BlockToolResult, ToolUseID: childToolID, Content: strings.Join(paths, "\n")}}, - }, - }) - randomDelay(model) -} - -// emitSubagentCompletion emits the final text block and tool result for a subagent task. -func emitSubagentCompletion(enc *json.Encoder, taskToolID, model string, paths []string) { - emitTextBlock(enc, "Project structure analysis complete.", taskToolID) + e.completeTool(childToolID, map[string]any{"files": strings.Join(paths, "\n")}) randomDelay(model) - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - { - Type: BlockToolResult, - ToolUseID: taskToolID, - Content: fmt.Sprintf("Subagent completed: Found %d files across the project.", len(paths)), - }, - }, - }, + e.text("Project structure analysis complete.") + randomDelay(model) + e.completeTool(taskToolID, map[string]any{ + "result": fmt.Sprintf("Subagent completed: Found %d files across the project.", len(paths)), }) } -// emitTodo emits a TodoWrite tool_use followed by a tool_result. -func emitTodo(enc *json.Encoder, model string) { +// emitTodo emits a TodoWrite tool call. +func emitTodo(e *emitter, model string) { toolID := nextToolID() randomDelay(model) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: toolID, - Name: ToolTodoWrite, - Input: map[string]any{ - "todos": []map[string]any{ - {"id": "1", "content": "Review code changes", "status": "in_progress"}, - {"id": "2", "content": "Run tests", "status": "pending"}, - {"id": "3", "content": "Update documentation", "status": "pending"}, - }, - }, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), + e.startTool(toolID, "Update todo list", acp.ToolKindOther, map[string]any{ + "todos": []map[string]any{ + {"id": "1", "content": "Review code changes", "status": "in_progress"}, + {"id": "2", "content": "Run tests", "status": "pending"}, + {"id": "3", "content": "Update documentation", "status": "pending"}, }, }) randomDelay(model) - - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - { - Type: BlockToolResult, - ToolUseID: toolID, - Content: "Todo list updated: 3 items (1 in progress, 2 pending)", - }, - }, - }, - }) + e.completeTool(toolID, map[string]any{"result": "Todo list updated: 3 items (1 in progress, 2 pending)"}) } // emitMermaidSequence emits a rich markdown message containing mermaid diagrams. -func emitMermaidSequence(enc *json.Encoder, model string) { - emitThinking(enc, model) +func emitMermaidSequence(e *emitter, model string) { + emitThinking(e, model) randomDelay(model) - emitTextBlock(enc, "Here's an overview of the system architecture with diagrams:\n\n"+ - "## System Flow\n\n"+ - "The following flowchart shows the request processing pipeline:\n\n"+ - "```mermaid\n"+ - "flowchart TD\n"+ - " A([Client Request]) --> B{Auth Check}\n"+ - " B -->|Valid| C[API Gateway]\n"+ - " B -->|Invalid| D[401 Unauthorized]\n"+ - " C --> E[Load Balancer]\n"+ - " E --> F[Service A]\n"+ - " E --> G[Service B]\n"+ - " F --> H[(Database)]\n"+ - " G --> H\n"+ - " H --> I[Response Builder]\n"+ - " I --> J([Client Response])\n"+ - "```\n\n"+ - "## Sequence Diagram\n\n"+ - "Here's how the authentication flow works between components:\n\n"+ - "```mermaid\n"+ - "sequenceDiagram\n"+ - " participant U as User\n"+ - " participant FE as Frontend\n"+ - " participant API as API Server\n"+ - " participant DB as Database\n"+ - " U->>FE: Login Request\n"+ - " FE->>API: POST /auth/login\n"+ - " API->>DB: Verify Credentials\n"+ - " DB-->>API: User Record\n"+ - " API-->>FE: JWT Token\n"+ - " FE-->>U: Redirect to Dashboard\n"+ - "```\n\n"+ - "### Key Points\n\n"+ - "- All requests go through the **API Gateway** for rate limiting\n"+ - "- Authentication uses **JWT tokens** with a 24h expiry\n"+ - "- Services communicate via `gRPC` internally\n"+ - "- Database connections use a **connection pool** (max 50)\n", "") + e.text("Here's an overview of the system architecture with diagrams:\n\n" + + "## System Flow\n\n" + + "The following flowchart shows the request processing pipeline:\n\n" + + "```mermaid\n" + + "flowchart TD\n" + + " A([Client Request]) --> B{Auth Check}\n" + + " B -->|Valid| C[API Gateway]\n" + + " B -->|Invalid| D[401 Unauthorized]\n" + + " C --> E[Load Balancer]\n" + + " E --> F[Service A]\n" + + " E --> G[Service B]\n" + + " F --> H[(Database)]\n" + + " G --> H\n" + + " H --> I[Response Builder]\n" + + " I --> J([Client Response])\n" + + "```\n\n" + + "## Sequence Diagram\n\n" + + "Here's how the authentication flow works between components:\n\n" + + "```mermaid\n" + + "sequenceDiagram\n" + + " participant U as User\n" + + " participant FE as Frontend\n" + + " participant API as API Server\n" + + " participant DB as Database\n" + + " U->>FE: Login Request\n" + + " FE->>API: POST /auth/login\n" + + " API->>DB: Verify Credentials\n" + + " DB-->>API: User Record\n" + + " API-->>FE: JWT Token\n" + + " FE-->>U: Redirect to Dashboard\n" + + "```\n\n" + + "### Key Points\n\n" + + "- All requests go through the **API Gateway** for rate limiting\n" + + "- Authentication uses **JWT tokens** with a 24h expiry\n" + + "- Services communicate via `gRPC` internally\n" + + "- Database connections use a **connection pool** (max 50)\n") } -// emitToolUseBlock emits an assistant message with a single tool_use content block. -func emitToolUseBlock(enc *json.Encoder, toolID, toolName string, input map[string]any) { - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - {Type: BlockToolUse, ID: toolID, Name: toolName, Input: input}, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, - }) -} - -// emitToolResultBlock emits a user message with a tool_result content block. -func emitToolResultBlock(enc *json.Encoder, toolID, content string, isError bool) { - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - {Type: BlockToolResult, ToolUseID: toolID, Content: content, IsError: isError}, - }, - }, - }) -} - -// emitWebFetch emits a WebFetch tool_use followed by a tool_result. -func emitWebFetch(enc *json.Encoder, model string) { +// emitWebFetch emits a WebFetch tool call. +func emitWebFetch(e *emitter, model string) { toolID := nextToolID() randomDelay(model) - _ = enc.Encode(AssistantMsg{ - Type: TypeAssistant, - Message: AssistantBody{ - Role: "assistant", - Content: []ContentBlock{ - { - Type: BlockToolUse, - ID: toolID, - Name: ToolWebFetch, - Input: map[string]any{ - "url": "https://example.com/api/docs", - "prompt": "Extract the API endpoints and their descriptions", - }, - }, - }, - Model: "mock-default", - StopReason: "tool_use", - Usage: defaultUsage(), - }, + e.startTool(toolID, "Fetch API docs", acp.ToolKindFetch, map[string]any{ + "url": "https://example.com/api/docs", + "prompt": "Extract the API endpoints and their descriptions", }) randomDelay(model) - - _ = enc.Encode(UserMsg{ - Type: TypeUser, - Message: UserMsgBody{ - Role: "user", - Content: []ContentBlock{ - { - Type: BlockToolResult, - ToolUseID: toolID, - Content: "API Documentation:\n- GET /api/v1/users - List all users\n- POST /api/v1/users - Create a new user\n- GET /api/v1/users/:id - Get user by ID\n- PUT /api/v1/users/:id - Update user\n- DELETE /api/v1/users/:id - Delete user", - }, - }, - }, + e.completeTool(toolID, map[string]any{ + "content": "API Documentation:\n- GET /api/v1/users - List all users\n- POST /api/v1/users - Create a new user\n- GET /api/v1/users/:id - Get user by ID\n- PUT /api/v1/users/:id - Update user\n- DELETE /api/v1/users/:id - Delete user", }) } diff --git a/apps/backend/cmd/mock-agent/types.go b/apps/backend/cmd/mock-agent/types.go deleted file mode 100644 index e9c99ace60..0000000000 --- a/apps/backend/cmd/mock-agent/types.go +++ /dev/null @@ -1,192 +0,0 @@ -package main - -import "encoding/json" - -// Message types -const ( - TypeSystem = "system" - TypeAssistant = "assistant" - TypeUser = "user" - TypeResult = "result" - TypeControlRequest = "control_request" - TypeControlResponse = "control_response" -) - -// Content block types -const ( - BlockText = "text" - BlockThinking = "thinking" - BlockToolUse = "tool_use" - BlockToolResult = "tool_result" -) - -// Tool names matching Claude Code conventions -const ( - ToolBash = "Bash" - ToolEdit = "Edit" - ToolRead = "Read" - ToolGlob = "Glob" - ToolGrep = "Grep" - ToolTask = "Task" - ToolTodoWrite = "TodoWrite" - ToolWebFetch = "WebFetch" -) - -// IncomingMessage is a minimal struct for parsing stdin messages. -type IncomingMessage struct { - Type string `json:"type"` - RequestID string `json:"request_id,omitempty"` - Message *IncomingBody `json:"message,omitempty"` - Response *IncomingControl `json:"response,omitempty"` -} - -// IncomingBody is the message body for user messages. -type IncomingBody struct { - Role string `json:"role"` - Content string `json:"content"` -} - -// IncomingControl is the response body for control_response messages. -type IncomingControl struct { - Subtype string `json:"subtype"` - RequestID string `json:"request_id,omitempty"` - Result *PermissionReply `json:"result,omitempty"` -} - -// PermissionReply is the result from a permission response. -type PermissionReply struct { - Behavior string `json:"behavior"` -} - -// --- Outgoing message types (written to stdout) --- - -// SystemMsg is the system message emitted at the start of each turn. -type SystemMsg struct { - Type string `json:"type"` - SessionID string `json:"session_id"` - SessionStatus string `json:"session_status"` -} - -// AssistantMsg is an assistant message with content blocks. -type AssistantMsg struct { - Type string `json:"type"` - ParentToolUseID string `json:"parent_tool_use_id,omitempty"` - Message AssistantBody `json:"message"` -} - -// AssistantBody is the body of an assistant message. -type AssistantBody struct { - Role string `json:"role"` - Content []ContentBlock `json:"content"` - Model string `json:"model"` - StopReason string `json:"stop_reason,omitempty"` - Usage *Usage `json:"usage,omitempty"` -} - -// ContentBlock represents a content block in an assistant or user message. -type ContentBlock struct { - Type string `json:"type"` - - // text block - Text string `json:"text,omitempty"` - - // thinking block - Thinking string `json:"thinking,omitempty"` - - // tool_use block - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Input map[string]any `json:"input,omitempty"` - - // tool_result block - ToolUseID string `json:"tool_use_id,omitempty"` - Content string `json:"content,omitempty"` - IsError bool `json:"is_error,omitempty"` -} - -// Usage contains token usage information. -type Usage struct { - InputTokens int64 `json:"input_tokens"` - OutputTokens int64 `json:"output_tokens"` - CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,omitempty"` - CacheReadInputTokens int64 `json:"cache_read_input_tokens,omitempty"` -} - -// UserMsg is a user message (used for tool results). -type UserMsg struct { - Type string `json:"type"` - ParentToolUseID string `json:"parent_tool_use_id,omitempty"` - Message UserMsgBody `json:"message"` -} - -// UserMsgBody is the body of a user message with tool results. -type UserMsgBody struct { - Role string `json:"role"` - Content []ContentBlock `json:"content"` -} - -// ResultMsg is the final result message for a turn. -type ResultMsg struct { - Type string `json:"type"` - Result json.RawMessage `json:"result"` - CostUSD float64 `json:"cost_usd"` - DurationMS int64 `json:"duration_ms"` - DurationAPIMS int64 `json:"duration_api_ms"` - IsError bool `json:"is_error"` - NumTurns int `json:"num_turns"` - TotalInputTokens int64 `json:"total_input_tokens"` - TotalOutputTokens int64 `json:"total_output_tokens"` - ModelUsage map[string]ModelUsageStats `json:"model_usage,omitempty"` -} - -// ModelUsageStats per-model usage statistics. -type ModelUsageStats struct { - ContextWindow int64 `json:"context_window"` -} - -// ResultData is the result object for successful completions. -type ResultData struct { - Text string `json:"text"` - SessionID string `json:"session_id"` -} - -// ControlRequestMsg is a control request emitted to stdout (permission requests). -type ControlRequestMsg struct { - Type string `json:"type"` - RequestID string `json:"request_id"` - Request ControlRequestBody `json:"request"` -} - -// ControlRequestBody is the body of a control request. -type ControlRequestBody struct { - Subtype string `json:"subtype"` - ToolName string `json:"tool_name,omitempty"` - Input map[string]any `json:"input,omitempty"` - ToolUseID string `json:"tool_use_id,omitempty"` -} - -// ControlResponseMsg is a control response emitted to stdout (for initialize). -type ControlResponseMsg struct { - Type string `json:"type"` - Response ControlResponseBody `json:"response"` -} - -// ControlResponseBody is the body of a control response. -type ControlResponseBody struct { - Subtype string `json:"subtype"` - RequestID string `json:"request_id"` - Response *InitializeResponse `json:"response,omitempty"` -} - -// InitializeResponse is the response to an initialize control request. -type InitializeResponse struct { - Commands []Command `json:"commands"` - Agents []string `json:"agents"` -} - -// Command is an available slash command. -type Command struct { - Name string `json:"name"` - Description string `json:"description"` - ArgumentHint string `json:"argumentHint,omitempty"` -} diff --git a/apps/backend/internal/agent/agents/amp_acp.go b/apps/backend/internal/agent/agents/amp_acp.go new file mode 100644 index 0000000000..63734ddf85 --- /dev/null +++ b/apps/backend/internal/agent/agents/amp_acp.go @@ -0,0 +1,121 @@ +package agents + +import ( + "context" + _ "embed" + "time" + + "github.com/kandev/kandev/pkg/agent" +) + +//go:embed logos/amp_light.svg +var ampACPLogoLight []byte + +//go:embed logos/amp_dark.svg +var ampACPLogoDark []byte + +const ampACPPkg = "amp-acp" + +var ( + _ Agent = (*AmpACP)(nil) + _ PassthroughAgent = (*AmpACP)(nil) +) + +// AmpACP implements Agent for Sourcegraph Amp using the ACP protocol. +// It runs the community amp-acp npm package which bridges Amp to ACP over +// stdin/stdout. Used for A/B comparison against the stream-json Amp agent. +type AmpACP struct { + StandardPassthrough +} + +func NewAmpACP() *AmpACP { + return &AmpACP{ + StandardPassthrough: StandardPassthrough{ + PermSettings: ampPermSettings, + Cfg: PassthroughConfig{ + Supported: true, + Label: "CLI Passthrough", + Description: "Show terminal directly instead of chat interface", + PassthroughCmd: NewCommand("npx", "-y", ampPkg), + ModelFlag: NewParam("-m", "{model}"), + IdleTimeout: 3 * time.Second, + BufferMaxBytes: DefaultBufferMaxBytes, + }, + }, + } +} + +func (a *AmpACP) ID() string { return "amp-acp" } +func (a *AmpACP) Name() string { return "Amp ACP Agent" } +func (a *AmpACP) DisplayName() string { return "Amp (ACP)" } +func (a *AmpACP) Description() string { + return "Sourcegraph Amp coding agent using the ACP protocol via the community bridge." +} +func (a *AmpACP) Enabled() bool { return true } +func (a *AmpACP) DisplayOrder() int { return 8 } + +func (a *AmpACP) Logo(v LogoVariant) []byte { + if v == LogoDark { + return ampACPLogoDark + } + return ampACPLogoLight +} + +func (a *AmpACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error) { + install := OSPaths{ + Linux: []string{"~/.amp/bin"}, + MacOS: []string{"~/.amp/bin"}, + } + mcp := OSPaths{ + Linux: []string{"~/.config/amp/settings.json"}, + MacOS: []string{"~/.amp/bin"}, + } + + result, err := Detect(ctx, WithFileExists(install.Resolve()...)) + if err != nil { + return result, err + } + result.SupportsMCP = true + result.InstallationPaths = install.Expanded() + result.MCPConfigPaths = mcp.Expanded() + result.Capabilities = DiscoveryCapabilities{ + SupportsSessionResume: true, + } + return result, nil +} + +func (a *AmpACP) DefaultModel() string { return "smart" } + +func (a *AmpACP) ListModels(ctx context.Context) (*ModelList, error) { + return &ModelList{Models: ampStaticModels(), SupportsDynamic: false}, nil +} + +func (a *AmpACP) BuildCommand(opts CommandOptions) Command { + return Cmd("npx", "-y", ampACPPkg).Build() +} + +func (a *AmpACP) Runtime() *RuntimeConfig { + canRecover := true + return &RuntimeConfig{ + Cmd: Cmd("npx", "-y", ampACPPkg).Build(), + WorkingDir: "{workspace}", + Env: map[string]string{}, + ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour}, + Protocol: agent.ProtocolACP, + SessionConfig: SessionConfig{ + NativeSessionResume: true, + CanRecover: &canRecover, + SessionDirTemplate: "{home}/.config/amp", + }, + } +} + +func (a *AmpACP) RemoteAuth() *RemoteAuth { return nil } + +func (a *AmpACP) InstallScript() string { + return "npm install -g " + ampACPPkg +} + +func (a *AmpACP) PermissionSettings() map[string]PermissionSetting { + return ampPermSettings +} diff --git a/apps/backend/internal/agent/agents/claude_acp.go b/apps/backend/internal/agent/agents/claude_acp.go new file mode 100644 index 0000000000..012f1455a2 --- /dev/null +++ b/apps/backend/internal/agent/agents/claude_acp.go @@ -0,0 +1,140 @@ +package agents + +import ( + "context" + _ "embed" + "time" + + "github.com/kandev/kandev/pkg/agent" +) + +//go:embed logos/claude_code_light.svg +var claudeACPLogoLight []byte + +//go:embed logos/claude_code_dark.svg +var claudeACPLogoDark []byte + +const claudeACPPkg = "@zed-industries/claude-agent-acp" + +var ( + _ Agent = (*ClaudeACP)(nil) + _ PassthroughAgent = (*ClaudeACP)(nil) +) + +// ClaudeACP implements Agent for the Zed Industries claude-agent-acp package. +// It speaks the ACP protocol (JSON-RPC 2.0 over stdin/stdout) and wraps the +// Claude Agent SDK. Used for A/B comparison against the stream-json Claude Code agent. +type ClaudeACP struct { + StandardPassthrough +} + +func NewClaudeACP() *ClaudeACP { + return &ClaudeACP{ + StandardPassthrough: StandardPassthrough{ + PermSettings: claudeCodePermSettings, + 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"), + }, + }, + } +} + +func (a *ClaudeACP) ID() string { return "claude-acp" } +func (a *ClaudeACP) Name() string { return "Claude ACP Agent" } +func (a *ClaudeACP) DisplayName() string { return "Claude (ACP)" } +func (a *ClaudeACP) Description() string { + return "Anthropic Claude coding agent using the ACP protocol via the Zed Industries bridge." +} +func (a *ClaudeACP) Enabled() bool { return true } +func (a *ClaudeACP) DisplayOrder() int { return 2 } + +func (a *ClaudeACP) Logo(v LogoVariant) []byte { + if v == LogoDark { + return claudeACPLogoDark + } + return claudeACPLogoLight +} + +func (a *ClaudeACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error) { + result, err := Detect(ctx, WithFileExists("~/.claude.json")) + if err != nil { + return result, err + } + result.SupportsMCP = true + result.InstallationPaths = []string{expandHomePath("~/.claude.json")} + result.Capabilities = DiscoveryCapabilities{ + SupportsSessionResume: true, + } + return result, nil +} + +func (a *ClaudeACP) DefaultModel() string { return "claude-sonnet-4-6" } + +func (a *ClaudeACP) ListModels(ctx context.Context) (*ModelList, error) { + return &ModelList{Models: claudeCodeStaticModels(), SupportsDynamic: true}, nil +} + +func (a *ClaudeACP) BuildCommand(opts CommandOptions) Command { + return Cmd("npx", "-y", claudeACPPkg).Build() +} + +func (a *ClaudeACP) Runtime() *RuntimeConfig { + canRecover := true + return &RuntimeConfig{ + Image: "kandev/multi-agent", + Tag: "latest", + Cmd: Cmd("npx", "-y", claudeACPPkg).Build(), + WorkingDir: "{workspace}", + RequiredEnv: []string{}, // Auth via ANTHROPIC_API_KEY or OAuth credentials file (see RemoteAuth) + Env: map[string]string{ + "MCP_TIMEOUT": "7200000", + }, + Mounts: []MountTemplate{ + {Source: "{workspace}", Target: "/workspace"}, + }, + ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour}, + Protocol: agent.ProtocolACP, + SessionConfig: SessionConfig{ + NativeSessionResume: true, + CanRecover: &canRecover, + SessionDirTemplate: "{home}/.claude", + }, + } +} + +func (a *ClaudeACP) RemoteAuth() *RemoteAuth { + return &RemoteAuth{ + Methods: []RemoteAuthMethod{ + { + Type: "env", + EnvVar: "CLAUDE_CODE_OAUTH_TOKEN", + SetupHint: "Run `claude setup-token` to generate a long-lived OAuth token", + SetupScript: `mkdir -p "${HOME}/.claude" +cat > "${HOME}/.claude/.credentials.json" < "${HOME}/.claude.json" <<'JSON' +{"hasCompletedOnboarding":true} +JSON +chmod 600 "${HOME}/.claude/.credentials.json" +chmod 600 "${HOME}/.claude.json"`, + }, + }, + } +} + +func (a *ClaudeACP) InstallScript() string { + return "npm install -g " + claudeACPPkg +} + +func (a *ClaudeACP) PermissionSettings() map[string]PermissionSetting { + return claudeCodePermSettings +} diff --git a/apps/backend/internal/agent/agents/codex_acp.go b/apps/backend/internal/agent/agents/codex_acp.go new file mode 100644 index 0000000000..eeeec424da --- /dev/null +++ b/apps/backend/internal/agent/agents/codex_acp.go @@ -0,0 +1,132 @@ +package agents + +import ( + "context" + _ "embed" + "time" + + "github.com/kandev/kandev/pkg/agent" +) + +//go:embed logos/codex_light.svg +var codexACPLogoLight []byte + +//go:embed logos/codex_dark.svg +var codexACPLogoDark []byte + +const codexACPPkg = "@zed-industries/codex-acp" + +var ( + _ Agent = (*CodexACP)(nil) + _ PassthroughAgent = (*CodexACP)(nil) +) + +// CodexACP implements Agent for the Zed Industries codex-acp package. +// It speaks the ACP protocol (JSON-RPC 2.0 over stdin/stdout) via a Rust binary +// wrapping OpenAI Codex. Used for A/B comparison against the native Codex agent. +type CodexACP struct { + StandardPassthrough +} + +func NewCodexACP() *CodexACP { + return &CodexACP{ + StandardPassthrough: StandardPassthrough{ + PermSettings: codexPermSettings, + 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, + }, + }, + } +} + +func (a *CodexACP) ID() string { return "codex-acp" } +func (a *CodexACP) Name() string { return "Codex ACP Agent" } +func (a *CodexACP) DisplayName() string { return "Codex (ACP)" } +func (a *CodexACP) Description() string { + return "OpenAI Codex coding agent using the ACP protocol via the Zed Industries bridge." +} +func (a *CodexACP) Enabled() bool { return true } +func (a *CodexACP) DisplayOrder() int { return 3 } + +func (a *CodexACP) Logo(v LogoVariant) []byte { + if v == LogoDark { + return codexACPLogoDark + } + return codexACPLogoLight +} + +func (a *CodexACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error) { + result, err := Detect(ctx, WithFileExists("~/.codex/auth.json")) + if err != nil { + return result, err + } + result.SupportsMCP = true + result.InstallationPaths = []string{expandHomePath("~/.codex/auth.json")} + return result, nil +} + +func (a *CodexACP) DefaultModel() string { return "gpt-5.3-codex" } + +func (a *CodexACP) ListModels(ctx context.Context) (*ModelList, error) { + return &ModelList{Models: codexStaticModels(), SupportsDynamic: false}, nil +} + +func (a *CodexACP) BuildCommand(opts CommandOptions) Command { + return Cmd("npx", "-y", codexACPPkg).Build() +} + +func (a *CodexACP) Runtime() *RuntimeConfig { + canRecover := true + return &RuntimeConfig{ + Image: "kandev/multi-agent", + Tag: "latest", + Cmd: Cmd("npx", "-y", codexACPPkg).Build(), + WorkingDir: "{workspace}", + RequiredEnv: []string{"OPENAI_API_KEY"}, + Env: map[string]string{}, + Mounts: []MountTemplate{ + {Source: "{workspace}", Target: "/workspace"}, + {Source: "{home}/.codex", Target: "/root/.codex"}, + }, + ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour}, + Protocol: agent.ProtocolACP, + SessionConfig: SessionConfig{ + NativeSessionResume: true, + CanRecover: &canRecover, + }, + } +} + +func (a *CodexACP) RemoteAuth() *RemoteAuth { + return &RemoteAuth{ + Methods: []RemoteAuthMethod{ + { + Type: "files", + Label: "Copy auth files", + SourceFiles: map[string][]string{ + "darwin": {".codex/auth.json", ".codex/config.toml"}, + "linux": {".codex/auth.json", ".codex/config.toml"}, + }, + TargetRelDir: ".codex", + }, + { + Type: "env", + EnvVar: "OPENAI_API_KEY", + }, + }, + } +} + +func (a *CodexACP) InstallScript() string { + return "npm install -g " + codexACPPkg +} + +func (a *CodexACP) PermissionSettings() map[string]PermissionSetting { + return codexPermSettings +} diff --git a/apps/backend/internal/agent/agents/copilot.go b/apps/backend/internal/agent/agents/copilot.go index 20957f87d9..530b841a61 100644 --- a/apps/backend/internal/agent/agents/copilot.go +++ b/apps/backend/internal/agent/agents/copilot.go @@ -149,7 +149,7 @@ var copilotPermSettings = map[string]PermissionSetting{ func copilotStaticModels() []Model { return []Model{ - {ID: "gpt-4.1", Name: "GPT-4.1", Description: "OpenAI GPT-4.1", Provider: "openai", IsDefault: true, Source: "static"}, + {ID: "gpt-4.1", Name: "GPT-4.1", Description: "OpenAI GPT-4.1", Provider: "openai", Source: "static"}, {ID: "claude-sonnet-4", Name: "Claude Sonnet 4", Description: "Anthropic Claude Sonnet 4", Provider: "anthropic", Source: "static"}, {ID: "claude-sonnet-4.5", Name: "Claude Sonnet 4.5", Description: "Anthropic Claude Sonnet 4.5", Provider: "anthropic", Source: "static"}, {ID: "claude-opus-4.5", Name: "Claude Opus 4.5", Description: "Anthropic Claude Opus 4.5", Provider: "anthropic", Source: "static"}, @@ -161,7 +161,7 @@ func copilotStaticModels() []Model { {ID: "gpt-5.1", Name: "GPT-5.1", Description: "OpenAI GPT-5.1", Provider: "openai", Source: "static"}, {ID: "gpt-5", Name: "GPT-5", Description: "OpenAI GPT-5", Provider: "openai", Source: "static"}, {ID: "gpt-5.1-codex-mini", Name: "GPT-5.1 Codex Mini", Description: "OpenAI GPT-5.1 Codex Mini", Provider: "openai", Source: "static"}, - {ID: "gpt-5-mini", Name: "GPT-5 Mini", Description: "OpenAI GPT-5 Mini", Provider: "openai", Source: "static"}, + {ID: "gpt-5-mini", Name: "GPT-5 Mini", Description: "OpenAI GPT-5 Mini", Provider: "openai", Source: "static", IsDefault: true}, {ID: "gemini-3-pro-preview", Name: "Gemini 3 Pro Preview", Description: "Google Gemini 3 Pro Preview", Provider: "google", Source: "static"}, } } diff --git a/apps/backend/internal/agent/agents/copilot_acp.go b/apps/backend/internal/agent/agents/copilot_acp.go new file mode 100644 index 0000000000..810debcdfc --- /dev/null +++ b/apps/backend/internal/agent/agents/copilot_acp.go @@ -0,0 +1,126 @@ +package agents + +import ( + "context" + _ "embed" + "time" + + "github.com/kandev/kandev/pkg/agent" +) + +//go:embed logos/copilot_light.svg +var copilotACPLogoLight []byte + +//go:embed logos/copilot_dark.svg +var copilotACPLogoDark []byte + +const copilotACPPkg = "@github/copilot" + +var ( + _ Agent = (*CopilotACP)(nil) + _ PassthroughAgent = (*CopilotACP)(nil) +) + +// CopilotACP implements Agent for GitHub Copilot using ACP protocol mode. +// It runs the same @github/copilot CLI with the --acp flag, speaking standard +// ACP over stdin/stdout. Used for A/B comparison against the Go SDK-based Copilot agent. +type CopilotACP struct { + StandardPassthrough +} + +func NewCopilotACP() *CopilotACP { + return &CopilotACP{ + StandardPassthrough: StandardPassthrough{ + PermSettings: copilotPermSettings, + Cfg: PassthroughConfig{ + Supported: true, + Label: "CLI Passthrough", + Description: "Show terminal directly instead of chat interface", + PassthroughCmd: NewCommand("npx", "-y", copilotACPPkg), + ModelFlag: NewParam("--model", "{model}"), + IdleTimeout: 3 * time.Second, + BufferMaxBytes: DefaultBufferMaxBytes, + ResumeFlag: NewParam("--continue"), + SessionResumeFlag: NewParam("--resume"), + }, + }, + } +} + +func (a *CopilotACP) ID() string { return "copilot-acp" } +func (a *CopilotACP) Name() string { return "Copilot ACP Agent" } +func (a *CopilotACP) DisplayName() string { return "Copilot (ACP)" } +func (a *CopilotACP) Description() string { + return "GitHub Copilot coding agent using the ACP protocol over stdin/stdout." +} +func (a *CopilotACP) Enabled() bool { return true } +func (a *CopilotACP) DisplayOrder() int { return 7 } + +func (a *CopilotACP) Logo(v LogoVariant) []byte { + if v == LogoDark { + return copilotACPLogoDark + } + return copilotACPLogoLight +} + +func (a *CopilotACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error) { + install := OSPaths{ + MacOS: []string{"~/.copilot/pkg"}, + } + mcp := OSPaths{ + Linux: []string{"~/.copilot/mcp-config.json"}, + MacOS: []string{"~/.copilot/mcp-config.json"}, + } + + result, err := Detect(ctx, WithFileExists(install.Resolve()...)) + if err != nil { + return result, err + } + result.SupportsMCP = true + result.InstallationPaths = install.Expanded() + result.MCPConfigPaths = mcp.Expanded() + result.Capabilities = DiscoveryCapabilities{ + SupportsSessionResume: true, + } + return result, nil +} + +func (a *CopilotACP) DefaultModel() string { return "gpt-4.1" } + +func (a *CopilotACP) ListModels(ctx context.Context) (*ModelList, error) { + return &ModelList{Models: copilotStaticModels(), SupportsDynamic: false}, nil +} + +func (a *CopilotACP) BuildCommand(opts CommandOptions) Command { + return Cmd("npx", "-y", copilotACPPkg, "--acp"). + Model(NewParam("--model", "{model}"), opts.Model). + Settings(copilotPermSettings, opts.PermissionValues). + Build() +} + +func (a *CopilotACP) Runtime() *RuntimeConfig { + canRecover := true + return &RuntimeConfig{ + Cmd: Cmd("npx", "-y", copilotACPPkg, "--acp").Build(), + WorkingDir: "{workspace}", + Env: map[string]string{}, + ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour}, + Protocol: agent.ProtocolACP, + ModelFlag: NewParam("--model", "{model}"), + SessionConfig: SessionConfig{ + NativeSessionResume: true, + CanRecover: &canRecover, + SessionDirTemplate: "{home}/.copilot", + }, + } +} + +func (a *CopilotACP) RemoteAuth() *RemoteAuth { return nil } + +func (a *CopilotACP) InstallScript() string { + return "npm install -g " + copilotACPPkg +} + +func (a *CopilotACP) PermissionSettings() map[string]PermissionSetting { + return copilotPermSettings +} diff --git a/apps/backend/internal/agent/agents/mock.go b/apps/backend/internal/agent/agents/mock.go index eddda2ff9f..8e247e52dd 100644 --- a/apps/backend/internal/agent/agents/mock.go +++ b/apps/backend/internal/agent/agents/mock.go @@ -97,7 +97,6 @@ func (a *MockAgent) BuildCommand(opts CommandOptions) Command { } return Cmd(binary). Model(NewParam("--model", "{model}"), opts.Model). - Resume(NewParam("--resume"), opts.SessionID, false). Build() } @@ -108,10 +107,9 @@ func (a *MockAgent) Runtime() *RuntimeConfig { WorkingDir: "{workspace}", Env: map[string]string{}, ResourceLimits: ResourceLimits{MemoryMB: 512, CPUCores: 0.5, Timeout: time.Hour}, - Protocol: agent.ProtocolClaudeCode, + Protocol: agent.ProtocolACP, ModelFlag: NewParam("--model", "{model}"), SessionConfig: SessionConfig{ - ResumeFlag: NewParam("--resume"), CanRecover: &canRecover, }, } diff --git a/apps/backend/internal/agent/agents/mock_test.go b/apps/backend/internal/agent/agents/mock_test.go index b71f06f58e..d3a2d0dcac 100644 --- a/apps/backend/internal/agent/agents/mock_test.go +++ b/apps/backend/internal/agent/agents/mock_test.go @@ -2,63 +2,36 @@ package agents import ( "testing" + + "github.com/kandev/kandev/pkg/agent" ) -func TestMockAgent_BuildCommand_WithSessionID(t *testing.T) { - a := NewMockAgent() - cmd := a.BuildCommand(CommandOptions{Model: "mock-fast", SessionID: "sess-123"}) - args := cmd.Args() - - foundResume := false - for i, arg := range args { - if arg == "--resume" { - foundResume = true - if i+1 >= len(args) { - t.Fatal("--resume flag has no value") - } - if args[i+1] != "sess-123" { - t.Errorf("--resume value = %q, want %q", args[i+1], "sess-123") - } - break - } - } - if !foundResume { - t.Errorf("expected --resume flag in args %v", args) - } -} - -func TestMockAgent_BuildCommand_WithoutSessionID(t *testing.T) { +func TestMockAgent_BuildCommand_WithModel(t *testing.T) { a := NewMockAgent() cmd := a.BuildCommand(CommandOptions{Model: "mock-fast"}) args := cmd.Args() - for _, arg := range args { - if arg == "--resume" { - t.Errorf("--resume flag should not be present without SessionID, got args %v", args) - } - } -} - -func TestMockAgent_BuildCommand_WithModel(t *testing.T) { - a := NewMockAgent() - cmd := a.BuildCommand(CommandOptions{Model: "mock-fast", SessionID: "sess-456"}) - args := cmd.Args() - foundModel := false - foundResume := false for i, arg := range args { if arg == "--model" && i+1 < len(args) && args[i+1] == "mock-fast" { foundModel = true } - if arg == "--resume" && i+1 < len(args) && args[i+1] == "sess-456" { - foundResume = true - } } if !foundModel { t.Errorf("expected --model mock-fast in args %v", args) } - if !foundResume { - t.Errorf("expected --resume sess-456 in args %v", args) +} + +func TestMockAgent_BuildCommand_NoResumeFlag(t *testing.T) { + a := NewMockAgent() + // ACP handles resume via session/load, so --resume should not appear. + cmd := a.BuildCommand(CommandOptions{Model: "mock-fast", SessionID: "sess-123"}) + args := cmd.Args() + + for _, arg := range args { + if arg == "--resume" { + t.Errorf("--resume flag should not be present for ACP agent, got args %v", args) + } } } @@ -71,16 +44,22 @@ func TestMockAgent_Runtime_CanRecover(t *testing.T) { } } -func TestMockAgent_Runtime_ResumeFlag(t *testing.T) { +func TestMockAgent_Runtime_ProtocolACP(t *testing.T) { a := NewMockAgent() rt := a.Runtime() - if rt.SessionConfig.ResumeFlag.IsEmpty() { - t.Error("expected ResumeFlag to be set on mock agent RuntimeConfig") + if rt.Protocol != agent.ProtocolACP { + t.Errorf("expected Protocol = %q, got %q", agent.ProtocolACP, rt.Protocol) } - flagArgs := rt.SessionConfig.ResumeFlag.Args() - if len(flagArgs) == 0 || flagArgs[0] != "--resume" { - t.Errorf("expected ResumeFlag args to start with --resume, got %v", flagArgs) +} + +func TestMockAgent_Runtime_NoResumeFlag(t *testing.T) { + a := NewMockAgent() + rt := a.Runtime() + + // ACP agents handle resume via session/load, not CLI flags. + if !rt.SessionConfig.ResumeFlag.IsEmpty() { + t.Error("expected ResumeFlag to be empty for ACP agent") } } @@ -88,7 +67,7 @@ func TestMockAgent_PassthroughConfig_ResumeFlags(t *testing.T) { a := NewMockAgent() pt := a.PassthroughConfig() - // Generic resume flag (-c) + // Generic resume flag (-c) — still used for TUI passthrough mode if pt.ResumeFlag.IsEmpty() { t.Error("expected ResumeFlag to be set on PassthroughConfig") } @@ -97,7 +76,7 @@ func TestMockAgent_PassthroughConfig_ResumeFlags(t *testing.T) { t.Errorf("expected ResumeFlag = -c, got %v", resumeArgs) } - // Session-specific resume flag (--resume) + // Session-specific resume flag (--resume) — TUI passthrough mode if pt.SessionResumeFlag.IsEmpty() { t.Error("expected SessionResumeFlag to be set on PassthroughConfig") } diff --git a/apps/backend/internal/agent/agents/opencode_acp.go b/apps/backend/internal/agent/agents/opencode_acp.go index 317b925cbb..fe73f0ef6e 100644 --- a/apps/backend/internal/agent/agents/opencode_acp.go +++ b/apps/backend/internal/agent/agents/opencode_acp.go @@ -8,15 +8,35 @@ import ( ) var ( - _ Agent = (*OpenCodeACP)(nil) - _ InferenceAgent = (*OpenCodeACP)(nil) + _ Agent = (*OpenCodeACP)(nil) + _ PassthroughAgent = (*OpenCodeACP)(nil) + _ InferenceAgent = (*OpenCodeACP)(nil) ) // OpenCodeACP is the ACP protocol variant of OpenCode. // Uses JSON-RPC 2.0 over stdin/stdout via "opencode acp" instead of REST/SSE. -type OpenCodeACP struct{} +type OpenCodeACP struct { + StandardPassthrough +} -func NewOpenCodeACP() *OpenCodeACP { return &OpenCodeACP{} } +func NewOpenCodeACP() *OpenCodeACP { + return &OpenCodeACP{ + StandardPassthrough: StandardPassthrough{ + PermSettings: opencodePermSettings, + Cfg: PassthroughConfig{ + Supported: true, + Label: "CLI Passthrough", + Description: "Show terminal directly instead of chat interface", + PassthroughCmd: NewCommand("opencode"), + ModelFlag: NewParam("--model", "{model}"), + PromptFlag: NewParam("--prompt", "{prompt}"), + IdleTimeout: 3 * time.Second, + BufferMaxBytes: DefaultBufferMaxBytes, + ResumeFlag: NewParam("-c"), + }, + }, + } +} func (a *OpenCodeACP) ID() string { return "opencode-acp" } func (a *OpenCodeACP) Name() string { return "OpenCode AI Agent (ACP)" } diff --git a/apps/backend/internal/agent/lifecycle/event_types.go b/apps/backend/internal/agent/lifecycle/event_types.go index 146a7437da..361f4403d9 100644 --- a/apps/backend/internal/agent/lifecycle/event_types.go +++ b/apps/backend/internal/agent/lifecycle/event_types.go @@ -130,6 +130,27 @@ type AgentStreamEventData struct { // CurrentModeID is the active session mode identifier. // Populated when Type is "session_mode". CurrentModeID string `json:"current_mode_id,omitempty"` + + // AvailableModes lists modes the agent supports. + // Populated when Type is "session_mode". + AvailableModes []streams.SessionModeInfo `json:"available_modes,omitempty"` + + // Agent capabilities (from "agent_capabilities" event) + SupportsImage bool `json:"supports_image"` + SupportsAudio bool `json:"supports_audio"` + SupportsEmbeddedContext bool `json:"supports_embedded_context"` + AuthMethods []streams.AuthMethodInfo `json:"auth_methods,omitempty"` + + // Session models (from "session_models" event) + CurrentModelID string `json:"current_model_id,omitempty"` + SessionModels []streams.SessionModelInfo `json:"session_models,omitempty"` + ConfigOptions []streams.ConfigOption `json:"config_options,omitempty"` + + // Usage (attached to "complete" event) + Usage *streams.PromptUsage `json:"usage,omitempty"` + + // Plan entries (from "plan" event — ACP/Codex agent todos) + PlanEntries []streams.PlanEntry `json:"plan_entries,omitempty"` } // AgentStreamEventPayload is the payload for agent stream events (WebSocket streaming). @@ -374,14 +395,76 @@ func (p AvailableCommandsEventPayload) GetSessionID() string { // SessionModeEventPayload is the payload for session mode change events. type SessionModeEventPayload struct { - TaskID string `json:"task_id"` - SessionID string `json:"session_id"` - AgentID string `json:"agent_id"` - CurrentModeID string `json:"current_mode_id"` - Timestamp string `json:"timestamp"` + TaskID string `json:"task_id"` + SessionID string `json:"session_id"` + AgentID string `json:"agent_id"` + CurrentModeID string `json:"current_mode_id"` + AvailableModes []streams.SessionModeInfo `json:"available_modes,omitempty"` + Timestamp string `json:"timestamp"` } // GetSessionID returns the session ID for this event (used by event routing). func (p SessionModeEventPayload) GetSessionID() string { return p.SessionID } + +// AgentCapabilitiesEventPayload is the payload for agent capabilities events. +type AgentCapabilitiesEventPayload struct { + TaskID string `json:"task_id"` + SessionID string `json:"session_id"` + AgentID string `json:"agent_id"` + SupportsImage bool `json:"supports_image"` + SupportsAudio bool `json:"supports_audio"` + SupportsEmbeddedContext bool `json:"supports_embedded_context"` + AuthMethods []streams.AuthMethodInfo `json:"auth_methods"` + Timestamp string `json:"timestamp"` +} + +// GetSessionID returns the session ID for this event (used by event routing). +func (p AgentCapabilitiesEventPayload) GetSessionID() string { + return p.SessionID +} + +// SessionModelsEventPayload is the payload for session models events. +type SessionModelsEventPayload struct { + TaskID string `json:"task_id"` + SessionID string `json:"session_id"` + AgentID string `json:"agent_id"` + CurrentModelID string `json:"current_model_id"` + Models []streams.SessionModelInfo `json:"models"` + ConfigOptions []streams.ConfigOption `json:"config_options,omitempty"` + Timestamp string `json:"timestamp"` +} + +// GetSessionID returns the session ID for this event (used by event routing). +func (p SessionModelsEventPayload) GetSessionID() string { + return p.SessionID +} + +// SessionTodosEventPayload is the payload for session todos (ACP plan entries) events. +type SessionTodosEventPayload struct { + TaskID string `json:"task_id"` + SessionID string `json:"session_id"` + AgentID string `json:"agent_id"` + Entries []streams.PlanEntry `json:"entries"` + Timestamp string `json:"timestamp"` +} + +// GetSessionID returns the session ID for this event (used by event routing). +func (p SessionTodosEventPayload) GetSessionID() string { + return p.SessionID +} + +// SessionPromptUsageEventPayload is the payload for prompt usage events. +type SessionPromptUsageEventPayload struct { + TaskID string `json:"task_id"` + SessionID string `json:"session_id"` + AgentID string `json:"agent_id"` + Usage *streams.PromptUsage `json:"usage"` + Timestamp string `json:"timestamp"` +} + +// GetSessionID returns the session ID for this event (used by event routing). +func (p SessionPromptUsageEventPayload) GetSessionID() string { + return p.SessionID +} diff --git a/apps/backend/internal/agent/lifecycle/events.go b/apps/backend/internal/agent/lifecycle/events.go index 1479a0e3be..080a0a95c8 100644 --- a/apps/backend/internal/agent/lifecycle/events.go +++ b/apps/backend/internal/agent/lifecycle/events.go @@ -130,24 +130,34 @@ func (p *EventPublisher) PublishAgentStreamEvent(execution *AgentExecution, even // Build the nested event data // event.SessionID is the ACP session ID (internal agent protocol session) eventData := &AgentStreamEventData{ - Type: event.Type, - ACPSessionID: event.SessionID, - Text: event.Text, - ToolCallID: event.ToolCallID, - ParentToolCallID: event.ParentToolCallID, - PendingID: event.PendingID, - ToolName: event.ToolName, - ToolTitle: event.ToolTitle, - ToolStatus: event.ToolStatus, - Error: event.Error, - SessionStatus: event.SessionStatus, - Data: event.Data, - Normalized: event.NormalizedPayload, - AvailableCommands: event.AvailableCommands, - ToolCallContents: event.ToolCallContents, - ContentBlocks: event.ContentBlocks, - Role: event.Role, - CurrentModeID: event.CurrentModeID, + Type: event.Type, + ACPSessionID: event.SessionID, + Text: event.Text, + ToolCallID: event.ToolCallID, + ParentToolCallID: event.ParentToolCallID, + PendingID: event.PendingID, + ToolName: event.ToolName, + ToolTitle: event.ToolTitle, + ToolStatus: event.ToolStatus, + Error: event.Error, + SessionStatus: event.SessionStatus, + Data: event.Data, + Normalized: event.NormalizedPayload, + AvailableCommands: event.AvailableCommands, + ToolCallContents: event.ToolCallContents, + ContentBlocks: event.ContentBlocks, + Role: event.Role, + CurrentModeID: event.CurrentModeID, + AvailableModes: event.AvailableModes, + SupportsImage: event.SupportsImage, + SupportsAudio: event.SupportsAudio, + SupportsEmbeddedContext: event.SupportsEmbeddedContext, + AuthMethods: event.AuthMethods, + CurrentModelID: event.CurrentModelID, + SessionModels: event.SessionModels, + ConfigOptions: event.ConfigOptions, + Usage: event.Usage, + PlanEntries: event.PlanEntries, } // Build agent event message payload diff --git a/apps/backend/internal/agent/lifecycle/manager_events.go b/apps/backend/internal/agent/lifecycle/manager_events.go index c7d345afb2..b7ccb3dce5 100644 --- a/apps/backend/internal/agent/lifecycle/manager_events.go +++ b/apps/backend/internal/agent/lifecycle/manager_events.go @@ -349,6 +349,23 @@ func (m *Manager) handleAgentEvent(execution *AgentExecution, event agentctl.Age case "available_commands": m.handleAvailableCommandsEvent(execution, event) return + + case "session_mode": + execution.SetModeState(&CachedModeState{ + CurrentModeID: event.CurrentModeID, + AvailableModes: event.AvailableModes, + }) + // No return — must flow through to PublishAgentStreamEvent so the orchestrator + // can filter and re-publish to the dedicated session mode subject. + + case "session_models": + execution.SetModelState(&CachedModelState{ + CurrentModelID: event.CurrentModelID, + Models: event.SessionModels, + ConfigOptions: event.ConfigOptions, + }) + // No return — must flow through to PublishAgentStreamEvent so the orchestrator + // can persist the model and re-publish to the dedicated session models subject. } m.eventPublisher.PublishAgentStreamEvent(execution, event) diff --git a/apps/backend/internal/agent/lifecycle/manager_interaction.go b/apps/backend/internal/agent/lifecycle/manager_interaction.go index 8c0351c375..7031ad29fb 100644 --- a/apps/backend/internal/agent/lifecycle/manager_interaction.go +++ b/apps/backend/internal/agent/lifecycle/manager_interaction.go @@ -72,6 +72,137 @@ func (m *Manager) CancelAgent(ctx context.Context, executionID string) error { return nil } +// SetSessionMode changes the session mode for a running agent. +// Always uses the execution's current ACPSessionID rather than the caller's copy, +// which may be stale during startup/restart when the session is being re-initialized. +func (m *Manager) SetSessionMode(ctx context.Context, executionID, _ string, modeID string) error { + execution, exists := m.executionStore.Get(executionID) + if !exists { + return fmt.Errorf("execution %q not found", executionID) + } + if execution.agentctl == nil { + return fmt.Errorf("execution %q has no agentctl client", executionID) + } + if !execution.sessionInitialized || execution.ACPSessionID == "" { + return fmt.Errorf("execution %q ACP session is not ready", executionID) + } + return execution.agentctl.SetMode(ctx, execution.ACPSessionID, modeID) +} + +// SetSessionModeBySessionID changes the session mode for a running agent by session ID. +func (m *Manager) SetSessionModeBySessionID(ctx context.Context, sessionID, modeID string) error { + execution, exists := m.executionStore.GetBySessionID(sessionID) + if !exists { + return fmt.Errorf("no agent running for session %q", sessionID) + } + return m.SetSessionMode(ctx, execution.ID, execution.ACPSessionID, modeID) +} + +// SetSessionModel changes the session model for a running agent. +func (m *Manager) SetSessionModel(ctx context.Context, executionID, modelID string) error { + execution, exists := m.executionStore.Get(executionID) + if !exists { + return fmt.Errorf("execution %q not found", executionID) + } + if execution.agentctl == nil { + return fmt.Errorf("execution %q has no agentctl client", executionID) + } + return execution.agentctl.SetModel(ctx, modelID) +} + +// SetSessionModelBySessionID changes the session model for a running agent by session ID. +func (m *Manager) SetSessionModelBySessionID(ctx context.Context, sessionID, modelID string) error { + execution, exists := m.executionStore.GetBySessionID(sessionID) + if !exists { + return fmt.Errorf("no agent running for session %q", sessionID) + } + return m.SetSessionModel(ctx, execution.ID, modelID) +} + +// AuthenticateBySessionID triggers authentication for a given auth method on the agent. +func (m *Manager) AuthenticateBySessionID(ctx context.Context, sessionID, methodID string) error { + execution, exists := m.executionStore.GetBySessionID(sessionID) + if !exists { + return fmt.Errorf("no agent running for session %q", sessionID) + } + if execution.agentctl == nil { + return fmt.Errorf("execution %q has no agentctl client", execution.ID) + } + return execution.agentctl.Authenticate(ctx, methodID) +} + +// ResetAgentContext resets the agent's conversation context. For ACP agents that support +// session reset, this creates a new session on the existing connection (fast, no process restart). +// For all other agents, this falls back to RestartAgentProcess (full subprocess restart). +func (m *Manager) ResetAgentContext(ctx context.Context, executionID string) error { + execution, exists := m.executionStore.Get(executionID) + if !exists { + return fmt.Errorf("execution %q not found: %w", executionID, ErrExecutionNotFound) + } + + // Passthrough agents always need full restart + if execution.PassthroughProcessID != "" { + return m.RestartAgentProcess(ctx, executionID) + } + + if execution.agentctl == nil { + return fmt.Errorf("execution %q has no agentctl client", executionID) + } + + // Resolve agent config and MCP servers for session reset + agentConfig, err := m.getAgentConfigForExecution(execution) + if err != nil { + m.logger.Info("cannot resolve agent config for session reset, falling back to process restart", + zap.String("execution_id", executionID), zap.Error(err)) + return m.RestartAgentProcess(ctx, executionID) + } + + mcpServers, err := m.resolveMcpServers(ctx, execution, agentConfig) + if err != nil { + m.logger.Warn("cannot resolve MCP servers for session reset, falling back to process restart", + zap.String("execution_id", executionID), zap.Error(err)) + return m.RestartAgentProcess(ctx, executionID) + } + + // Try session-level reset (only ACP adapters support this) + newSessionID, err := execution.agentctl.ResetSession(ctx, execution.WorkspacePath, mcpServers) + if err != nil { + m.logger.Info("session reset not supported, falling back to process restart", + zap.String("execution_id", executionID), zap.Error(err)) + return m.RestartAgentProcess(ctx, executionID) + } + + // Success — update execution state without restarting process + _ = m.executionStore.WithLock(executionID, func(exec *AgentExecution) { + exec.ACPSessionID = newSessionID + exec.Status = v1.AgentStatusReady + exec.needsResumeContext = false + exec.resumeContextInjected = false + + exec.messageMu.Lock() + exec.messageBuffer.Reset() + exec.thinkingBuffer.Reset() + exec.currentMessageID = "" + exec.currentThinkingID = "" + exec.messageMu.Unlock() + + // Drain any stale prompt completion signal + select { + case <-exec.promptDoneCh: + default: + } + }) + + m.logger.Info("agent context reset via session (no process restart)", + zap.String("execution_id", executionID), + zap.String("session_id", execution.SessionID), + zap.String("new_acp_session_id", newSessionID)) + + m.eventPublisher.PublishAgentEvent(ctx, events.AgentContextReset, execution) + m.eventPublisher.PublishAgentEvent(ctx, events.AgentReady, execution) + return nil +} + // CancelAgentBySessionID cancels the current agent turn for a specific session func (m *Manager) CancelAgentBySessionID(ctx context.Context, sessionID string) error { execution, exists := m.executionStore.GetBySessionID(sessionID) @@ -369,6 +500,26 @@ func (m *Manager) GetAvailableCommandsForSession(sessionID string) []streams.Ava return execution.GetAvailableCommands() } +// GetModeStateForSession returns the cached session mode state. +// Returns nil if the session has no execution or no mode state cached. +func (m *Manager) GetModeStateForSession(sessionID string) *CachedModeState { + execution, exists := m.executionStore.GetBySessionID(sessionID) + if !exists { + return nil + } + return execution.GetModeState() +} + +// GetModelStateForSession returns the cached session model state. +// Returns nil if the session has no execution or no model state cached. +func (m *Manager) GetModelStateForSession(sessionID string) *CachedModelState { + execution, exists := m.executionStore.GetBySessionID(sessionID) + if !exists { + return nil + } + return execution.GetModelState() +} + // ListExecutions returns all currently tracked agent executions. // // Returns a snapshot of all executions in memory at the time of call. The returned slice @@ -520,6 +671,16 @@ func (m *Manager) MarkCompleted(executionID string, exitCode int, errorMessage s return fmt.Errorf("execution %q not found", executionID) } + // Guard against duplicate completion (e.g. ACP prompt error + process exit error). + // MarkCompleted is a terminal transition — once in Completed/Failed, skip re-publishing. + if execution.Status == v1.AgentStatusCompleted || execution.Status == v1.AgentStatusFailed { + m.logger.Warn("ignoring duplicate MarkCompleted for already-terminal execution", + zap.String("execution_id", executionID), + zap.String("current_status", string(execution.Status)), + zap.Int("exit_code", exitCode)) + return nil + } + _ = m.executionStore.WithLock(executionID, func(exec *AgentExecution) { now := time.Now() exec.FinishedAt = &now diff --git a/apps/backend/internal/agent/lifecycle/manager_lifecycle_test.go b/apps/backend/internal/agent/lifecycle/manager_lifecycle_test.go index 1bfdb2dcfa..f9118c3854 100644 --- a/apps/backend/internal/agent/lifecycle/manager_lifecycle_test.go +++ b/apps/backend/internal/agent/lifecycle/manager_lifecycle_test.go @@ -72,6 +72,34 @@ func TestManager_MarkCompleted_Failure(t *testing.T) { } } +func TestManager_MarkCompleted_Idempotent(t *testing.T) { + mgr := newTestManager() + + execution := &AgentExecution{ + ID: "test-execution-id", + TaskID: "test-task-id", + AgentProfileID: "test-agent", + Status: v1.AgentStatusFailed, + StartedAt: time.Now(), + } + exitCode := 1 + execution.ExitCode = &exitCode + execution.ErrorMessage = "first error" + + mgr.executionStore.Add(execution) + + // Second MarkCompleted should be a no-op (already terminal) + err := mgr.MarkCompleted("test-execution-id", 1, "second error") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + got, _ := mgr.GetExecution("test-execution-id") + if got.ErrorMessage != "first error" { + t.Errorf("expected original error message preserved, got %q", got.ErrorMessage) + } +} + func TestManager_MarkCompleted_NotFound(t *testing.T) { mgr := newTestManager() diff --git a/apps/backend/internal/agent/lifecycle/manager_profile.go b/apps/backend/internal/agent/lifecycle/manager_profile.go index b4d806a3da..cd8f7c8fab 100644 --- a/apps/backend/internal/agent/lifecycle/manager_profile.go +++ b/apps/backend/internal/agent/lifecycle/manager_profile.go @@ -144,7 +144,21 @@ func runtimeName(rt ExecutorBackend) executor.Name { return rt.Name() } +// resolveProfileModel resolves the model configured on an agent profile. +// Returns empty string if the profile cannot be resolved. +func (m *Manager) resolveProfileModel(ctx context.Context, profileID string) string { + if profileID == "" || m.profileResolver == nil { + return "" + } + info, err := m.profileResolver.ResolveProfile(ctx, profileID) + if err != nil || info == nil { + return "" + } + return info.Model +} + // initializeACPSession delegates to SessionManager for full ACP session initialization and prompting func (m *Manager) initializeACPSession(ctx context.Context, execution *AgentExecution, agentConfig agents.Agent, taskDescription string, mcpServers []agentctltypes.McpServer) error { - return m.sessionManager.InitializeAndPrompt(ctx, execution, agentConfig, taskDescription, mcpServers, m.MarkReady) + profileModel := m.resolveProfileModel(ctx, execution.AgentProfileID) + return m.sessionManager.InitializeAndPrompt(ctx, execution, agentConfig, taskDescription, mcpServers, m.MarkReady, profileModel) } diff --git a/apps/backend/internal/agent/lifecycle/session.go b/apps/backend/internal/agent/lifecycle/session.go index 092937a285..579cdf43cc 100644 --- a/apps/backend/internal/agent/lifecycle/session.go +++ b/apps/backend/internal/agent/lifecycle/session.go @@ -124,6 +124,11 @@ func (sm *SessionManager) createOrLoadSession( mcpServers []agentctltypes.McpServer, ) (string, error) { rt := agentConfig.Runtime() + sm.logger.Debug("createOrLoadSession decision", + zap.String("agent_type", agentConfig.ID()), + zap.Bool("native_session_resume", rt.SessionConfig.NativeSessionResume), + zap.String("existing_session_id", existingSessionID), + zap.Bool("will_attempt_load", rt.SessionConfig.NativeSessionResume && existingSessionID != "")) if rt.SessionConfig.NativeSessionResume && existingSessionID != "" { sessionID, err := sm.loadSession(ctx, client, agentConfig, existingSessionID) if err != nil { @@ -258,6 +263,7 @@ func (sm *SessionManager) InitializeAndPrompt( taskDescription string, mcpServers []agentctltypes.McpServer, markReady func(executionID string) error, + profileModel string, ) error { // Create session-level trace span to group all operations under one trace _, sessionSpan := tracing.TraceSessionStart( @@ -321,6 +327,21 @@ func (sm *SessionManager) InitializeAndPrompt( execution.ACPSessionID = result.SessionID execution.sessionInitialized = true + // Set the user's configured profile model if it differs from the agent's default. + // ACP agents ignore --model CLI flags, so the model must be set via ACP protocol. + if profileModel != "" && profileModel != agentConfig.DefaultModel() && execution.agentctl != nil { + if err := execution.agentctl.SetModel(ctx, profileModel); err != nil { + sm.logger.Warn("failed to set profile model via ACP", + zap.String("execution_id", execution.ID), + zap.String("model", profileModel), + zap.Error(err)) + } else { + sm.logger.Info("set profile model on ACP session", + zap.String("execution_id", execution.ID), + zap.String("model", profileModel)) + } + } + // Publish session created event if sm.eventPublisher != nil { sm.eventPublisher.PublishACPSessionCreated(execution, result.SessionID) diff --git a/apps/backend/internal/agent/lifecycle/session_test.go b/apps/backend/internal/agent/lifecycle/session_test.go index 6d89482125..2e09070e89 100644 --- a/apps/backend/internal/agent/lifecycle/session_test.go +++ b/apps/backend/internal/agent/lifecycle/session_test.go @@ -234,7 +234,7 @@ func TestInitializeAndPrompt_StreamBeforeInitialize(t *testing.T) { err := sm.InitializeAndPrompt(ctx, execution, agentConfig, "", nil, func(executionID string) error { return nil - }) + }, "") if err != nil { t.Fatalf("InitializeAndPrompt failed: %v", err) } @@ -306,7 +306,7 @@ func TestInitializeAndPrompt_StreamTimeout(t *testing.T) { err := sm.InitializeAndPrompt(ctx, execution, agentConfig, "", nil, func(executionID string) error { return nil - }) + }, "") // Should fail because stream couldn't connect and Initialize fails if err == nil { @@ -359,7 +359,7 @@ func TestInitializeAndPrompt_WithTaskDescription(t *testing.T) { err := sm.InitializeAndPrompt(ctx, execution, agentConfig, "Build a feature", nil, func(executionID string) error { return nil - }) + }, "") if err != nil { t.Fatalf("InitializeAndPrompt failed: %v", err) } @@ -427,7 +427,7 @@ func TestInitializeAndPrompt_NoStreamManager(t *testing.T) { // But it should NOT panic due to nil streamManager. err := sm.InitializeAndPrompt(ctx, execution, agentConfig, "", nil, func(executionID string) error { return nil - }) + }, "") // Expect error because Initialize call over WS will fail (stream not connected) if err == nil { diff --git a/apps/backend/internal/agent/lifecycle/types.go b/apps/backend/internal/agent/lifecycle/types.go index 0e9e42eeeb..43fc6425a7 100644 --- a/apps/backend/internal/agent/lifecycle/types.go +++ b/apps/backend/internal/agent/lifecycle/types.go @@ -84,6 +84,14 @@ type AgentExecution struct { availableCommands []streams.AvailableCommand availableCommandsMu sync.RWMutex + // Cached session mode state (for re-sending on subscribe after page refresh) + modeState *CachedModeState + modeStateMu sync.RWMutex + + // Cached session model state (for re-sending on subscribe after page refresh) + modelState *CachedModelState + modelStateMu sync.RWMutex + // Channel signaled by handleAgentEvent(complete) or stream disconnect to unblock SendPrompt. // Buffered (size 1) so the sender never blocks. promptDoneCh chan PromptCompletionSignal @@ -140,6 +148,47 @@ func (ae *AgentExecution) GetAvailableCommands() []streams.AvailableCommand { return ae.availableCommands } +// CachedModeState holds the last-known session mode state for re-sending on subscribe. +type CachedModeState struct { + CurrentModeID string + AvailableModes []streams.SessionModeInfo +} + +// CachedModelState holds the last-known session model state for re-sending on subscribe. +type CachedModelState struct { + CurrentModelID string + Models []streams.SessionModelInfo + ConfigOptions []streams.ConfigOption +} + +// SetModeState caches the session mode state on this execution. +func (ae *AgentExecution) SetModeState(state *CachedModeState) { + ae.modeStateMu.Lock() + defer ae.modeStateMu.Unlock() + ae.modeState = state +} + +// GetModeState returns the cached session mode state. +func (ae *AgentExecution) GetModeState() *CachedModeState { + ae.modeStateMu.RLock() + defer ae.modeStateMu.RUnlock() + return ae.modeState +} + +// SetModelState caches the session model state on this execution. +func (ae *AgentExecution) SetModelState(state *CachedModelState) { + ae.modelStateMu.Lock() + defer ae.modelStateMu.Unlock() + ae.modelState = state +} + +// GetModelState returns the cached session model state. +func (ae *AgentExecution) GetModelState() *CachedModelState { + ae.modelStateMu.RLock() + defer ae.modelStateMu.RUnlock() + return ae.modelState +} + // SetSessionSpan stores the session-level trace span on the execution. func (ae *AgentExecution) SetSessionSpan(span trace.Span) { ae.sessionSpanMu.Lock() diff --git a/apps/backend/internal/agent/registry/registry.go b/apps/backend/internal/agent/registry/registry.go index 72c6ef4fc3..3f9a941c3a 100644 --- a/apps/backend/internal/agent/registry/registry.go +++ b/apps/backend/internal/agent/registry/registry.go @@ -47,12 +47,16 @@ func (r *Registry) LoadDefaults() { all := []agents.Agent{ agents.NewAuggie(), agents.NewClaudeCode(), + agents.NewClaudeACP(), agents.NewCodex(), + agents.NewCodexACP(), agents.NewCopilot(), + agents.NewCopilotACP(), agents.NewGemini(), agents.NewOpenCode(), agents.NewOpenCodeACP(), agents.NewAmp(), + agents.NewAmpACP(), agents.NewMockAgent(), } diff --git a/apps/backend/internal/agentctl/client/agent.go b/apps/backend/internal/agentctl/client/agent.go index 1e73ac8e84..fb81533823 100644 --- a/apps/backend/internal/agentctl/client/agent.go +++ b/apps/backend/internal/agentctl/client/agent.go @@ -77,36 +77,48 @@ type NewSessionResponse struct { Error string `json:"error,omitempty"` } -// NewSession creates a new ACP session via the agent WebSocket stream. -func (c *Client) NewSession(ctx context.Context, cwd string, mcpServers []types.McpServer) (string, error) { +// createSessionRequest sends a session creation request and parses the response. +// Used by both NewSession and ResetSession which share the same payload/response format. +func (c *Client) createSessionRequest(ctx context.Context, action, cwd string, mcpServers []types.McpServer) (string, error) { payload := struct { Cwd string `json:"cwd"` McpServers []types.McpServer `json:"mcp_servers,omitempty"` }{Cwd: cwd, McpServers: mcpServers} - resp, err := c.sendStreamRequest(ctx, "agent.session.new", payload) + resp, err := c.sendStreamRequest(ctx, action, payload) if err != nil { - return "", fmt.Errorf("new session request failed: %w", err) + return "", fmt.Errorf("%s request failed: %w", action, err) } if resp.Type == ws.MessageTypeError { var errPayload ws.ErrorPayload if err := resp.ParsePayload(&errPayload); err != nil { - return "", fmt.Errorf("new session failed: unable to parse error") + return "", fmt.Errorf("%s failed: unable to parse error", action) } - return "", fmt.Errorf("new session failed: %s", errPayload.Message) + return "", fmt.Errorf("%s failed: %s", action, errPayload.Message) } var result NewSessionResponse if err := resp.ParsePayload(&result); err != nil { - return "", fmt.Errorf("failed to parse new session response: %w", err) + return "", fmt.Errorf("failed to parse %s response: %w", action, err) } if !result.Success { - return "", fmt.Errorf("new session failed: %s", result.Error) + return "", fmt.Errorf("%s failed: %s", action, result.Error) } return result.SessionID, nil } +// NewSession creates a new ACP session via the agent WebSocket stream. +func (c *Client) NewSession(ctx context.Context, cwd string, mcpServers []types.McpServer) (string, error) { + return c.createSessionRequest(ctx, "agent.session.new", cwd, mcpServers) +} + +// ResetSession creates a new session on the same connection, resetting context without +// restarting the subprocess. Returns the new session ID or an error if not supported. +func (c *Client) ResetSession(ctx context.Context, cwd string, mcpServers []types.McpServer) (string, error) { + return c.createSessionRequest(ctx, "agent.session.reset", cwd, mcpServers) +} + // LoadSession resumes an existing ACP session via the agent WebSocket stream. func (c *Client) LoadSession(ctx context.Context, sessionID string) error { payload := struct { @@ -139,6 +151,73 @@ func (c *Client) LoadSession(ctx context.Context, sessionID string) error { return nil } +// SetMode changes the agent's session mode via the agent WebSocket stream. +func (c *Client) SetMode(ctx context.Context, sessionID, modeID string) error { + payload := struct { + SessionID string `json:"session_id"` + ModeID string `json:"mode_id"` + }{SessionID: sessionID, ModeID: modeID} + + resp, err := c.sendStreamRequest(ctx, "agent.session.set_mode", payload) + if err != nil { + return fmt.Errorf("set mode request failed: %w", err) + } + + if resp.Type == ws.MessageTypeError { + var errPayload ws.ErrorPayload + if err := resp.ParsePayload(&errPayload); err != nil { + return fmt.Errorf("set mode failed: unable to parse error") + } + return fmt.Errorf("set mode failed: %s", errPayload.Message) + } + + return nil +} + +// SetModel changes the agent's model via the agent WebSocket stream. +func (c *Client) SetModel(ctx context.Context, modelID string) error { + payload := struct { + ModelID string `json:"model_id"` + }{ModelID: modelID} + + resp, err := c.sendStreamRequest(ctx, "agent.session.set_model", payload) + if err != nil { + return fmt.Errorf("set model request failed: %w", err) + } + + if resp.Type == ws.MessageTypeError { + var errPayload ws.ErrorPayload + if err := resp.ParsePayload(&errPayload); err != nil { + return fmt.Errorf("set model failed: unable to parse error") + } + return fmt.Errorf("set model failed: %s", errPayload.Message) + } + + return nil +} + +// Authenticate triggers authentication for a given auth method via the agent WebSocket stream. +func (c *Client) Authenticate(ctx context.Context, methodID string) error { + payload := struct { + MethodID string `json:"method_id"` + }{MethodID: methodID} + + resp, err := c.sendStreamRequest(ctx, "agent.session.authenticate", payload) + if err != nil { + return fmt.Errorf("authenticate request failed: %w", err) + } + + if resp.Type == ws.MessageTypeError { + var errPayload ws.ErrorPayload + if err := resp.ParsePayload(&errPayload); err != nil { + return fmt.Errorf("authenticate failed: unable to parse error") + } + return fmt.Errorf("authenticate failed: %s", errPayload.Message) + } + + return nil +} + // Prompt sends a fire-and-forget prompt to the agent via the agent WebSocket stream. // The server returns an accepted response immediately; completion is signaled via stream events. // Attachments (images) are passed to the agent if provided. diff --git a/apps/backend/internal/agentctl/server/acp/client.go b/apps/backend/internal/agentctl/server/acp/client.go index 272d120396..0caed5f91b 100644 --- a/apps/backend/internal/agentctl/server/acp/client.go +++ b/apps/backend/internal/agentctl/server/acp/client.go @@ -27,6 +27,7 @@ type PermissionRequestHandler func(ctx context.Context, req *types.PermissionReq type Client struct { logger *zap.Logger workspaceRoot string + terminals *TerminalManager mu sync.RWMutex updateHandler UpdateHandler @@ -73,6 +74,7 @@ func NewClient(opts ...ClientOption) *Client { for _, opt := range opts { opt(c) } + c.terminals = NewTerminalManager(c.logger) return c } @@ -363,55 +365,98 @@ func (c *Client) WriteTextFile(ctx context.Context, p acp.WriteTextFileRequest) return acp.WriteTextFileResponse{}, err } -// CreateTerminal creates a new terminal +// CreateTerminal starts a command in a new terminal. func (c *Client) CreateTerminal(ctx context.Context, p acp.CreateTerminalRequest) (acp.CreateTerminalResponse, error) { _, span := shared.TraceProtocolRequest(ctx, shared.ProtocolACP, "", "request.create_terminal") defer span.End() span.SetAttributes(attribute.String("command", p.Command)) - c.logger.Debug("create terminal request", zap.String("command", p.Command)) - return acp.CreateTerminalResponse{TerminalId: "t-1"}, nil + c.logger.Debug("create terminal request", + zap.String("command", p.Command), + zap.Strings("args", p.Args), + ) + + cwd := c.workspaceRoot + if p.Cwd != nil { + cwd = *p.Cwd + } + env := make(map[string]string, len(p.Env)) + for _, e := range p.Env { + env[e.Name] = e.Value + } + limit := 0 + if p.OutputByteLimit != nil { + limit = *p.OutputByteLimit + } + + id, err := c.terminals.Create(p.Command, p.Args, cwd, env, limit) + if err != nil { + span.RecordError(err) + return acp.CreateTerminalResponse{}, err + } + return acp.CreateTerminalResponse{TerminalId: id}, nil } -// KillTerminalCommand kills a terminal command +// KillTerminalCommand sends SIGTERM to a terminal's process. func (c *Client) KillTerminalCommand(ctx context.Context, p acp.KillTerminalCommandRequest) (acp.KillTerminalCommandResponse, error) { _, span := shared.TraceProtocolRequest(ctx, shared.ProtocolACP, "", "request.kill_terminal_command") defer span.End() span.SetAttributes(attribute.String("terminal_id", p.TerminalId)) - c.logger.Debug("kill terminal request", zap.String("terminal_id", p.TerminalId)) + if err := c.terminals.Kill(p.TerminalId); err != nil { + span.RecordError(err) + return acp.KillTerminalCommandResponse{}, err + } return acp.KillTerminalCommandResponse{}, nil } -// TerminalOutput gets terminal output +// TerminalOutput returns the current output of a terminal. func (c *Client) TerminalOutput(ctx context.Context, p acp.TerminalOutputRequest) (acp.TerminalOutputResponse, error) { _, span := shared.TraceProtocolRequest(ctx, shared.ProtocolACP, "", "request.terminal_output") defer span.End() span.SetAttributes(attribute.String("terminal_id", p.TerminalId)) - c.logger.Debug("terminal output request", zap.String("terminal_id", p.TerminalId)) - return acp.TerminalOutputResponse{Output: "ok", Truncated: false}, nil + output, truncated, exitCode, signal, err := c.terminals.Output(p.TerminalId) + if err != nil { + span.RecordError(err) + return acp.TerminalOutputResponse{}, err + } + + resp := acp.TerminalOutputResponse{ + Output: output, + Truncated: truncated, + } + if exitCode != nil || signal != nil { + resp.ExitStatus = &acp.TerminalExitStatus{ + ExitCode: exitCode, + Signal: signal, + } + } + return resp, nil } -// ReleaseTerminal releases a terminal +// ReleaseTerminal kills (if running) and releases a terminal. func (c *Client) ReleaseTerminal(ctx context.Context, p acp.ReleaseTerminalRequest) (acp.ReleaseTerminalResponse, error) { _, span := shared.TraceProtocolRequest(ctx, shared.ProtocolACP, "", "request.release_terminal") defer span.End() span.SetAttributes(attribute.String("terminal_id", p.TerminalId)) - c.logger.Debug("release terminal request", zap.String("terminal_id", p.TerminalId)) + _ = c.terminals.Release(p.TerminalId) return acp.ReleaseTerminalResponse{}, nil } -// WaitForTerminalExit waits for terminal to exit +// WaitForTerminalExit blocks until the terminal's command exits. func (c *Client) WaitForTerminalExit(ctx context.Context, p acp.WaitForTerminalExitRequest) (acp.WaitForTerminalExitResponse, error) { _, span := shared.TraceProtocolRequest(ctx, shared.ProtocolACP, "", "request.wait_for_terminal_exit") defer span.End() span.SetAttributes(attribute.String("terminal_id", p.TerminalId)) - c.logger.Debug("wait for terminal exit request", zap.String("terminal_id", p.TerminalId)) - exitCode := 0 - return acp.WaitForTerminalExitResponse{ExitCode: &exitCode}, nil + exitCode, signal, err := c.terminals.WaitForExit(p.TerminalId) + if err != nil { + span.RecordError(err) + return acp.WaitForTerminalExitResponse{}, err + } + return acp.WaitForTerminalExitResponse{ExitCode: exitCode, Signal: signal}, nil } // Verify interface implementation diff --git a/apps/backend/internal/agentctl/server/acp/terminal.go b/apps/backend/internal/agentctl/server/acp/terminal.go new file mode 100644 index 0000000000..9884d2c837 --- /dev/null +++ b/apps/backend/internal/agentctl/server/acp/terminal.go @@ -0,0 +1,232 @@ +package acp + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "sync" + "sync/atomic" + "syscall" + + "go.uber.org/zap" +) + +// terminal represents a single ACP terminal (one command execution). +type terminal struct { + cmd *exec.Cmd + output *terminalOutput + doneCh chan struct{} // closed when the process exits + mu sync.Mutex + killed bool +} + +// terminalOutput is a thread-safe, bounded output buffer. +type terminalOutput struct { + mu sync.Mutex + buf bytes.Buffer + limit int + truncated bool +} + +func newTerminalOutput(limit int) *terminalOutput { + if limit <= 0 { + limit = 1024 * 1024 // 1MB default + } + return &terminalOutput{limit: limit} +} + +func (o *terminalOutput) Write(p []byte) (int, error) { + o.mu.Lock() + defer o.mu.Unlock() + n, err := o.buf.Write(p) + if o.buf.Len() > o.limit { + excess := o.buf.Len() - o.limit + o.buf.Next(excess) + o.truncated = true + } + return n, err +} + +func (o *terminalOutput) snapshot() (string, bool) { + o.mu.Lock() + defer o.mu.Unlock() + return o.buf.String(), o.truncated +} + +// TerminalManager manages ACP terminal instances. +type TerminalManager struct { + logger *zap.Logger + nextID atomic.Int64 + + mu sync.RWMutex + terminals map[string]*terminal +} + +// NewTerminalManager creates a new terminal manager. +func NewTerminalManager(logger *zap.Logger) *TerminalManager { + return &TerminalManager{ + logger: logger, + terminals: make(map[string]*terminal), + } +} + +// Create starts a command in a new terminal and returns its ID. +func (m *TerminalManager) Create(command string, args []string, cwd string, env map[string]string, outputByteLimit int) (string, error) { + id := fmt.Sprintf("t-%d", m.nextID.Add(1)) + + cmd := exec.Command(command, args...) + if cwd != "" { + cmd.Dir = cwd + } + if len(env) > 0 { + cmd.Env = os.Environ() + for k, v := range env { + cmd.Env = append(cmd.Env, k+"="+v) + } + } + + out := newTerminalOutput(outputByteLimit) + cmd.Stdout = out + cmd.Stderr = out + + if err := cmd.Start(); err != nil { + return "", fmt.Errorf("start command %q: %w", command, err) + } + + t := &terminal{ + cmd: cmd, + output: out, + doneCh: make(chan struct{}), + } + + // Wait for exit in background and close doneCh. + go func() { + _ = cmd.Wait() + close(t.doneCh) + }() + + m.mu.Lock() + m.terminals[id] = t + m.mu.Unlock() + + m.logger.Debug("terminal created", + zap.String("terminal_id", id), + zap.String("command", command), + zap.Strings("args", args), + ) + return id, nil +} + +// Output returns the current output of a terminal. +func (m *TerminalManager) Output(id string) (output string, truncated bool, exitCode *int, signal *string, err error) { + m.mu.RLock() + t, ok := m.terminals[id] + m.mu.RUnlock() + if !ok { + return "", false, nil, nil, fmt.Errorf("terminal %q not found", id) + } + + output, truncated = t.output.snapshot() + + // Check if process has exited. + select { + case <-t.doneCh: + code, sig := exitStatus(t.cmd) + return output, truncated, code, sig, nil + default: + return output, truncated, nil, nil, nil + } +} + +// WaitForExit blocks until the terminal's command exits. +func (m *TerminalManager) WaitForExit(id string) (exitCode *int, signal *string, err error) { + m.mu.RLock() + t, ok := m.terminals[id] + m.mu.RUnlock() + if !ok { + return nil, nil, fmt.Errorf("terminal %q not found", id) + } + + <-t.doneCh + code, sig := exitStatus(t.cmd) + return code, sig, nil +} + +// Kill sends SIGTERM to the terminal's process without releasing resources. +func (m *TerminalManager) Kill(id string) error { + m.mu.RLock() + t, ok := m.terminals[id] + m.mu.RUnlock() + if !ok { + return fmt.Errorf("terminal %q not found", id) + } + + t.mu.Lock() + defer t.mu.Unlock() + if t.killed { + return nil + } + t.killed = true + + if t.cmd.Process != nil { + _ = t.cmd.Process.Signal(syscall.SIGTERM) + } + return nil +} + +// Release kills the terminal (if still running) and removes it. +func (m *TerminalManager) Release(id string) error { + m.mu.Lock() + t, ok := m.terminals[id] + if ok { + delete(m.terminals, id) + } + m.mu.Unlock() + if !ok { + return nil + } + + t.mu.Lock() + if !t.killed && t.cmd.Process != nil { + _ = t.cmd.Process.Signal(syscall.SIGKILL) + } + t.mu.Unlock() + + m.logger.Debug("terminal released", zap.String("terminal_id", id)) + return nil +} + +// ReleaseAll kills and removes all terminals. +func (m *TerminalManager) ReleaseAll() { + m.mu.Lock() + terminals := m.terminals + m.terminals = make(map[string]*terminal) + m.mu.Unlock() + + for id, t := range terminals { + if t.cmd.Process != nil { + _ = t.cmd.Process.Signal(syscall.SIGKILL) + } + m.logger.Debug("terminal released (shutdown)", zap.String("terminal_id", id)) + } +} + +// exitStatus extracts exit code and signal from a completed command. +func exitStatus(cmd *exec.Cmd) (*int, *string) { + state := cmd.ProcessState + if state == nil { + return nil, nil + } + ws, ok := state.Sys().(syscall.WaitStatus) + if !ok { + code := state.ExitCode() + return &code, nil + } + if ws.Signaled() { + sig := ws.Signal().String() + return nil, &sig + } + code := ws.ExitStatus() + return &code, nil +} diff --git a/apps/backend/internal/agentctl/server/adapter/adapter.go b/apps/backend/internal/agentctl/server/adapter/adapter.go index 612cb7a343..3a430c7126 100644 --- a/apps/backend/internal/agentctl/server/adapter/adapter.go +++ b/apps/backend/internal/agentctl/server/adapter/adapter.go @@ -88,6 +88,31 @@ type StderrProviderSetter interface { SetStderrProvider(provider StderrProvider) } +// ModeSettableAdapter is an optional interface implemented by adapters that +// support changing the session mode (e.g., ACP adapters with session/set_mode). +type ModeSettableAdapter interface { + SetMode(ctx context.Context, modeID string) error +} + +// ModelSettableAdapter is an optional interface implemented by adapters that +// support changing the session model (e.g., ACP adapters with session/set_model). +type ModelSettableAdapter interface { + SetModel(ctx context.Context, modelID string) error +} + +// AuthenticatableAdapter is an optional interface implemented by adapters that +// support ACP authentication (session/authenticate). +type AuthenticatableAdapter interface { + Authenticate(ctx context.Context, methodID string) error +} + +// SessionResettableAdapter is an optional interface implemented by adapters that +// can reset context by creating a new session on the same connection, without +// restarting the agent subprocess. Only ACP adapters support this. +type SessionResettableAdapter interface { + ResetSession(ctx context.Context, mcpServers []types.McpServer) (string, error) +} + // AgentInfo contains information about the connected agent. type AgentInfo struct { Name string `json:"name"` diff --git a/apps/backend/internal/agentctl/server/adapter/amp_adapter.go b/apps/backend/internal/agentctl/server/adapter/amp_adapter.go index 14d2179f04..8faa7884b4 100644 --- a/apps/backend/internal/agentctl/server/adapter/amp_adapter.go +++ b/apps/backend/internal/agentctl/server/adapter/amp_adapter.go @@ -92,6 +92,9 @@ type AmpAdapter struct { // Set in handleMessage before dispatch; used by sendUpdate for OTel tracing. lastRawData json.RawMessage + // Attachment management + attachMgr *shared.AttachmentManager + // Synchronization mu sync.RWMutex closed bool @@ -104,9 +107,10 @@ const defaultAmpContextWindow = 200000 func NewAmpAdapter(cfg *Config, log *logger.Logger) *AmpAdapter { ctx, cancel := context.WithCancel(context.Background()) + l := log.WithFields(zap.String("adapter", "amp")) return &AmpAdapter{ cfg: cfg, - logger: log.WithFields(zap.String("adapter", "amp")), + logger: l, normalizer: NewAmpNormalizer(), oneShotCfg: cfg.OneShotConfig, ctx: ctx, @@ -115,6 +119,7 @@ func NewAmpAdapter(cfg *Config, log *logger.Logger) *AmpAdapter { mainModelContextWindow: defaultAmpContextWindow, pendingToolCalls: make(map[string]bool), pendingToolPayloads: make(map[string]*streams.NormalizedPayload), + attachMgr: shared.NewAttachmentManager(cfg.WorkDir, l.Zap()), } } @@ -193,6 +198,7 @@ func (a *AmpAdapter) NewSession(ctx context.Context, _ []types.McpServer) (strin // Generate a placeholder session ID - Amp will return its thread ID sessionID := uuid.New().String() a.sessionID = sessionID + a.attachMgr.SetSessionID(sessionID) a.logger.Info("created new session placeholder", zap.String("session_id", sessionID)) @@ -206,6 +212,7 @@ func (a *AmpAdapter) LoadSession(ctx context.Context, sessionID string) error { a.sessionID = sessionID a.hasAmpThreadID = sessionID != "" // LoadSession always receives a real Amp thread ID a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) // Set thread ID in client for tracking (only for non-one-shot) if a.client != nil { @@ -220,11 +227,26 @@ func (a *AmpAdapter) LoadSession(ctx context.Context, sessionID string) error { // Prompt sends a prompt to Amp and waits for completion. // In one-shot mode, this spawns a new subprocess per prompt. // Note: attachments are not yet supported in Amp protocol - they are ignored. -func (a *AmpAdapter) Prompt(ctx context.Context, message string, _ []v1.MessageAttachment) error { - if a.oneShotCfg != nil { - return a.promptOneShot(ctx, message) +func (a *AmpAdapter) Prompt(ctx context.Context, message string, attachments []v1.MessageAttachment) error { + // Save attachments to workspace and prepend references to message + finalMessage := message + if len(attachments) > 0 { + saved, err := a.attachMgr.SaveAttachments(attachments) + if err != nil { + a.logger.Warn("failed to save attachments", zap.Error(err)) + } else if len(saved) > 0 { + finalMessage = shared.BuildAttachmentPrompt(saved) + message + } } - return a.promptLongLived(ctx, message) + + if a.oneShotCfg != nil { + err := a.promptOneShot(ctx, finalMessage) + a.attachMgr.Cleanup() + return err + } + err := a.promptLongLived(ctx, finalMessage) + a.attachMgr.Cleanup() + return err } // oneShotProcess holds the state of a one-shot subprocess spawned for a single prompt. @@ -495,6 +517,9 @@ func (a *AmpAdapter) Close() error { a.logger.Info("closing Amp adapter") + // Clean up any saved attachments + a.attachMgr.Cleanup() + // Cancel the context if a.cancel != nil { a.cancel() diff --git a/apps/backend/internal/agentctl/server/adapter/copilot_adapter.go b/apps/backend/internal/agentctl/server/adapter/copilot_adapter.go index 2066241122..53ad7ef488 100644 --- a/apps/backend/internal/agentctl/server/adapter/copilot_adapter.go +++ b/apps/backend/internal/agentctl/server/adapter/copilot_adapter.go @@ -82,6 +82,9 @@ type CopilotAdapter struct { // Set in handleEvent before dispatch; used by sendUpdate for OTel tracing. lastRawData json.RawMessage + // Attachment management + attachMgr *shared.AttachmentManager + // Synchronization mu sync.RWMutex closed bool @@ -103,15 +106,17 @@ const mcpServerTypeHTTP = "http" func NewCopilotAdapter(cfg *Config, log *logger.Logger) *CopilotAdapter { ctx, cancel := context.WithCancel(context.Background()) + l := log.WithFields(zap.String("adapter", "copilot")) return &CopilotAdapter{ cfg: cfg, - logger: log.WithFields(zap.String("adapter", "copilot")), + logger: l, normalizer: NewCopilotNormalizer(), ctx: ctx, cancel: cancel, updatesCh: make(chan AgentEvent, 100), contextWindowSize: defaultCopilotContextWindow, pendingToolPayloads: make(map[string]*streams.NormalizedPayload), + attachMgr: shared.NewAttachmentManager(cfg.WorkDir, l.Zap()), } } @@ -316,6 +321,7 @@ func (a *CopilotAdapter) NewSession(ctx context.Context, mcpServers []types.McpS a.mu.Lock() a.sessionID = sessionID a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) a.logger.Info("created new session", zap.String("session_id", sessionID)) @@ -348,6 +354,7 @@ func (a *CopilotAdapter) LoadSession(ctx context.Context, sessionID string) erro a.mu.Lock() a.sessionID = sessionID a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) a.logger.Info("loaded session", zap.String("session_id", sessionID)) @@ -366,8 +373,7 @@ func (a *CopilotAdapter) LoadSession(ctx context.Context, sessionID string) erro } // Prompt sends a prompt to Copilot and waits for completion. -// Note: attachments are not yet supported in Copilot protocol - they are ignored. -func (a *CopilotAdapter) Prompt(ctx context.Context, message string, _ []v1.MessageAttachment) error { +func (a *CopilotAdapter) Prompt(ctx context.Context, message string, attachments []v1.MessageAttachment) error { if a.client == nil { return fmt.Errorf("adapter not initialized") } @@ -381,12 +387,23 @@ func (a *CopilotAdapter) Prompt(ctx context.Context, message string, _ []v1.Mess a.receivedDeltas = false // Reset delta tracking for new operation a.mu.Unlock() + // Save attachments to workspace and prepend references to message + finalMessage := message + if len(attachments) > 0 { + saved, err := a.attachMgr.SaveAttachments(attachments) + if err != nil { + a.logger.Warn("failed to save attachments", zap.Error(err)) + } else if len(saved) > 0 { + finalMessage = shared.BuildAttachmentPrompt(saved) + message + } + } + a.logger.Info("sending prompt via SDK", zap.String("session_id", sessionID), zap.String("operation_id", operationID)) // Send message (non-blocking, events come via handler) - if _, err := a.client.Send(ctx, message); err != nil { + if _, err := a.client.Send(ctx, finalMessage); err != nil { a.mu.Lock() a.resultCh = nil a.mu.Unlock() @@ -414,6 +431,7 @@ func (a *CopilotAdapter) Prompt(ctx context.Context, message string, _ []v1.Mess a.logger.Info("prompt completed", zap.String("operation_id", operationID), zap.Bool("success", result.success)) + a.attachMgr.Cleanup() return nil } } @@ -466,6 +484,9 @@ func (a *CopilotAdapter) Close() error { a.logger.Info("closing Copilot SDK adapter") + // Clean up any saved attachments + a.attachMgr.Cleanup() + // Cancel the context if a.cancel != nil { a.cancel() diff --git a/apps/backend/internal/agentctl/server/adapter/e2e/mock_agent_test.go b/apps/backend/internal/agentctl/server/adapter/e2e/mock_agent_test.go index 5e078b8867..9a65fb83d3 100644 --- a/apps/backend/internal/agentctl/server/adapter/e2e/mock_agent_test.go +++ b/apps/backend/internal/agentctl/server/adapter/e2e/mock_agent_test.go @@ -3,8 +3,13 @@ package e2e import ( + "context" + "sync" "testing" + "time" + "github.com/kandev/kandev/internal/agentctl/server/adapter" + "github.com/kandev/kandev/internal/agentctl/server/process" "github.com/kandev/kandev/pkg/agent" ) @@ -16,7 +21,7 @@ func TestMockAgent_BasicPrompt(t *testing.T) { result := RunAgent(t, AgentSpec{ Name: "mock-agent", Command: binary + " --model mock-fast", - Protocol: agent.ProtocolClaudeCode, + Protocol: agent.ProtocolACP, DefaultPrompt: "hello", AutoApprove: true, }) @@ -27,3 +32,420 @@ func TestMockAgent_BasicPrompt(t *testing.T) { t.Logf("mock agent completed in %s with %d events", result.Duration, len(result.Events)) } + +// TestMockAgent_SimpleMessage tests the deterministic /e2e:simple-message scenario. +// Validates: thinking event + text message event + complete event. +func TestMockAgent_SimpleMessage(t *testing.T) { + binary := buildMockAgent(t) + + result := RunAgent(t, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + DefaultPrompt: "/e2e:simple-message", + AutoApprove: true, + }) + defer DumpEventsOnFailure(t, result) + + AssertTurnCompleted(t, result) + AssertNoErrors(t, result.Events) + AssertHasEventType(t, result.Events, adapter.EventTypeReasoning) + AssertHasEventType(t, result.Events, adapter.EventTypeMessageChunk) + + // Verify specific content + hasThinkingContent := false + hasTextContent := false + for _, ev := range result.Events { + if ev.Type == adapter.EventTypeReasoning && ev.ReasoningText == "Processing the request..." { + hasThinkingContent = true + } + if ev.Type == adapter.EventTypeMessageChunk && ev.Text == "This is a simple mock response for e2e testing." { + hasTextContent = true + } + } + if !hasThinkingContent { + t.Error("expected thinking event with 'Processing the request...'") + } + if !hasTextContent { + t.Error("expected text event with 'This is a simple mock response for e2e testing.'") + } +} + +// TestMockAgent_ToolCallEvents tests tool call start + complete flow via /e2e:read-and-edit. +// Validates: tool_call and tool_update events are emitted with correct types. +func TestMockAgent_ToolCallEvents(t *testing.T) { + binary := buildMockAgent(t) + + result := RunAgent(t, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + DefaultPrompt: "/e2e:read-and-edit", + AutoApprove: true, + }) + defer DumpEventsOnFailure(t, result) + + AssertTurnCompleted(t, result) + AssertNoErrors(t, result.Events) + AssertHasEventType(t, result.Events, adapter.EventTypeToolCall) + AssertHasEventType(t, result.Events, adapter.EventTypeToolUpdate) + + // Count tool calls and updates + counts := CountEventsByType(result.Events) + if counts[adapter.EventTypeToolCall] < 2 { + t.Errorf("expected at least 2 tool_call events (read + edit), got %d", counts[adapter.EventTypeToolCall]) + } + + t.Logf("event counts: %v", counts) +} + +// TestMockAgent_PermissionFlow tests auto-approved permission requests via /e2e:permission-flow. +func TestMockAgent_PermissionFlow(t *testing.T) { + binary := buildMockAgent(t) + + result := RunAgent(t, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + DefaultPrompt: "/e2e:permission-flow", + AutoApprove: true, + }) + defer DumpEventsOnFailure(t, result) + + AssertTurnCompleted(t, result) + AssertNoErrors(t, result.Events) + + // With auto-approve, the tool call should complete successfully + AssertHasEventType(t, result.Events, adapter.EventTypeToolCall) + + // Look for the "Permission was granted" text + hasGrantedText := false + for _, ev := range result.Events { + if ev.Type == adapter.EventTypeMessageChunk && ev.Text == "Permission was granted and command executed." { + hasGrantedText = true + } + } + if !hasGrantedText { + t.Error("expected 'Permission was granted and command executed.' message (auto-approve should grant)") + } +} + +// TestMockAgent_AllTools tests one of every tool kind via /e2e:all-tools. +// Validates: read, search, edit, execute, fetch tool kinds all appear. +func TestMockAgent_AllTools(t *testing.T) { + binary := buildMockAgent(t) + + result := RunAgent(t, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + DefaultPrompt: "/e2e:all-tools", + AutoApprove: true, + }) + defer DumpEventsOnFailure(t, result) + + AssertTurnCompleted(t, result) + AssertNoErrors(t, result.Events) + + // Check that multiple tool kinds are present + toolNames := map[string]bool{} + for _, ev := range result.Events { + if ev.Type == adapter.EventTypeToolCall && ev.ToolName != "" { + toolNames[ev.ToolName] = true + } + } + + // ACP tool kinds map to ToolName in events + expectedKinds := []string{"read", "search", "edit", "execute", "fetch"} + for _, kind := range expectedKinds { + if !toolNames[kind] { + t.Errorf("expected tool kind %q in events, got tools: %v", kind, toolNames) + } + } +} + +// TestMockAgent_MultiTurn sends two prompts to the same session. +// Validates: the agent handles multiple prompts without errors and session ID stays consistent. +func TestMockAgent_MultiTurn(t *testing.T) { + binary := buildMockAgent(t) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + setup := setupAgentProcess(t, ctx, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + }) + + // First turn + events1 := collectPromptEvents(ctx, t, setup, "/e2e:simple-message") + assertEventsHaveType(t, events1, adapter.EventTypeComplete, "turn 1") + assertEventsNoErrors(t, events1, "turn 1") + + sessionID := setup.adpt.GetSessionID() + if sessionID == "" { + t.Fatal("session ID is empty after first turn") + } + + // Second turn — same session + events2 := collectPromptEvents(ctx, t, setup, "/e2e:multi-turn") + assertEventsHaveType(t, events2, adapter.EventTypeComplete, "turn 2") + assertEventsNoErrors(t, events2, "turn 2") + + // Session ID must remain the same + if setup.adpt.GetSessionID() != sessionID { + t.Errorf("session ID changed between turns: %s -> %s", sessionID, setup.adpt.GetSessionID()) + } + + t.Logf("multi-turn: turn 1 had %d events, turn 2 had %d events", len(events1), len(events2)) +} + +// TestMockAgent_SessionReset tests creating a new session on the same connection. +// Validates: ResetSession works and produces a different session ID. +func TestMockAgent_SessionReset(t *testing.T) { + binary := buildMockAgent(t) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + setup := setupAgentProcess(t, ctx, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + }) + + // First turn + events1 := collectPromptEvents(ctx, t, setup, "/e2e:simple-message") + assertEventsHaveType(t, events1, adapter.EventTypeComplete, "turn 1") + + firstSessionID := setup.adpt.GetSessionID() + + // Reset session (creates new session on same connection) + resettable, ok := setup.adpt.(adapter.SessionResettableAdapter) + if !ok { + t.Fatal("adapter does not implement SessionResettableAdapter") + } + + newSessionID, err := resettable.ResetSession(ctx, nil) + if err != nil { + t.Fatalf("ResetSession failed: %v", err) + } + + if newSessionID == "" { + t.Fatal("new session ID is empty after reset") + } + + // Drain events from ResetSession (session_status etc.) + drainEvents(ctx, setup, 200*time.Millisecond) + + // Prompt on the new session + events2 := collectPromptEvents(ctx, t, setup, "/e2e:simple-message") + assertEventsHaveType(t, events2, adapter.EventTypeComplete, "post-reset turn") + assertEventsNoErrors(t, events2, "post-reset turn") + + t.Logf("session reset: %s -> %s", firstSessionID, newSessionID) +} + +// TestMockAgent_LoadSession tests resuming a session via LoadSession. +// Validates: LoadSession succeeds and subsequent prompts work. +func TestMockAgent_LoadSession(t *testing.T) { + binary := buildMockAgent(t) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + setup := setupAgentProcess(t, ctx, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + }) + + // First turn to establish a session + events1 := collectPromptEvents(ctx, t, setup, "/e2e:simple-message") + assertEventsHaveType(t, events1, adapter.EventTypeComplete, "initial turn") + + sessionID := setup.adpt.GetSessionID() + if sessionID == "" { + t.Fatal("session ID is empty") + } + + // Load the same session (simulates resume after process restart) + if err := setup.adpt.LoadSession(ctx, sessionID); err != nil { + t.Fatalf("LoadSession failed: %v", err) + } + + // Drain events from LoadSession (session_status etc.) + drainEvents(ctx, setup, 200*time.Millisecond) + + // Prompt on the loaded session + events2 := collectPromptEvents(ctx, t, setup, "/e2e:simple-message") + assertEventsHaveType(t, events2, adapter.EventTypeComplete, "post-load turn") + assertEventsNoErrors(t, events2, "post-load turn") + + // Session ID should match + if setup.adpt.GetSessionID() != sessionID { + t.Errorf("session ID changed after LoadSession: %s -> %s", sessionID, setup.adpt.GetSessionID()) + } + + t.Logf("session load: resumed %s successfully", sessionID) +} + +// TestMockAgent_ThinkingEvents tests extended thinking/reasoning via /thinking. +func TestMockAgent_ThinkingEvents(t *testing.T) { + binary := buildMockAgent(t) + + result := RunAgent(t, AgentSpec{ + Name: "mock-agent", + Command: binary + " --model mock-fast", + Protocol: agent.ProtocolACP, + DefaultPrompt: "/thinking", + AutoApprove: true, + }) + defer DumpEventsOnFailure(t, result) + + AssertTurnCompleted(t, result) + AssertNoErrors(t, result.Events) + + // Should have multiple reasoning events (the scenario emits 5 thoughts) + reasoningCount := 0 + for _, ev := range result.Events { + if ev.Type == adapter.EventTypeReasoning { + reasoningCount++ + } + } + if reasoningCount < 3 { + t.Errorf("expected at least 3 reasoning events, got %d", reasoningCount) + } + + t.Logf("thinking: %d reasoning events emitted", reasoningCount) +} + +// --- Multi-turn helpers --- + +// agentSetup holds the state for multi-turn tests. +type agentSetup struct { + mgr managerInterface + adpt adapter.AgentAdapter +} + +// managerInterface is the subset of process.Manager needed by helpers. +type managerInterface interface { + GetUpdates() <-chan adapter.AgentEvent +} + +// setupAgentProcess initializes an agent process for multi-turn testing. +// Returns the setup with manager and adapter ready for prompting. +func setupAgentProcess(t *testing.T, ctx context.Context, spec AgentSpec) *agentSetup { + t.Helper() + requireBinary(t, spec.Command) + + workDir := setupWorkspace(t) + cfg := buildInstanceConfig(spec.Command, spec.Protocol, workDir, spec.AutoApprove, spec.ContinueCommand) + log := newTestLogger(t) + + mgr := process.NewManager(cfg, log) + if err := mgr.Start(ctx); err != nil { + t.Fatalf("failed to start agent: %v", err) + } + t.Cleanup(func() { + stopCtx, stopCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer stopCancel() + _ = mgr.Stop(stopCtx) + }) + + adpt := mgr.GetAdapter() + if adpt == nil { + t.Fatal("adapter is nil after Start") + } + if err := adpt.Initialize(ctx); err != nil { + t.Fatalf("failed to initialize adapter: %v", err) + } + if _, err := adpt.NewSession(ctx, nil); err != nil { + t.Fatalf("failed to create session: %v", err) + } + + return &agentSetup{mgr: mgr, adpt: adpt} +} + +// collectPromptEvents sends a prompt and collects all events until the turn completes. +// It uses a dedicated context to stop the collector goroutine cleanly between calls. +func collectPromptEvents(ctx context.Context, t *testing.T, setup *agentSetup, prompt string) []adapter.AgentEvent { + t.Helper() + + var events []adapter.AgentEvent + var mu sync.Mutex + collectCtx, collectCancel := context.WithCancel(ctx) + + go func() { + ch := setup.mgr.GetUpdates() + for { + select { + case ev, ok := <-ch: + if !ok { + return + } + mu.Lock() + events = append(events, ev) + mu.Unlock() + case <-collectCtx.Done(): + return + } + } + }() + + if err := setup.adpt.Prompt(ctx, prompt, nil); err != nil { + collectCancel() + t.Fatalf("prompt failed: %v", err) + } + + // Grace period for remaining events to propagate + time.Sleep(500 * time.Millisecond) + collectCancel() // Stop the collector goroutine + + mu.Lock() + defer mu.Unlock() + result := make([]adapter.AgentEvent, len(events)) + copy(result, events) + return result +} + +// drainEvents reads and discards events from the updates channel for the given duration. +// Use between operations that emit events (e.g., ResetSession, LoadSession) to avoid +// stale events being picked up by the next collectPromptEvents call. +func drainEvents(ctx context.Context, setup *agentSetup, duration time.Duration) { + timer := time.NewTimer(duration) + defer timer.Stop() + ch := setup.mgr.GetUpdates() + for { + select { + case <-ch: + // discard + case <-timer.C: + return + case <-ctx.Done(): + return + } + } +} + +// assertEventsHaveType checks that at least one event of the given type exists. +func assertEventsHaveType(t *testing.T, events []adapter.AgentEvent, eventType, context string) { + t.Helper() + for _, ev := range events { + if ev.Type == eventType { + return + } + } + t.Errorf("[%s] expected at least one %q event, got none (total: %d events)", context, eventType, len(events)) +} + +// assertEventsNoErrors checks that no error events were received. +func assertEventsNoErrors(t *testing.T, events []adapter.AgentEvent, context string) { + t.Helper() + for _, ev := range events { + if ev.Type == adapter.EventTypeError { + t.Errorf("[%s] unexpected error event: %s", context, ev.Error) + } + } +} diff --git a/apps/backend/internal/agentctl/server/adapter/transport/acp/adapter.go b/apps/backend/internal/agentctl/server/adapter/transport/acp/adapter.go index bf04dedd75..32afcfe52e 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/acp/adapter.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/acp/adapter.go @@ -4,10 +4,12 @@ package acp import ( "context" + "encoding/base64" "encoding/json" "fmt" "io" "log/slog" + "strings" "sync" "github.com/coder/acp-go-sdk" @@ -31,6 +33,13 @@ type ( PlanEntry = streams.PlanEntry ) +// Content block type constants. +const ( + contentTypeImage = "image" + contentTypeAudio = "audio" + contentTypeResource = "resource" +) + // AgentInfo contains information about the connected agent. type AgentInfo struct { Name string `json:"name"` @@ -88,6 +97,9 @@ type Adapter struct { promptTraceCtx context.Context promptTraceMu sync.RWMutex + // Attachment management + attachMgr *shared.AttachmentManager + // Synchronization mu sync.RWMutex closed bool @@ -97,13 +109,15 @@ type Adapter struct { // Call Connect() after starting the subprocess to wire up stdin/stdout. // cfg.AgentID is required for debug file naming. func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter { + l := log.WithFields(zap.String("adapter", "acp"), zap.String("agent_id", cfg.AgentID)) return &Adapter{ cfg: cfg, - logger: log.WithFields(zap.String("adapter", "acp"), zap.String("agent_id", cfg.AgentID)), + logger: l, agentID: cfg.AgentID, normalizer: NewNormalizer(), updatesCh: make(chan AgentEvent, 100), activeToolCalls: make(map[string]*streams.NormalizedPayload), + attachMgr: shared.NewAttachmentManager(cfg.WorkDir, l.Zap()), } } @@ -189,6 +203,15 @@ func (a *Adapter) Initialize(ctx context.Context) error { zap.String("agent_version", a.agentInfo.Version), zap.Bool("supports_load_session", a.capabilities.LoadSession)) + // Emit agent capabilities event with prompt capabilities and auth methods + a.sendUpdate(AgentEvent{ + Type: streams.EventTypeAgentCapabilities, + SupportsImage: a.capabilities.PromptCapabilities.Image, + SupportsAudio: a.capabilities.PromptCapabilities.Audio, + SupportsEmbeddedContext: a.capabilities.PromptCapabilities.EmbeddedContext, + AuthMethods: convertAuthMethods(resp.AuthMethods), + }) + return nil } @@ -210,9 +233,10 @@ func (a *Adapter) NewSession(ctx context.Context, mcpServers []types.McpServer) ctx, span := shared.TraceProtocolRequest(ctx, shared.ProtocolACP, a.agentID, "session.new") defer span.End() + filteredServers := filterMcpServersByCapabilities(mcpServers, a.capabilities.McpCapabilities, a.logger) resp, err := conn.NewSession(ctx, acp.NewSessionRequest{ Cwd: a.cfg.WorkDir, - McpServers: toACPMcpServers(mcpServers), + McpServers: toACPMcpServers(filteredServers), }) if err != nil { span.RecordError(err) @@ -223,6 +247,7 @@ func (a *Adapter) NewSession(ctx context.Context, mcpServers []types.McpServer) a.sessionID = string(resp.SessionId) sessionID := a.sessionID a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) span.SetAttributes(attribute.String("session_id", sessionID)) a.logger.Info("created new session", zap.String("session_id", sessionID)) @@ -232,6 +257,11 @@ func (a *Adapter) NewSession(ctx context.Context, mcpServers []types.McpServer) a.emitInitialModeState(resp.Modes) } + // Emit session models if the agent returned model state + if resp.Models != nil { + a.emitSessionModels(sessionID, resp.Models, resp.Meta) + } + // Emit session status event to normalize with other adapters. // This eliminates the need for ReportsStatusViaStream flag. a.sendUpdate(AgentEvent{ @@ -247,6 +277,28 @@ func (a *Adapter) NewSession(ctx context.Context, mcpServers []types.McpServer) return sessionID, nil } +// filterMcpServersByCapabilities removes MCP servers that the agent doesn't support. +// Stdio servers are always allowed; SSE/HTTP servers require the corresponding capability. +func filterMcpServersByCapabilities(servers []types.McpServer, caps acp.McpCapabilities, logger *logger.Logger) []types.McpServer { + filtered := make([]types.McpServer, 0, len(servers)) + for _, s := range servers { + switch s.Type { + case "sse": + if !caps.Sse { + logger.Warn("filtering out SSE MCP server (agent does not support SSE)", zap.String("name", s.Name)) + continue + } + case "http": + if !caps.Http { + logger.Warn("filtering out HTTP MCP server (agent does not support HTTP)", zap.String("name", s.Name)) + continue + } + } + filtered = append(filtered, s) + } + return filtered +} + func toACPMcpServers(servers []types.McpServer) []acp.McpServer { if len(servers) == 0 { return []acp.McpServer{} @@ -290,6 +342,8 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { // Check if the agent supports session loading if !supportsLoad { + a.logger.Debug("session/load rejected: agent does not advertise LoadSession capability", + zap.String("session_id", sessionID)) return fmt.Errorf("agent does not support session loading (LoadSession capability is false)") } @@ -318,6 +372,7 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { a.mu.Lock() a.sessionID = sessionID a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) span.SetAttributes(attribute.String("session_id", sessionID)) a.logger.Info("loaded session", zap.String("session_id", sessionID)) @@ -327,6 +382,11 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { a.emitInitialModeState(resp.Modes) } + // Emit session models if the agent returned model state + if resp.Models != nil { + a.emitSessionModels(sessionID, resp.Models, resp.Meta) + } + // Emit session status event to normalize with other adapters. // This eliminates the need for ReportsStatusViaStream flag. a.sendUpdate(AgentEvent{ @@ -342,6 +402,13 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { return nil } +// ResetSession creates a new session on the existing connection, effectively resetting +// the agent's conversation context without restarting the subprocess. This is much faster +// than a full process restart since the ACP protocol supports multiple sessions per connection. +func (a *Adapter) ResetSession(ctx context.Context, mcpServers []types.McpServer) (string, error) { + return a.NewSession(ctx, mcpServers) +} + // Prompt sends a prompt to the agent. // If pending context is set (from SetPendingContext), it will be prepended to the message. // Attachments (images) are converted to ACP ImageBlocks and included in the prompt. @@ -370,10 +437,27 @@ func (a *Adapter) Prompt(ctx context.Context, message string, attachments []v1.M // Build content blocks: text first, then images contentBlocks := []acp.ContentBlock{acp.TextBlock(finalMessage)} - // Add image attachments as ImageBlocks + // Add media attachments as typed content blocks for _, att := range attachments { - if att.Type == "image" { + switch att.Type { + case contentTypeImage: contentBlocks = append(contentBlocks, acp.ImageBlock(att.Data, att.MimeType)) + case contentTypeAudio: + contentBlocks = append(contentBlocks, acp.AudioBlock(att.Data, att.MimeType)) + case contentTypeResource: + if a.capabilities.PromptCapabilities.EmbeddedContext { + contentBlocks = append(contentBlocks, buildResourceBlock(att)) + } else { + // Agent doesn't support embedded resources — save to workspace and reference in text + saved, saveErr := a.attachMgr.SaveAttachments([]v1.MessageAttachment{att}) + if saveErr != nil || len(saved) == 0 { + a.logger.Warn("failed to save attachment to workspace, falling back to resource block", + zap.String("name", att.Name), zap.Error(saveErr)) + contentBlocks = append(contentBlocks, buildResourceBlock(att)) + } else { + contentBlocks = append(contentBlocks, acp.TextBlock(shared.BuildAttachmentPrompt(saved))) + } + } } } @@ -432,8 +516,12 @@ func (a *Adapter) Prompt(ctx context.Context, message string, attachments []v1.M Type: streams.EventTypeComplete, SessionID: sessionID, Data: map[string]any{"stop_reason": stopReason}, + Usage: extractPromptUsage(resp.Meta), }) + // Clean up saved attachments — agent has finished reading them + a.attachMgr.Cleanup() + return nil } @@ -551,6 +639,9 @@ func (a *Adapter) Close() error { a.logger.Info("closing ACP adapter") + // Clean up any saved attachments + a.attachMgr.Cleanup() + // Close update channel close(a.updatesCh) @@ -752,11 +843,98 @@ func (a *Adapter) convertAvailableCommands(sessionID string, update *acp.Session // emitInitialModeState emits a session_mode event from the session response's Modes field. // Called after session/new and session/load to provide the initial mode state. func (a *Adapter) emitInitialModeState(modes *acp.SessionModeState) { + availModes := make([]streams.SessionModeInfo, 0, len(modes.AvailableModes)) + for _, m := range modes.AvailableModes { + availModes = append(availModes, streams.SessionModeInfo{ + ID: string(m.Id), + Name: m.Name, + Description: derefStr(m.Description), + }) + } + a.sendUpdate(AgentEvent{ + Type: streams.EventTypeSessionMode, + SessionID: a.sessionID, + CurrentModeID: string(modes.CurrentModeId), + AvailableModes: availModes, + }) +} + +// emitSessionModels emits a session_models event from the session response. +func (a *Adapter) emitSessionModels(sessionID string, models *acp.SessionModelState, meta any) { + a.sendUpdate(AgentEvent{ + Type: streams.EventTypeSessionModels, + SessionID: sessionID, + CurrentModelID: string(models.CurrentModelId), + SessionModels: convertSessionModels(models.AvailableModels), + ConfigOptions: extractConfigOptions(meta), + }) +} + +// SetMode changes the agent's session mode via ACP session/set_mode. +func (a *Adapter) SetMode(ctx context.Context, modeID string) error { + a.mu.RLock() + conn := a.acpConn + sessionID := a.sessionID + a.mu.RUnlock() + + if conn == nil { + return fmt.Errorf("adapter not initialized") + } + + _, err := conn.SetSessionMode(ctx, acp.SetSessionModeRequest{ + SessionId: acp.SessionId(sessionID), + ModeId: acp.SessionModeId(modeID), + }) + if err != nil { + return fmt.Errorf("set session mode failed: %w", err) + } + a.sendUpdate(AgentEvent{ Type: streams.EventTypeSessionMode, - SessionID: a.sessionID, - CurrentModeID: string(modes.CurrentModeId), + SessionID: sessionID, + CurrentModeID: modeID, }) + return nil +} + +// SetModel changes the agent's model via ACP session/set_model (unstable SDK method). +func (a *Adapter) SetModel(ctx context.Context, modelID string) error { + a.mu.RLock() + conn := a.acpConn + sessionID := a.sessionID + a.mu.RUnlock() + + if conn == nil { + return fmt.Errorf("adapter not initialized") + } + + _, err := conn.SetSessionModel(ctx, acp.SetSessionModelRequest{ + SessionId: acp.SessionId(sessionID), + ModelId: acp.ModelId(modelID), + }) + if err != nil { + return fmt.Errorf("set session model failed: %w", err) + } + return nil +} + +// Authenticate triggers ACP session/authenticate for a given auth method. +func (a *Adapter) Authenticate(ctx context.Context, methodID string) error { + a.mu.RLock() + conn := a.acpConn + a.mu.RUnlock() + + if conn == nil { + return fmt.Errorf("adapter not initialized") + } + + _, err := conn.Authenticate(ctx, acp.AuthenticateRequest{ + MethodId: acp.AuthMethodId(methodID), + }) + if err != nil { + return fmt.Errorf("authenticate failed: %w", err) + } + return nil } // derefStr safely dereferences a string pointer, returning empty string if nil. @@ -767,6 +945,49 @@ func derefStr(s *string) string { return "" } +// buildResourceBlock constructs an ACP ResourceBlock from a MessageAttachment. +// Text-based MIME types use TextResourceContents; everything else uses BlobResourceContents. +func buildResourceBlock(att v1.MessageAttachment) acp.ContentBlock { + uri := att.Name // Use filename as URI if no explicit URI + if uri == "" { + uri = "attachment" + } + if isTextMimeType(att.MimeType) { + text := att.Data + if decoded, err := base64.StdEncoding.DecodeString(att.Data); err == nil { + text = string(decoded) + } + return acp.ResourceBlock(acp.EmbeddedResourceResource{ + TextResourceContents: &acp.TextResourceContents{ + Uri: uri, + Text: text, + MimeType: acp.Ptr(att.MimeType), + }, + }) + } + return acp.ResourceBlock(acp.EmbeddedResourceResource{ + BlobResourceContents: &acp.BlobResourceContents{ + Uri: uri, + Blob: att.Data, + MimeType: acp.Ptr(att.MimeType), + }, + }) +} + +// isTextMimeType returns true for MIME types that represent text content. +func isTextMimeType(mimeType string) bool { + if strings.HasPrefix(mimeType, "text/") { + return true + } + switch mimeType { + case "application/json", "application/xml", "application/javascript", + "application/typescript", "application/x-yaml", "application/toml", + "application/x-sh", "application/sql": + return true + } + return false +} + // convertToolCallContents converts ACP ToolCallContent items to our protocol-agnostic type. func (a *Adapter) convertToolCallContents(contents []acp.ToolCallContent) []streams.ToolCallContentItem { if len(contents) == 0 { @@ -809,9 +1030,9 @@ func (a *Adapter) convertContentBlockToStreams(cb acp.ContentBlock) *streams.Con case cb.Text != nil: return &streams.ContentBlock{Type: "text", Text: cb.Text.Text} case cb.Image != nil: - return &streams.ContentBlock{Type: "image", Data: cb.Image.Data, MimeType: cb.Image.MimeType, URI: derefStr(cb.Image.Uri)} + return &streams.ContentBlock{Type: contentTypeImage, Data: cb.Image.Data, MimeType: cb.Image.MimeType, URI: derefStr(cb.Image.Uri)} case cb.Audio != nil: - return &streams.ContentBlock{Type: "audio", Data: cb.Audio.Data, MimeType: cb.Audio.MimeType} + return &streams.ContentBlock{Type: contentTypeAudio, Data: cb.Audio.Data, MimeType: cb.Audio.MimeType} case cb.ResourceLink != nil: return &streams.ContentBlock{ Type: "resource_link", URI: cb.ResourceLink.Uri, Name: cb.ResourceLink.Name, diff --git a/apps/backend/internal/agentctl/server/adapter/transport/acp/meta_convert.go b/apps/backend/internal/agentctl/server/adapter/transport/acp/meta_convert.go new file mode 100644 index 0000000000..3ec5023c92 --- /dev/null +++ b/apps/backend/internal/agentctl/server/adapter/transport/acp/meta_convert.go @@ -0,0 +1,229 @@ +package acp + +import ( + "fmt" + + "github.com/coder/acp-go-sdk" + "github.com/kandev/kandev/internal/agentctl/types/streams" +) + +// convertAuthMethods converts ACP auth methods to stream types, +// normalizing known _meta patterns (terminal-auth) while preserving raw _meta. +func convertAuthMethods(methods []acp.AuthMethod) []streams.AuthMethodInfo { + if len(methods) == 0 { + return nil + } + result := make([]streams.AuthMethodInfo, 0, len(methods)) + for _, m := range methods { + info := streams.AuthMethodInfo{ + ID: string(m.Id), + Name: m.Name, + Description: derefStr(m.Description), + Meta: toStringMap(m.Meta), + } + // Normalize _meta.terminal-auth → TerminalAuth + info.TerminalAuth = extractTerminalAuth(info.Meta) + result = append(result, info) + } + return result +} + +// extractTerminalAuth normalizes the terminal-auth pattern from _meta. +// Example _meta: {"terminal-auth": {"command": "copilot", "args": ["auth", "login"], "label": "Login with GitHub"}} +func extractTerminalAuth(meta map[string]any) *streams.TerminalAuth { + if meta == nil { + return nil + } + raw, ok := meta["terminal-auth"] + if !ok { + return nil + } + m, ok := raw.(map[string]any) + if !ok { + return nil + } + ta := &streams.TerminalAuth{} + if cmd, ok := m["command"].(string); ok { + ta.Command = cmd + } + if label, ok := m["label"].(string); ok { + ta.Label = label + } + if args, ok := m["args"].([]any); ok { + for _, a := range args { + if s, ok := a.(string); ok { + ta.Args = append(ta.Args, s) + } + } + } + if ta.Command == "" { + return nil + } + return ta +} + +// convertSessionModels converts ACP model info to stream types, +// normalizing known _meta patterns (copilotUsage) while preserving raw _meta. +func convertSessionModels(models []acp.ModelInfo) []streams.SessionModelInfo { + if len(models) == 0 { + return nil + } + result := make([]streams.SessionModelInfo, 0, len(models)) + for _, m := range models { + info := streams.SessionModelInfo{ + ModelID: string(m.ModelId), + Name: m.Name, + Description: derefStr(m.Description), + Meta: toStringMap(m.Meta), + } + // Normalize _meta.copilotUsage → UsageMultiplier + info.UsageMultiplier = extractUsageMultiplier(info.Meta) + result = append(result, info) + } + return result +} + +// extractUsageMultiplier normalizes the copilotUsage pattern from model _meta. +// Example _meta: {"copilotUsage": "3x"} or {"copilotUsage": 3} +func extractUsageMultiplier(meta map[string]any) string { + if meta == nil { + return "" + } + raw, ok := meta["copilotUsage"] + if !ok { + return "" + } + switch v := raw.(type) { + case string: + return v + case float64: + if v == float64(int64(v)) { + return fmt.Sprintf("%dx", int64(v)) + } + return fmt.Sprintf("%.2fx", v) + default: + return fmt.Sprintf("%v", v) + } +} + +// extractConfigOptions extracts config options from ACP session _meta. +// Example _meta: {"configOptions": [{"type": "select", "id": "mode", "name": "Mode", ...}]} +func extractConfigOptions(meta any) []streams.ConfigOption { + m, ok := toAnyMap(meta) + if !ok { + return nil + } + raw, ok := m["configOptions"] + if !ok { + return nil + } + items, ok := raw.([]any) + if !ok { + return nil + } + result := make([]streams.ConfigOption, 0, len(items)) + for _, item := range items { + opt, ok := item.(map[string]any) + if !ok { + continue + } + co := streams.ConfigOption{ + Type: getString(opt, "type"), + ID: getString(opt, "id"), + Name: getString(opt, "name"), + CurrentValue: getString(opt, "currentValue"), + Category: getString(opt, "category"), + } + if options, ok := opt["options"].([]any); ok { + for _, o := range options { + if om, ok := o.(map[string]any); ok { + co.Options = append(co.Options, streams.ConfigOptionValue{ + Value: getString(om, "value"), + Name: getString(om, "name"), + }) + } + } + } + result = append(result, co) + } + return result +} + +// extractPromptUsage extracts token usage from ACP prompt response _meta. +// Example _meta: {"usage": {"input_tokens": 100, "output_tokens": 50, "total_tokens": 150}} +func extractPromptUsage(meta any) *streams.PromptUsage { + m, ok := toAnyMap(meta) + if !ok { + return nil + } + raw, ok := m["usage"] + if !ok { + return nil + } + u, ok := raw.(map[string]any) + if !ok { + return nil + } + usage := &streams.PromptUsage{ + InputTokens: getInt64(u, "input_tokens"), + OutputTokens: getInt64(u, "output_tokens"), + CachedReadTokens: getInt64(u, "cached_read_tokens"), + CachedWriteTokens: getInt64(u, "cached_write_tokens"), + TotalTokens: getInt64(u, "total_tokens"), + } + // Also check camelCase variants + if usage.InputTokens == 0 { + usage.InputTokens = getInt64(u, "inputTokens") + } + if usage.OutputTokens == 0 { + usage.OutputTokens = getInt64(u, "outputTokens") + } + if usage.TotalTokens == 0 { + usage.TotalTokens = getInt64(u, "totalTokens") + } + if usage.CachedReadTokens == 0 { + usage.CachedReadTokens = getInt64(u, "cachedReadTokens") + } + if usage.CachedWriteTokens == 0 { + usage.CachedWriteTokens = getInt64(u, "cachedWriteTokens") + } + if usage.InputTokens == 0 && usage.OutputTokens == 0 && usage.TotalTokens == 0 { + return nil + } + return usage +} + +// toStringMap converts any to map[string]any, handling the common JSON unmarshal case. +func toStringMap(v any) map[string]any { + m, _ := toAnyMap(v) + return m +} + +// toAnyMap converts any to map[string]any. +func toAnyMap(v any) (map[string]any, bool) { + if v == nil { + return nil, false + } + m, ok := v.(map[string]any) + return m, ok +} + +// getString safely extracts a string from a map. +func getString(m map[string]any, key string) string { + v, _ := m[key].(string) + return v +} + +// getInt64 safely extracts an int64 from a map (JSON numbers are float64). +func getInt64(m map[string]any, key string) int64 { + switch v := m[key].(type) { + case float64: + return int64(v) + case int64: + return v + case int: + return int64(v) + default: + return 0 + } +} diff --git a/apps/backend/internal/agentctl/server/adapter/transport/codex/adapter.go b/apps/backend/internal/agentctl/server/adapter/transport/codex/adapter.go index e3020b9f3e..a873b4e802 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/codex/adapter.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/codex/adapter.go @@ -102,6 +102,9 @@ type Adapter struct { promptTraceCtx context.Context promptTraceMu sync.RWMutex + // Attachment management + attachMgr *shared.AttachmentManager + // Synchronization mu sync.RWMutex closed bool @@ -117,14 +120,16 @@ type turnCompleteResult struct { // Call Connect() after starting the subprocess to wire up stdin/stdout. func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter { ctx, cancel := context.WithCancel(context.Background()) + l := log.WithFields(zap.String("adapter", "codex"), zap.String("agent_id", cfg.AgentID)) return &Adapter{ cfg: cfg, - logger: log.WithFields(zap.String("adapter", "codex"), zap.String("agent_id", cfg.AgentID)), + logger: l, agentID: cfg.AgentID, normalizer: NewNormalizer(), ctx: ctx, cancel: cancel, updatesCh: make(chan AgentEvent, 100), + attachMgr: shared.NewAttachmentManager(cfg.WorkDir, l.Zap()), } } @@ -154,6 +159,9 @@ func (a *Adapter) Close() error { a.logger.Info("closing Codex adapter") + // Clean up any saved attachments + a.attachMgr.Cleanup() + // Cancel the context to stop the read loop goroutine if a.cancel != nil { a.cancel() diff --git a/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_prompt.go b/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_prompt.go index 57b642b23b..34e42d79aa 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_prompt.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_prompt.go @@ -2,14 +2,10 @@ package codex import ( "context" - "encoding/base64" "encoding/json" "fmt" - "os" - "path/filepath" "strings" - "github.com/google/uuid" "github.com/kandev/kandev/internal/agentctl/server/adapter/transport/shared" "github.com/kandev/kandev/internal/agentctl/types/streams" v1 "github.com/kandev/kandev/pkg/api/v1" @@ -74,12 +70,22 @@ func (a *Adapter) buildPromptInputs(message string, attachments []v1.MessageAtta } if len(attachments) > 0 { - imagePaths, err := a.saveImageAttachments(a.cfg.WorkDir, attachments) + saved, err := a.attachMgr.SaveAttachments(attachments) if err != nil { - a.logger.Warn("failed to save image attachments", zap.Error(err)) + a.logger.Warn("failed to save attachments", zap.Error(err)) } else { - for _, imagePath := range imagePaths { - inputs = append(inputs, codex.UserInput{Type: "localImage", Path: imagePath}) + var nonImageSaved []shared.SavedAttachment + for _, s := range saved { + if s.Type == "image" { + // Codex supports localImage input type with absolute path + inputs = append(inputs, codex.UserInput{Type: "localImage", Path: s.AbsPath}) + } else { + nonImageSaved = append(nonImageSaved, s) + } + } + // Non-image files are referenced in prompt text + if prompt := shared.BuildAttachmentPrompt(nonImageSaved); prompt != "" { + inputs = append([]codex.UserInput{{Type: "text", Text: prompt}}, inputs...) } } } @@ -153,6 +159,9 @@ func (a *Adapter) waitForTurnCompletion(ctx context.Context, threadID, turnID st } a.logger.Info("turn completed", zap.String("turn_id", turnID), zap.Bool("success", completeResult.success)) + // Clean up saved attachments — agent has finished reading them + a.attachMgr.Cleanup() + // Emit complete event via the stream. // This normalizes Codex behavior to match other adapters. // All adapters now emit complete events, eliminating the need for protocol-specific flags. @@ -166,58 +175,6 @@ func (a *Adapter) waitForTurnCompletion(ctx context.Context, threadID, turnID st } } -// saveImageAttachments saves image attachments to temp files in the workspace. -func (a *Adapter) saveImageAttachments(workDir string, attachments []v1.MessageAttachment) ([]string, error) { - var imagePaths []string - - if workDir == "" { - return nil, fmt.Errorf("workDir is required to save attachments") - } - - tempDir := filepath.Join(workDir, ".kandev", "temp", "images") - if err := os.MkdirAll(tempDir, 0755); err != nil { - return nil, fmt.Errorf("failed to create temp dir: %w", err) - } - - for _, att := range attachments { - if att.Type != "image" { - continue - } - - imageData, err := base64.StdEncoding.DecodeString(att.Data) - if err != nil { - a.logger.Warn("failed to decode image attachment", zap.Error(err)) - continue - } - - ext := ".png" - switch att.MimeType { - case "image/jpeg": - ext = ".jpg" - case "image/gif": - ext = ".gif" - case "image/webp": - ext = ".webp" - case "image/png": - ext = ".png" - } - - filename := fmt.Sprintf("image-%s%s", uuid.New().String()[:8], ext) - filePath := filepath.Join(tempDir, filename) - if err := os.WriteFile(filePath, imageData, 0644); err != nil { - a.logger.Warn("failed to write image file", zap.Error(err), zap.String("path", filePath)) - continue - } - - imagePaths = append(imagePaths, filePath) - a.logger.Info("saved image attachment", - zap.String("path", filePath), - zap.Int("size", len(imageData))) - } - - return imagePaths, nil -} - // Cancel interrupts the current turn. func (a *Adapter) Cancel(ctx context.Context) error { a.mu.RLock() diff --git a/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_session.go b/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_session.go index 9dcfa21cab..2a0aa46817 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_session.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/codex/codex_session.go @@ -61,6 +61,7 @@ func (a *Adapter) NewSession(ctx context.Context, _ []types.McpServer) (string, a.mu.Lock() a.threadID = result.Thread.ID a.mu.Unlock() + a.attachMgr.SetSessionID(result.Thread.ID) a.logger.Info("created new thread", zap.String("thread_id", a.threadID)) @@ -113,6 +114,7 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { a.mu.Lock() a.threadID = sessionID a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) a.logger.Info("resumed thread", zap.String("thread_id", a.threadID)) diff --git a/apps/backend/internal/agentctl/server/adapter/transport/opencode/adapter.go b/apps/backend/internal/agentctl/server/adapter/transport/opencode/adapter.go index 365a91fe31..375b92d649 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/opencode/adapter.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/opencode/adapter.go @@ -112,6 +112,9 @@ type Adapter struct { promptTraceCtx context.Context promptTraceMu sync.RWMutex + // Attachment management + attachMgr *shared.AttachmentManager + // Synchronization mu sync.RWMutex closed bool @@ -150,9 +153,10 @@ func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter { log.Info("parsed model from AGENT_MODEL", zap.String("model", modelStr)) } + l := log.WithFields(zap.String("adapter", "opencode"), zap.String("agent_id", agentID)) return &Adapter{ cfg: cfg, - logger: log.WithFields(zap.String("adapter", "opencode"), zap.String("agent_id", agentID)), + logger: l, agentID: agentID, normalizer: NewNormalizer(), model: modelSpec, @@ -164,6 +168,7 @@ func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter { password: opencode.GenerateServerPassword(), directory: cfg.WorkDir, modelContextWindow: 200000, // Default + attachMgr: shared.NewAttachmentManager(cfg.WorkDir, l.Zap()), } } @@ -343,6 +348,7 @@ func (a *Adapter) NewSession(ctx context.Context, _ []types.McpServer) (string, a.mu.Lock() a.sessionID = sessionID a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) a.logger.Info("created new session", zap.String("session_id", sessionID)) @@ -374,6 +380,7 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { a.mu.Lock() a.sessionID = newSessionID a.mu.Unlock() + a.attachMgr.SetSessionID(newSessionID) a.logger.Info("loaded session (forked)", zap.String("original_session_id", sessionID), @@ -394,8 +401,7 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { } // Prompt sends a prompt to OpenCode and waits for completion. -// Note: attachments are not yet supported in OpenCode protocol - they are ignored. -func (a *Adapter) Prompt(ctx context.Context, message string, _ []v1.MessageAttachment) error { +func (a *Adapter) Prompt(ctx context.Context, message string, attachments []v1.MessageAttachment) error { a.mu.Lock() client := a.client sessionID := a.sessionID @@ -405,6 +411,17 @@ func (a *Adapter) Prompt(ctx context.Context, message string, _ []v1.MessageAtta a.resultCh = make(chan resultComplete, 1) a.mu.Unlock() + // Save attachments to workspace and prepend references to message + finalMessage := message + if len(attachments) > 0 { + saved, err := a.attachMgr.SaveAttachments(attachments) + if err != nil { + a.logger.Warn("failed to save attachments", zap.Error(err)) + } else if len(saved) > 0 { + finalMessage = shared.BuildAttachmentPrompt(saved) + message + } + } + if client == nil { return fmt.Errorf("adapter not initialized") } @@ -413,12 +430,13 @@ func (a *Adapter) Prompt(ctx context.Context, message string, _ []v1.MessageAtta promptCtx, promptSpan := shared.TraceProtocolRequest(ctx, shared.ProtocolOpenCode, a.agentID, "prompt") promptSpan.SetAttributes( attribute.String("session_id", sessionID), - attribute.Int("prompt_length", len(message)), + attribute.Int("prompt_length", len(finalMessage)), ) a.setPromptTraceCtx(promptCtx) defer func() { a.clearPromptTraceCtx() promptSpan.End() + a.attachMgr.Cleanup() }() a.logger.Info("sending prompt", @@ -431,7 +449,7 @@ func (a *Adapter) Prompt(ctx context.Context, message string, _ []v1.MessageAtta } // Send prompt with model selection (blocks until OpenCode finishes) - if err := client.SendPrompt(ctx, sessionID, message, a.model, "", ""); err != nil { + if err := client.SendPrompt(ctx, sessionID, finalMessage, a.model, "", ""); err != nil { a.mu.Lock() a.resultCh = nil a.mu.Unlock() @@ -441,19 +459,21 @@ func (a *Adapter) Prompt(ctx context.Context, message string, _ []v1.MessageAtta a.logger.Info("prompt HTTP request completed, waiting for SSE idle signal", zap.String("session_id", sessionID)) - // Wait for result via control channel or context cancellation + return a.waitForPromptCompletion(ctx, client, sessionID) +} + +// waitForPromptCompletion blocks until the prompt completes via the SSE control channel. +func (a *Adapter) waitForPromptCompletion(ctx context.Context, client *opencode.Client, sessionID string) error { controlCh := client.ControlChannel() for { select { case <-ctx.Done(): - // Request cancellation _ = a.Cancel(context.Background()) return ctx.Err() case control, ok := <-controlCh: if !ok { - // Channel closed a.sendUpdate(AgentEvent{ Type: streams.EventTypeComplete, SessionID: sessionID, @@ -552,6 +572,9 @@ func (a *Adapter) Close() error { } a.closed = true + // Clean up any saved attachments + a.attachMgr.Cleanup() + a.logger.Debug("OpenCode adapter: cancelling context") a.cancel() diff --git a/apps/backend/internal/agentctl/server/adapter/transport/shared/attachments.go b/apps/backend/internal/agentctl/server/adapter/transport/shared/attachments.go new file mode 100644 index 0000000000..11e31c0880 --- /dev/null +++ b/apps/backend/internal/agentctl/server/adapter/transport/shared/attachments.go @@ -0,0 +1,171 @@ +package shared + +import ( + "encoding/base64" + "fmt" + "os" + "path/filepath" + "strings" + + v1 "github.com/kandev/kandev/pkg/api/v1" + "go.uber.org/zap" +) + +// SavedAttachment represents an attachment saved to the workspace. +type SavedAttachment struct { + // RelPath is the path relative to workDir (e.g. ".kandev/attachments/{sid}/file.pdf"). + RelPath string + // AbsPath is the absolute path to the saved file. + AbsPath string + // Name is the original filename. + Name string + // MimeType is the MIME type of the attachment. + MimeType string + // Type is the attachment type ("image" or "resource"). + Type string +} + +// AttachmentManager saves attachments to session-scoped directories and cleans up. +// Each session gets its own subdirectory under .kandev/attachments/{sessionID}/ +// so concurrent agents sharing a workspace don't interfere with each other. +type AttachmentManager struct { + workDir string + sessionID string + logger *zap.Logger +} + +// NewAttachmentManager creates a new AttachmentManager. +// sessionID can be empty initially and set later via SetSessionID. +func NewAttachmentManager(workDir string, logger *zap.Logger) *AttachmentManager { + return &AttachmentManager{ + workDir: workDir, + logger: logger, + } +} + +// SetSessionID updates the session ID used for the scoped subdirectory. +func (m *AttachmentManager) SetSessionID(id string) { + m.sessionID = id +} + +// SaveAttachments saves all attachments to .kandev/attachments/{sessionID}/. +// Returns saved attachment metadata so the caller can decide how to reference them. +func (m *AttachmentManager) SaveAttachments(attachments []v1.MessageAttachment) ([]SavedAttachment, error) { + if len(attachments) == 0 { + return nil, nil + } + if m.workDir == "" || m.sessionID == "" { + return nil, fmt.Errorf("workDir or sessionID not set") + } + + dir := filepath.Join(m.workDir, ".kandev", "attachments", m.sessionID) + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, fmt.Errorf("create attachments dir: %w", err) + } + + var saved []SavedAttachment + for _, att := range attachments { + name := att.Name + if name == "" { + name = m.generateName(att) + } + // Sanitize: strip directory components to prevent path traversal attacks. + name = filepath.Base(name) + if name == "." || name == ".." || name == string(filepath.Separator) { + m.logger.Warn("skipping attachment with invalid name", zap.String("original_name", att.Name)) + continue + } + + decoded, err := base64.StdEncoding.DecodeString(att.Data) + if err != nil { + m.logger.Warn("failed to decode attachment", zap.String("name", name), zap.Error(err)) + continue + } + + absPath := filepath.Join(dir, name) + if err := os.WriteFile(absPath, decoded, 0o644); err != nil { + m.logger.Warn("failed to write attachment", zap.String("path", absPath), zap.Error(err)) + continue + } + + relPath := filepath.Join(".kandev", "attachments", m.sessionID, name) + saved = append(saved, SavedAttachment{ + RelPath: relPath, + AbsPath: absPath, + Name: name, + MimeType: att.MimeType, + Type: att.Type, + }) + + m.logger.Debug("saved attachment", zap.String("path", relPath), zap.Int("size", len(decoded))) + } + + return saved, nil +} + +// Cleanup removes the session's attachment directory. +// Safe to call multiple times or with empty sessionID (no-op). +func (m *AttachmentManager) Cleanup() { + if m.sessionID == "" || m.workDir == "" { + return + } + dir := filepath.Join(m.workDir, ".kandev", "attachments", m.sessionID) + if err := os.RemoveAll(dir); err != nil { + m.logger.Debug("failed to clean attachments dir", zap.String("dir", dir), zap.Error(err)) + } +} + +// BuildAttachmentPrompt generates prompt text referencing saved attachment files. +// Used by adapters that don't support native multimodal content. +func BuildAttachmentPrompt(saved []SavedAttachment) string { + if len(saved) == 0 { + return "" + } + + var sb strings.Builder + if len(saved) == 1 { + s := saved[0] + fmt.Fprintf(&sb, "The user attached a file: %s (saved to %s in the workspace). Use your file reading tools to access it.\n\n", s.Name, s.RelPath) + } else { + sb.WriteString("The user attached files that you should read and analyze:\n") + for _, s := range saved { + fmt.Fprintf(&sb, "- %s (saved to %s)\n", s.Name, s.RelPath) + } + sb.WriteString("\nUse your file reading tools to access them.\n\n") + } + return sb.String() +} + +// generateName creates a filename for attachments that don't have a Name field. +func (m *AttachmentManager) generateName(att v1.MessageAttachment) string { + ext := extensionFromMimeType(att.MimeType) + return "attachment" + ext +} + +// extensionFromMimeType returns a file extension for common MIME types. +func extensionFromMimeType(mimeType string) string { + switch mimeType { + case "image/png": + return ".png" + case "image/jpeg": + return ".jpg" + case "image/gif": + return ".gif" + case "image/webp": + return ".webp" + case "application/pdf": + return ".pdf" + case "text/plain": + return ".txt" + case "application/json": + return ".json" + case "text/csv": + return ".csv" + case "text/html": + return ".html" + case "text/markdown": + return ".md" + default: + return "" + } +} diff --git a/apps/backend/internal/agentctl/server/adapter/transport/shared/attachments_test.go b/apps/backend/internal/agentctl/server/adapter/transport/shared/attachments_test.go new file mode 100644 index 0000000000..daf459e8c6 --- /dev/null +++ b/apps/backend/internal/agentctl/server/adapter/transport/shared/attachments_test.go @@ -0,0 +1,381 @@ +package shared + +import ( + "encoding/base64" + "os" + "path/filepath" + "testing" + + v1 "github.com/kandev/kandev/pkg/api/v1" + "go.uber.org/zap" +) + +func testLogger() *zap.Logger { + return zap.NewNop() +} + +func TestNewAttachmentManager(t *testing.T) { + mgr := NewAttachmentManager("/tmp/work", testLogger()) + if mgr == nil { + t.Fatal("expected non-nil manager") + } + if mgr.workDir != "/tmp/work" { + t.Errorf("workDir = %q, want %q", mgr.workDir, "/tmp/work") + } + if mgr.sessionID != "" { + t.Errorf("sessionID = %q, want empty", mgr.sessionID) + } +} + +func TestSetSessionID(t *testing.T) { + mgr := NewAttachmentManager("/tmp/work", testLogger()) + mgr.SetSessionID("sess-123") + if mgr.sessionID != "sess-123" { + t.Errorf("sessionID = %q, want %q", mgr.sessionID, "sess-123") + } +} + +func TestSaveAttachments_EmptyList(t *testing.T) { + mgr := NewAttachmentManager("/tmp/work", testLogger()) + mgr.SetSessionID("sess-1") + + saved, err := mgr.SaveAttachments(nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if saved != nil { + t.Errorf("expected nil, got %v", saved) + } +} + +func TestSaveAttachments_MissingSessionID(t *testing.T) { + mgr := NewAttachmentManager("/tmp/work", testLogger()) + + _, err := mgr.SaveAttachments([]v1.MessageAttachment{{Type: "image", Data: "abc"}}) + if err == nil { + t.Fatal("expected error when sessionID is empty") + } +} + +func TestSaveAttachments_MissingWorkDir(t *testing.T) { + mgr := NewAttachmentManager("", testLogger()) + mgr.SetSessionID("sess-1") + + _, err := mgr.SaveAttachments([]v1.MessageAttachment{{Type: "image", Data: "abc"}}) + if err == nil { + t.Fatal("expected error when workDir is empty") + } +} + +func TestSaveAttachments_ImageAttachment(t *testing.T) { + workDir := t.TempDir() + mgr := NewAttachmentManager(workDir, testLogger()) + mgr.SetSessionID("sess-img") + + content := []byte{0x89, 0x50, 0x4E, 0x47} // PNG header bytes + encoded := base64.StdEncoding.EncodeToString(content) + + saved, err := mgr.SaveAttachments([]v1.MessageAttachment{ + {Type: "image", Data: encoded, MimeType: "image/png", Name: "screenshot.png"}, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(saved) != 1 { + t.Fatalf("expected 1 saved, got %d", len(saved)) + } + + s := saved[0] + if s.Name != "screenshot.png" { + t.Errorf("Name = %q, want %q", s.Name, "screenshot.png") + } + if s.Type != "image" { + t.Errorf("Type = %q, want %q", s.Type, "image") + } + if s.MimeType != "image/png" { + t.Errorf("MimeType = %q, want %q", s.MimeType, "image/png") + } + expectedRel := filepath.Join(".kandev", "attachments", "sess-img", "screenshot.png") + if s.RelPath != expectedRel { + t.Errorf("RelPath = %q, want %q", s.RelPath, expectedRel) + } + + // Verify file was written + data, err := os.ReadFile(s.AbsPath) + if err != nil { + t.Fatalf("failed to read saved file: %v", err) + } + if len(data) != len(content) { + t.Errorf("file size = %d, want %d", len(data), len(content)) + } +} + +func TestSaveAttachments_ResourceAttachment(t *testing.T) { + workDir := t.TempDir() + mgr := NewAttachmentManager(workDir, testLogger()) + mgr.SetSessionID("sess-res") + + content := []byte("Hello, PDF content") + encoded := base64.StdEncoding.EncodeToString(content) + + saved, err := mgr.SaveAttachments([]v1.MessageAttachment{ + {Type: "resource", Data: encoded, MimeType: "application/pdf", Name: "report.pdf"}, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(saved) != 1 { + t.Fatalf("expected 1 saved, got %d", len(saved)) + } + + s := saved[0] + if s.Name != "report.pdf" { + t.Errorf("Name = %q, want %q", s.Name, "report.pdf") + } + if s.Type != "resource" { + t.Errorf("Type = %q, want %q", s.Type, "resource") + } + + data, err := os.ReadFile(s.AbsPath) + if err != nil { + t.Fatalf("failed to read saved file: %v", err) + } + if string(data) != string(content) { + t.Errorf("file content = %q, want %q", string(data), string(content)) + } +} + +func TestSaveAttachments_MultipleAttachments(t *testing.T) { + workDir := t.TempDir() + mgr := NewAttachmentManager(workDir, testLogger()) + mgr.SetSessionID("sess-multi") + + img := base64.StdEncoding.EncodeToString([]byte("image-data")) + pdf := base64.StdEncoding.EncodeToString([]byte("pdf-data")) + + saved, err := mgr.SaveAttachments([]v1.MessageAttachment{ + {Type: "image", Data: img, MimeType: "image/jpeg", Name: "photo.jpg"}, + {Type: "resource", Data: pdf, MimeType: "application/pdf", Name: "doc.pdf"}, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(saved) != 2 { + t.Fatalf("expected 2 saved, got %d", len(saved)) + } + + if saved[0].Name != "photo.jpg" { + t.Errorf("first Name = %q, want %q", saved[0].Name, "photo.jpg") + } + if saved[1].Name != "doc.pdf" { + t.Errorf("second Name = %q, want %q", saved[1].Name, "doc.pdf") + } +} + +func TestSaveAttachments_NoName_GeneratesFromMime(t *testing.T) { + workDir := t.TempDir() + mgr := NewAttachmentManager(workDir, testLogger()) + mgr.SetSessionID("sess-noname") + + encoded := base64.StdEncoding.EncodeToString([]byte("data")) + + saved, err := mgr.SaveAttachments([]v1.MessageAttachment{ + {Type: "image", Data: encoded, MimeType: "image/jpeg"}, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(saved) != 1 { + t.Fatalf("expected 1 saved, got %d", len(saved)) + } + if saved[0].Name != "attachment.jpg" { + t.Errorf("Name = %q, want %q", saved[0].Name, "attachment.jpg") + } +} + +func TestSaveAttachments_InvalidBase64_Skipped(t *testing.T) { + workDir := t.TempDir() + mgr := NewAttachmentManager(workDir, testLogger()) + mgr.SetSessionID("sess-invalid") + + saved, err := mgr.SaveAttachments([]v1.MessageAttachment{ + {Type: "resource", Data: "not-valid-base64!!!", MimeType: "text/plain", Name: "bad.txt"}, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(saved) != 0 { + t.Errorf("expected 0 saved (invalid base64 skipped), got %d", len(saved)) + } +} + +func TestCleanup(t *testing.T) { + workDir := t.TempDir() + mgr := NewAttachmentManager(workDir, testLogger()) + mgr.SetSessionID("sess-cleanup") + + // Save an attachment + encoded := base64.StdEncoding.EncodeToString([]byte("cleanup-test")) + saved, err := mgr.SaveAttachments([]v1.MessageAttachment{ + {Type: "resource", Data: encoded, MimeType: "text/plain", Name: "temp.txt"}, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + // Verify file exists + if _, err := os.Stat(saved[0].AbsPath); err != nil { + t.Fatalf("file should exist before cleanup: %v", err) + } + + // Cleanup + mgr.Cleanup() + + // Verify directory is gone + dir := filepath.Join(workDir, ".kandev", "attachments", "sess-cleanup") + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Errorf("directory should not exist after cleanup, got err: %v", err) + } +} + +func TestCleanup_EmptySessionID_NoOp(t *testing.T) { + mgr := NewAttachmentManager("/tmp/work", testLogger()) + // Should not panic + mgr.Cleanup() +} + +func TestCleanup_EmptyWorkDir_NoOp(t *testing.T) { + mgr := NewAttachmentManager("", testLogger()) + mgr.SetSessionID("sess-1") + // Should not panic + mgr.Cleanup() +} + +func TestCleanup_Idempotent(t *testing.T) { + workDir := t.TempDir() + mgr := NewAttachmentManager(workDir, testLogger()) + mgr.SetSessionID("sess-idem") + + encoded := base64.StdEncoding.EncodeToString([]byte("data")) + _, _ = mgr.SaveAttachments([]v1.MessageAttachment{ + {Type: "resource", Data: encoded, MimeType: "text/plain", Name: "f.txt"}, + }) + + // Cleanup twice — second call should not panic + mgr.Cleanup() + mgr.Cleanup() +} + +func TestCleanup_SessionIsolation(t *testing.T) { + workDir := t.TempDir() + mgr1 := NewAttachmentManager(workDir, testLogger()) + mgr1.SetSessionID("sess-A") + mgr2 := NewAttachmentManager(workDir, testLogger()) + mgr2.SetSessionID("sess-B") + + encoded := base64.StdEncoding.EncodeToString([]byte("data")) + + saved1, _ := mgr1.SaveAttachments([]v1.MessageAttachment{ + {Type: "resource", Data: encoded, MimeType: "text/plain", Name: "a.txt"}, + }) + saved2, _ := mgr2.SaveAttachments([]v1.MessageAttachment{ + {Type: "resource", Data: encoded, MimeType: "text/plain", Name: "b.txt"}, + }) + + // Cleanup session A + mgr1.Cleanup() + + // Session A file gone + if _, err := os.Stat(saved1[0].AbsPath); !os.IsNotExist(err) { + t.Error("session A file should be deleted after cleanup") + } + + // Session B file still exists + if _, err := os.Stat(saved2[0].AbsPath); err != nil { + t.Errorf("session B file should still exist: %v", err) + } + + // Cleanup session B + mgr2.Cleanup() + if _, err := os.Stat(saved2[0].AbsPath); !os.IsNotExist(err) { + t.Error("session B file should be deleted after cleanup") + } +} + +func TestBuildAttachmentPrompt_Empty(t *testing.T) { + result := BuildAttachmentPrompt(nil) + if result != "" { + t.Errorf("expected empty string, got %q", result) + } +} + +func TestBuildAttachmentPrompt_SingleFile(t *testing.T) { + saved := []SavedAttachment{ + {RelPath: ".kandev/attachments/s1/report.pdf", Name: "report.pdf"}, + } + result := BuildAttachmentPrompt(saved) + if result == "" { + t.Fatal("expected non-empty result") + } + // Should mention the file name and path + if !contains(result, "report.pdf") { + t.Errorf("result should contain filename, got: %q", result) + } + if !contains(result, ".kandev/attachments/s1/report.pdf") { + t.Errorf("result should contain path, got: %q", result) + } +} + +func TestBuildAttachmentPrompt_MultipleFiles(t *testing.T) { + saved := []SavedAttachment{ + {RelPath: ".kandev/attachments/s1/a.pdf", Name: "a.pdf"}, + {RelPath: ".kandev/attachments/s1/b.png", Name: "b.png"}, + } + result := BuildAttachmentPrompt(saved) + if !contains(result, "a.pdf") { + t.Errorf("result should contain a.pdf, got: %q", result) + } + if !contains(result, "b.png") { + t.Errorf("result should contain b.png, got: %q", result) + } +} + +func TestExtensionFromMimeType(t *testing.T) { + tests := []struct { + mimeType string + want string + }{ + {"image/png", ".png"}, + {"image/jpeg", ".jpg"}, + {"image/gif", ".gif"}, + {"image/webp", ".webp"}, + {"application/pdf", ".pdf"}, + {"text/plain", ".txt"}, + {"application/json", ".json"}, + {"text/csv", ".csv"}, + {"text/html", ".html"}, + {"text/markdown", ".md"}, + {"application/octet-stream", ""}, + {"video/mp4", ""}, + } + + for _, tt := range tests { + got := extensionFromMimeType(tt.mimeType) + if got != tt.want { + t.Errorf("extensionFromMimeType(%q) = %q, want %q", tt.mimeType, got, tt.want) + } + } +} + +func contains(s, substr string) bool { + return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsStr(s, substr)) +} + +func containsStr(s, substr string) bool { + for i := 0; i <= len(s)-len(substr); i++ { + if s[i:i+len(substr)] == substr { + return true + } + } + return false +} diff --git a/apps/backend/internal/agentctl/server/adapter/transport/streamjson/adapter.go b/apps/backend/internal/agentctl/server/adapter/transport/streamjson/adapter.go index 48807358d3..b43d60bc0c 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/streamjson/adapter.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/streamjson/adapter.go @@ -118,6 +118,9 @@ type Adapter struct { promptTraceCtx context.Context promptTraceMu sync.RWMutex + // Attachment management + attachMgr *shared.AttachmentManager + // Synchronization mu sync.RWMutex closed bool @@ -141,9 +144,10 @@ type resultComplete struct { // cfg.AgentID is required for debug file naming. func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter { ctx, cancel := context.WithCancel(context.Background()) + l := log.WithFields(zap.String("adapter", "stream-json"), zap.String("agent_id", cfg.AgentID)) return &Adapter{ cfg: cfg, - logger: log.WithFields(zap.String("adapter", "stream-json"), zap.String("agent_id", cfg.AgentID)), + logger: l, agentID: cfg.AgentID, normalizer: NewNormalizer(), ctx: ctx, @@ -151,6 +155,7 @@ func NewAdapter(cfg *shared.Config, log *logger.Logger) *Adapter { updatesCh: make(chan AgentEvent, 100), mainModelContextWindow: defaultContextWindow, pendingToolCalls: make(map[string]*streams.NormalizedPayload), + attachMgr: shared.NewAttachmentManager(cfg.WorkDir, l.Zap()), } } @@ -180,6 +185,9 @@ func (a *Adapter) Close() error { a.logger.Info("closing stream-json adapter") + // Clean up any saved attachments + a.attachMgr.Cleanup() + // Cancel the context to stop the read loop if a.cancel != nil { a.cancel() diff --git a/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_prompt.go b/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_prompt.go index 30d9dd7971..5d93593aec 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_prompt.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_prompt.go @@ -2,11 +2,7 @@ package streamjson import ( "context" - "encoding/base64" "fmt" - "os" - "path/filepath" - "strings" "github.com/google/uuid" "github.com/kandev/kandev/internal/agentctl/server/adapter/transport/shared" @@ -26,7 +22,6 @@ func (a *Adapter) Prompt(ctx context.Context, message string, attachments []v1.M sessionID := a.sessionID operationID := uuid.New().String() a.operationID = operationID - workDir := a.cfg.WorkDir // Create channel to wait for result a.resultCh = make(chan resultComplete, 1) a.mu.Unlock() @@ -35,14 +30,14 @@ func (a *Adapter) Prompt(ctx context.Context, message string, attachments []v1.M return fmt.Errorf("adapter not initialized") } - // Handle image attachments by saving to temp files + // Handle attachments by saving to workspace and referencing in prompt finalMessage := message if len(attachments) > 0 { - imagePaths, err := a.saveImageAttachments(workDir, attachments) + saved, err := a.attachMgr.SaveAttachments(attachments) if err != nil { - a.logger.Warn("failed to save image attachments", zap.Error(err)) - } else if len(imagePaths) > 0 { - finalMessage = a.buildMessageWithImages(message, imagePaths) + a.logger.Warn("failed to save attachments", zap.Error(err)) + } else if len(saved) > 0 { + finalMessage = shared.BuildAttachmentPrompt(saved) + message } } @@ -98,92 +93,12 @@ func (a *Adapter) Prompt(ctx context.Context, message string, attachments []v1.M a.logger.Info("prompt completed", zap.String("operation_id", operationID), zap.Bool("success", result.success)) + // Clean up saved attachments — agent has finished reading them + a.attachMgr.Cleanup() return nil } } -// saveImageAttachments saves image attachments to temp files in the workspace. -// Returns the relative paths to the saved files. -func (a *Adapter) saveImageAttachments(workDir string, attachments []v1.MessageAttachment) ([]string, error) { - var imagePaths []string - - // Create temp directory for images - tempDir := filepath.Join(workDir, ".kandev", "temp", "images") - if err := os.MkdirAll(tempDir, 0755); err != nil { - return nil, fmt.Errorf("failed to create temp directory: %w", err) - } - - for _, att := range attachments { - if att.Type != "image" { - continue - } - - // Decode base64 data - imageData, err := base64.StdEncoding.DecodeString(att.Data) - if err != nil { - a.logger.Warn("failed to decode image attachment", zap.Error(err)) - continue - } - - // Determine file extension from mime type - ext := ".png" // default - switch att.MimeType { - case "image/jpeg": - ext = ".jpg" - case "image/gif": - ext = ".gif" - case "image/webp": - ext = ".webp" - case "image/png": - ext = ".png" - } - - // Generate unique filename - filename := fmt.Sprintf("image-%s%s", uuid.New().String()[:8], ext) - filePath := filepath.Join(tempDir, filename) - - // Write image to file - if err := os.WriteFile(filePath, imageData, 0644); err != nil { - a.logger.Warn("failed to write image file", zap.Error(err), zap.String("path", filePath)) - continue - } - - // Store relative path from workspace root - relPath, err := filepath.Rel(workDir, filePath) - if err != nil { - relPath = filePath // Fall back to absolute path - } - - imagePaths = append(imagePaths, relPath) - a.logger.Info("saved image attachment", - zap.String("path", relPath), - zap.Int("size", len(imageData))) - } - - return imagePaths, nil -} - -// buildMessageWithImages prepends image file references to the user's message. -func (a *Adapter) buildMessageWithImages(message string, imagePaths []string) string { - var sb strings.Builder - - // Add image references at the beginning - if len(imagePaths) == 1 { - sb.WriteString(fmt.Sprintf("I've attached an image file that you should read and analyze: %s\n\n", imagePaths[0])) - } else { - sb.WriteString("I've attached image files that you should read and analyze:\n") - for _, path := range imagePaths { - sb.WriteString(fmt.Sprintf("- %s\n", path)) - } - sb.WriteString("\n") - } - - // Add the original message - sb.WriteString(message) - - return sb.String() -} - // Cancel interrupts the current operation. func (a *Adapter) Cancel(ctx context.Context) error { a.mu.RLock() diff --git a/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_session.go b/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_session.go index f520ca058f..265437d3cd 100644 --- a/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_session.go +++ b/apps/backend/internal/agentctl/server/adapter/transport/streamjson/streamjson_session.go @@ -43,6 +43,7 @@ func (a *Adapter) NewSession(ctx context.Context, _ []types.McpServer) (string, pendingCommands := a.takePendingCommands() a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) a.logger.Info("created new session placeholder", zap.String("session_id", sessionID)) a.emitPendingCommands(sessionID, pendingCommands) @@ -57,6 +58,7 @@ func (a *Adapter) LoadSession(ctx context.Context, sessionID string) error { pendingCommands := a.takePendingCommands() a.mu.Unlock() + a.attachMgr.SetSessionID(sessionID) a.logger.Info("loaded session", zap.String("session_id", sessionID)) a.emitPendingCommands(sessionID, pendingCommands) diff --git a/apps/backend/internal/agentctl/server/api/agent.go b/apps/backend/internal/agentctl/server/api/agent.go index 22b5e14c73..9350393a5a 100644 --- a/apps/backend/internal/agentctl/server/api/agent.go +++ b/apps/backend/internal/agentctl/server/api/agent.go @@ -248,6 +248,14 @@ func (s *Server) handleAgentStreamRequest(ctx context.Context, msg *ws.Message) return s.handleWSPermissionRespond(ctx, msg) case "agent.stderr": return s.handleWSStderr(ctx, msg) + case "agent.session.set_mode": + return s.handleWSSetMode(ctx, msg) + case "agent.session.set_model": + return s.handleWSSetModel(ctx, msg) + case "agent.session.authenticate": + return s.handleWSAuthenticate(ctx, msg) + case "agent.session.reset": + return s.handleWSResetSession(ctx, msg) default: resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeUnknownAction, fmt.Sprintf("unknown action: %s", msg.Action), nil) return resp @@ -476,3 +484,105 @@ func (s *Server) handleWSStderr(_ context.Context, msg *ws.Message) *ws.Message resp, _ := ws.NewResponse(msg.ID, msg.Action, AgentStderrResponse{Lines: lines}) return resp } + +func (s *Server) handleWSSetMode(ctx context.Context, msg *ws.Message) *ws.Message { + var req struct { + SessionID string `json:"session_id"` + ModeID string `json:"mode_id"` + } + return s.adapterAction(ctx, msg, &req, func(a adapter.AgentAdapter) error { + ms, ok := a.(adapter.ModeSettableAdapter) + if !ok { + return fmt.Errorf("agent does not support mode switching") + } + return ms.SetMode(ctx, req.ModeID) + }) +} + +// adapterAction extracts common boilerplate for WS handlers that operate on the agent adapter: +// parse payload, get adapter, assert interface, call action. +func (s *Server) adapterAction( + ctx context.Context, + msg *ws.Message, + payload any, + action func(agentAdapter adapter.AgentAdapter) error, +) *ws.Message { + if err := msg.ParsePayload(payload); err != nil { + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid request: "+err.Error(), nil) + return resp + } + + agentAdapter := s.procMgr.GetAdapter() + if agentAdapter == nil { + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "agent not running", nil) + return resp + } + + if err := action(agentAdapter); err != nil { + s.logger.Error(msg.Action+" failed", zap.Error(err)) + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil) + return resp + } + + resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]any{"success": true}) + return resp +} + +func (s *Server) handleWSSetModel(ctx context.Context, msg *ws.Message) *ws.Message { + var req struct { + ModelID string `json:"model_id"` + } + return s.adapterAction(ctx, msg, &req, func(a adapter.AgentAdapter) error { + ms, ok := a.(adapter.ModelSettableAdapter) + if !ok { + return fmt.Errorf("agent does not support model switching") + } + return ms.SetModel(ctx, req.ModelID) + }) +} + +func (s *Server) handleWSAuthenticate(ctx context.Context, msg *ws.Message) *ws.Message { + var req struct { + MethodID string `json:"method_id"` + } + return s.adapterAction(ctx, msg, &req, func(a adapter.AgentAdapter) error { + aa, ok := a.(adapter.AuthenticatableAdapter) + if !ok { + return fmt.Errorf("agent does not support authenticate") + } + return aa.Authenticate(ctx, req.MethodID) + }) +} + +func (s *Server) handleWSResetSession(ctx context.Context, msg *ws.Message) *ws.Message { + var req NewSessionRequest + if err := msg.ParsePayload(&req); err != nil { + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "invalid request: "+err.Error(), nil) + return resp + } + + agentAdapter := s.procMgr.GetAdapter() + if agentAdapter == nil { + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "agent not running", nil) + return resp + } + + sr, ok := agentAdapter.(adapter.SessionResettableAdapter) + if !ok { + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "agent does not support session reset", nil) + return resp + } + + sessionID, err := sr.ResetSession(ctx, req.McpServers) + if err != nil { + s.logger.Error("session reset failed", zap.Error(err)) + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil) + return resp + } + + resp, _ := ws.NewResponse(msg.ID, msg.Action, NewSessionResponse{ + Success: true, + SessionID: sessionID, + }) + return resp +} diff --git a/apps/backend/internal/agentctl/server/process/workspace_tracker.go b/apps/backend/internal/agentctl/server/process/workspace_tracker.go index 32610fbef9..29f955f925 100644 --- a/apps/backend/internal/agentctl/server/process/workspace_tracker.go +++ b/apps/backend/internal/agentctl/server/process/workspace_tracker.go @@ -50,10 +50,12 @@ type WorkspaceTracker struct { gitPollInterval time.Duration // Control - stopCh chan struct{} - wg sync.WaitGroup - started bool - stopOnce sync.Once + stopCh chan struct{} + wg sync.WaitGroup + started bool + stopOnce sync.Once + cancelCtx context.Context // Cancellable context for killing in-flight git commands on Stop + cancelFunc context.CancelFunc // Cancel function called during Stop } // NewWorkspaceTracker creates a new workspace tracker @@ -63,6 +65,8 @@ func NewWorkspaceTracker(workDir string, log *logger.Logger) *WorkspaceTracker { // Cache validated git index path (works with worktrees where .git is a file) gitIndexPath := resolveGitIndexPath(resolvedWorkDir) + ctx, cancel := context.WithCancel(context.Background()) + return &WorkspaceTracker{ workDir: resolvedWorkDir, gitIndexPath: gitIndexPath, @@ -70,6 +74,8 @@ func NewWorkspaceTracker(workDir string, log *logger.Logger) *WorkspaceTracker { workspaceStreamSubscribers: make(map[types.WorkspaceStreamSubscriber]struct{}), gitPollInterval: DefaultGitPollInterval, stopCh: make(chan struct{}), + cancelCtx: ctx, + cancelFunc: cancel, } } @@ -101,7 +107,9 @@ func resolveGitIndexPath(workDir string) string { // Start begins monitoring the workspace using polling (no fsnotify). // File changes are detected via git status polling, which is efficient and // doesn't consume file descriptors like fsnotify/kqueue does on macOS. -func (wt *WorkspaceTracker) Start(ctx context.Context) { +// The passed context is ignored — the tracker uses its own cancellable context +// so that Stop() can kill in-flight git commands immediately. +func (wt *WorkspaceTracker) Start(_ context.Context) { wt.mu.Lock() if wt.started { wt.mu.Unlock() @@ -113,18 +121,35 @@ func (wt *WorkspaceTracker) Start(ctx context.Context) { // Start file change monitoring (uses git status polling) wt.wg.Add(1) - go wt.monitorLoop(ctx) + go wt.monitorLoop(wt.cancelCtx) // Start git polling for detecting manual git operations (commits, resets, etc.) wt.wg.Add(1) - go wt.pollGitChanges(ctx) + go wt.pollGitChanges(wt.cancelCtx) } -// Stop stops the workspace tracker +// stopTimeout is the maximum time Stop() will wait for goroutines to exit. +const stopTimeout = 5 * time.Second + +// Stop stops the workspace tracker. It cancels in-flight git commands and waits +// up to 5 seconds for goroutines to exit before proceeding. func (wt *WorkspaceTracker) Stop() { wt.stopOnce.Do(func() { + wt.cancelFunc() // Kill in-flight git commands immediately close(wt.stopCh) - wt.wg.Wait() + + done := make(chan struct{}) + go func() { + wt.wg.Wait() + close(done) + }() + select { + case <-done: + // Clean shutdown + case <-time.After(stopTimeout): + wt.logger.Warn("workspace tracker stop timed out, proceeding anyway", + zap.Duration("timeout", stopTimeout)) + } wt.logger.Info("workspace tracker stopped") }) } diff --git a/apps/backend/internal/agentctl/types/streams/agent.go b/apps/backend/internal/agentctl/types/streams/agent.go index 8cd95b500a..cf08f28e61 100644 --- a/apps/backend/internal/agentctl/types/streams/agent.go +++ b/apps/backend/internal/agentctl/types/streams/agent.go @@ -45,6 +45,12 @@ const ( // EventTypeRateLimit indicates the agent is being rate-limited by the API. EventTypeRateLimit = "rate_limit" + + // EventTypeAgentCapabilities indicates agent capabilities from ACP initialize. + EventTypeAgentCapabilities = "agent_capabilities" + + // EventTypeSessionModels indicates available models from ACP session/new. + EventTypeSessionModels = "session_models" ) // Session status constants for EventTypeSessionStatus events. @@ -195,6 +201,39 @@ type AgentEvent struct { // CurrentModeID is the active session mode identifier (e.g., "code", "ask", "architect"). CurrentModeID string `json:"current_mode_id,omitempty"` + + // AvailableModes lists the modes the agent supports. + AvailableModes []SessionModeInfo `json:"available_modes,omitempty"` + + // --- Agent capabilities fields (for "agent_capabilities" type) --- + + // SupportsImage indicates the agent natively supports image content blocks. + SupportsImage bool `json:"supports_image"` + + // SupportsAudio indicates the agent natively supports audio content blocks. + SupportsAudio bool `json:"supports_audio"` + + // SupportsEmbeddedContext indicates the agent supports embedded context. + SupportsEmbeddedContext bool `json:"supports_embedded_context"` + + // AuthMethods lists authentication methods from ACP initialize. + AuthMethods []AuthMethodInfo `json:"auth_methods,omitempty"` + + // --- Session models fields (for "session_models" type) --- + + // CurrentModelID is the active model identifier. + CurrentModelID string `json:"current_model_id,omitempty"` + + // SessionModels lists models available in the ACP session. + SessionModels []SessionModelInfo `json:"session_models,omitempty"` + + // ConfigOptions lists session configuration options from ACP _meta. + ConfigOptions []ConfigOption `json:"config_options,omitempty"` + + // --- Usage fields (attached to "complete" event) --- + + // Usage contains token usage stats from the prompt response. + Usage *PromptUsage `json:"usage,omitempty"` } // PlanEntry represents an entry in the agent's execution plan. @@ -252,6 +291,105 @@ type ContentBlock struct { Size *int `json:"size,omitempty"` } +// SessionModeInfo represents an available session mode from ACP. +type SessionModeInfo struct { + // ID is the mode identifier (e.g., "code", "ask", "architect"). + ID string `json:"id"` + + // Name is a human-readable name for the mode. + Name string `json:"name"` + + // Description provides additional context about the mode. + Description string `json:"description,omitempty"` +} + +// SessionModelInfo represents a model available in an ACP session. +type SessionModelInfo struct { + // ModelID is the model identifier. + ModelID string `json:"model_id"` + + // Name is a human-readable model name. + Name string `json:"name"` + + // Description provides additional context about the model. + Description string `json:"description,omitempty"` + + // UsageMultiplier is the normalized pricing multiplier (e.g., "1x", "3x"). + UsageMultiplier string `json:"usage_multiplier,omitempty"` + + // Meta contains raw _meta from the agent for agent-specific rendering. + Meta map[string]any `json:"meta,omitempty"` +} + +// AuthMethodInfo represents an authentication method from ACP initialize. +type AuthMethodInfo struct { + // ID is the auth method identifier. + ID string `json:"id"` + + // Name is a human-readable name for the auth method. + Name string `json:"name"` + + // Description provides additional context. + Description string `json:"description,omitempty"` + + // TerminalAuth contains normalized terminal-based auth info from _meta. + TerminalAuth *TerminalAuth `json:"terminal_auth,omitempty"` + + // Meta contains raw _meta from the agent. + Meta map[string]any `json:"meta,omitempty"` +} + +// TerminalAuth contains normalized terminal-based authentication info. +type TerminalAuth struct { + // Command is the CLI command to run (e.g., "copilot"). + Command string `json:"command"` + + // Args are the command arguments (e.g., ["auth", "login"]). + Args []string `json:"args,omitempty"` + + // Label is a human-readable description of the auth action. + Label string `json:"label,omitempty"` +} + +// ConfigOption represents a session configuration option from ACP _meta. +type ConfigOption struct { + // Type is the option type: "select", "toggle", etc. + Type string `json:"type"` + + // ID is the option identifier (e.g., "mode", "model", "reasoning_effort"). + ID string `json:"id"` + + // Name is a human-readable name. + Name string `json:"name"` + + // CurrentValue is the currently selected value. + CurrentValue string `json:"current_value"` + + // Category groups related options. + Category string `json:"category,omitempty"` + + // Options lists the selectable values. + Options []ConfigOptionValue `json:"options,omitempty"` +} + +// ConfigOptionValue represents a selectable value for a ConfigOption. +type ConfigOptionValue struct { + // Value is the option value. + Value string `json:"value"` + + // Name is a human-readable label. + Name string `json:"name"` +} + +// PromptUsage contains token usage info from an ACP prompt response. +type PromptUsage struct { + InputTokens int64 `json:"input_tokens"` + OutputTokens int64 `json:"output_tokens"` + CachedReadTokens int64 `json:"cached_read_tokens,omitempty"` + CachedWriteTokens int64 `json:"cached_write_tokens,omitempty"` + TotalTokens int64 `json:"total_tokens"` +} + // ToolCallContentItem represents a content item produced by a tool call. // This is a discriminated union: exactly one of Content, Diff, or Terminal fields will be set. type ToolCallContentItem struct { diff --git a/apps/backend/internal/events/types.go b/apps/backend/internal/events/types.go index 5e4998d694..21624612ee 100644 --- a/apps/backend/internal/events/types.go +++ b/apps/backend/internal/events/types.go @@ -164,6 +164,21 @@ const ( SessionModeChanged = "session_mode.changed" // Agent session mode changed ) +// Event types for ACP capabilities and models +const ( + AgentCapabilitiesUpdated = "agent_capabilities.updated" // Agent capabilities received + SessionModelsUpdated = "session_models.updated" // Session models received +) + +// Event types for session todos (ACP plan entries) +const ( + SessionTodosUpdated = "session_todos.updated" // Agent plan/todo entries updated +) + +const ( + SessionPromptUsageUpdated = "session_prompt_usage.updated" // Prompt token usage updated +) + // Event types for GitHub integration const ( GitHubPRFeedback = "github.pr_feedback" // PR has new feedback (UI notification only) @@ -293,3 +308,43 @@ func BuildSessionModeSubject(sessionID string) string { func BuildSessionModeWildcardSubject() string { return SessionModeChanged + ".*" } + +// BuildAgentCapabilitiesSubject creates an agent capabilities subject for a specific session +func BuildAgentCapabilitiesSubject(sessionID string) string { + return AgentCapabilitiesUpdated + "." + sessionID +} + +// BuildAgentCapabilitiesWildcardSubject creates a wildcard subscription for all agent capabilities events +func BuildAgentCapabilitiesWildcardSubject() string { + return AgentCapabilitiesUpdated + ".*" +} + +// BuildSessionModelsSubject creates a session models subject for a specific session +func BuildSessionModelsSubject(sessionID string) string { + return SessionModelsUpdated + "." + sessionID +} + +// BuildSessionModelsWildcardSubject creates a wildcard subscription for all session models events +func BuildSessionModelsWildcardSubject() string { + return SessionModelsUpdated + ".*" +} + +// BuildSessionTodosSubject creates a session todos subject for a specific session +func BuildSessionTodosSubject(sessionID string) string { + return SessionTodosUpdated + "." + sessionID +} + +// BuildSessionTodosWildcardSubject creates a wildcard subscription for all session todos events +func BuildSessionTodosWildcardSubject() string { + return SessionTodosUpdated + ".*" +} + +// BuildSessionPromptUsageSubject creates a prompt usage subject for a specific session +func BuildSessionPromptUsageSubject(sessionID string) string { + return SessionPromptUsageUpdated + "." + sessionID +} + +// BuildSessionPromptUsageWildcardSubject creates a wildcard subscription for all prompt usage events +func BuildSessionPromptUsageWildcardSubject() string { + return SessionPromptUsageUpdated + ".*" +} diff --git a/apps/backend/internal/gateway/websocket/session_notifications.go b/apps/backend/internal/gateway/websocket/session_notifications.go index e9892b23c6..7caad8a563 100644 --- a/apps/backend/internal/gateway/websocket/session_notifications.go +++ b/apps/backend/internal/gateway/websocket/session_notifications.go @@ -49,6 +49,10 @@ func RegisterSessionStreamNotifications(ctx context.Context, eventBus bus.EventB b.subscribe(eventBus, events.BuildProcessStatusWildcardSubject(), ws.ActionSessionProcessStatus) b.subscribe(eventBus, events.BuildAvailableCommandsWildcardSubject(), ws.ActionSessionAvailableCommands) b.subscribe(eventBus, events.BuildSessionModeWildcardSubject(), ws.ActionSessionModeChanged) + b.subscribe(eventBus, events.BuildAgentCapabilitiesWildcardSubject(), ws.ActionSessionAgentCapabilities) + b.subscribe(eventBus, events.BuildSessionModelsWildcardSubject(), ws.ActionSessionModelsUpdated) + b.subscribe(eventBus, events.BuildSessionTodosWildcardSubject(), ws.ActionSessionTodosUpdated) + b.subscribe(eventBus, events.BuildSessionPromptUsageWildcardSubject(), ws.ActionSessionPromptUsage) go func() { <-ctx.Done() diff --git a/apps/backend/internal/integration/simulated_agent_manager_test.go b/apps/backend/internal/integration/simulated_agent_manager_test.go index bb6d66f034..06f16d2829 100644 --- a/apps/backend/internal/integration/simulated_agent_manager_test.go +++ b/apps/backend/internal/integration/simulated_agent_manager_test.go @@ -406,6 +406,14 @@ func (s *SimulatedAgentManagerClient) RestartAgentProcess(ctx context.Context, a return nil } +func (s *SimulatedAgentManagerClient) ResetAgentContext(ctx context.Context, agentExecutionID string) error { + return s.RestartAgentProcess(ctx, agentExecutionID) +} + +func (s *SimulatedAgentManagerClient) SetSessionModelBySessionID(_ context.Context, _, _ string) error { + return fmt.Errorf("not supported") +} + func (s *SimulatedAgentManagerClient) WasSessionInitialized(_ string) bool { return false } func (s *SimulatedAgentManagerClient) IsPassthroughSession(ctx context.Context, sessionID string) bool { return false diff --git a/apps/backend/internal/integration/test_server_test.go b/apps/backend/internal/integration/test_server_test.go index 418387d777..00975d2f00 100644 --- a/apps/backend/internal/integration/test_server_test.go +++ b/apps/backend/internal/integration/test_server_test.go @@ -198,6 +198,7 @@ func (a *testMessageCreatorAdapter) CreateThinkingMessageStreaming(ctx context.C func (a *testMessageCreatorAdapter) AppendThinkingMessage(ctx context.Context, messageID, additionalContent string) error { return a.svc.AppendThinkingContent(ctx, messageID, additionalContent) } +func (a *testMessageCreatorAdapter) InvalidateModelCache(string) {} // testTurnServiceAdapter adapts the task service to the orchestrator.TurnService interface for tests type testTurnServiceAdapter struct { diff --git a/apps/backend/internal/orchestrator/event_handlers_streaming.go b/apps/backend/internal/orchestrator/event_handlers_streaming.go index ad96160e3f..75c0d345db 100644 --- a/apps/backend/internal/orchestrator/event_handlers_streaming.go +++ b/apps/backend/internal/orchestrator/event_handlers_streaming.go @@ -7,6 +7,7 @@ import ( "go.uber.org/zap" "github.com/kandev/kandev/internal/agent/lifecycle" + "github.com/kandev/kandev/internal/agentctl/types/streams" "github.com/kandev/kandev/internal/events" "github.com/kandev/kandev/internal/events/bus" "github.com/kandev/kandev/internal/task/models" @@ -62,6 +63,15 @@ func (s *Service) handleAgentStreamEvent(ctx context.Context, payload *lifecycle case "session_mode": s.handleSessionModeEvent(ctx, payload) + case "agent_capabilities": + s.handleAgentCapabilitiesEvent(ctx, payload) + + case "session_models": + s.handleSessionModelsEvent(ctx, payload) + + case "plan": + s.handleSessionTodosEvent(ctx, payload) + case "permission_cancelled": s.handlePermissionCancelledEvent(ctx, payload) @@ -451,6 +461,7 @@ func (s *Service) handleCompleteStreamEvent(ctx context.Context, payload *lifecy s.saveAgentTextIfPresent(ctx, payload) s.publishAgentPlanIfPresent(ctx, payload) + s.publishPromptUsage(ctx, payload) s.completeTurnForSession(ctx, payload.SessionID) // Cancel any pending clarifications for this session so WaitForResponse @@ -502,6 +513,23 @@ func (s *Service) publishAgentPlanIfPresent(ctx context.Context, payload *lifecy } } +// publishPromptUsage broadcasts prompt token usage to the WebSocket for the frontend. +func (s *Service) publishPromptUsage(ctx context.Context, payload *lifecycle.AgentStreamEventPayload) { + sessionID := payload.SessionID + if sessionID == "" || s.eventBus == nil || payload.Data.Usage == nil { + return + } + eventPayload := lifecycle.SessionPromptUsageEventPayload{ + TaskID: payload.TaskID, + SessionID: sessionID, + AgentID: payload.AgentID, + Usage: payload.Data.Usage, + Timestamp: time.Now().UTC().Format(time.RFC3339), + } + subject := events.BuildSessionPromptUsageSubject(sessionID) + _ = s.eventBus.Publish(ctx, subject, bus.NewEvent(events.SessionPromptUsageUpdated, "orchestrator", eventPayload)) +} + // handleAvailableCommandsEvent broadcasts available_commands events to the WebSocket for the frontend. func (s *Service) handleAvailableCommandsEvent(ctx context.Context, payload *lifecycle.AgentStreamEventPayload) { sessionID := payload.SessionID @@ -525,21 +553,135 @@ func (s *Service) handleSessionModeEvent(ctx context.Context, payload *lifecycle if sessionID == "" || s.eventBus == nil { return } - // Don't broadcast "default" mode — it's the baseline state, not worth sending. - if payload.Data.CurrentModeID == "default" { - return - } eventPayload := lifecycle.SessionModeEventPayload{ - TaskID: payload.TaskID, - SessionID: sessionID, - AgentID: payload.AgentID, - CurrentModeID: payload.Data.CurrentModeID, - Timestamp: time.Now().UTC().Format(time.RFC3339), + TaskID: payload.TaskID, + SessionID: sessionID, + AgentID: payload.AgentID, + CurrentModeID: payload.Data.CurrentModeID, + AvailableModes: payload.Data.AvailableModes, + Timestamp: time.Now().UTC().Format(time.RFC3339), } subject := events.BuildSessionModeSubject(sessionID) _ = s.eventBus.Publish(ctx, subject, bus.NewEvent(events.SessionModeChanged, "orchestrator", eventPayload)) } +// handleAgentCapabilitiesEvent broadcasts agent_capabilities events to the WebSocket. +func (s *Service) handleAgentCapabilitiesEvent(ctx context.Context, payload *lifecycle.AgentStreamEventPayload) { + sessionID := payload.SessionID + if sessionID == "" || s.eventBus == nil { + return + } + eventPayload := lifecycle.AgentCapabilitiesEventPayload{ + TaskID: payload.TaskID, + SessionID: sessionID, + AgentID: payload.AgentID, + SupportsImage: payload.Data.SupportsImage, + SupportsAudio: payload.Data.SupportsAudio, + SupportsEmbeddedContext: payload.Data.SupportsEmbeddedContext, + AuthMethods: payload.Data.AuthMethods, + Timestamp: time.Now().UTC().Format(time.RFC3339), + } + subject := events.BuildAgentCapabilitiesSubject(sessionID) + _ = s.eventBus.Publish(ctx, subject, bus.NewEvent(events.AgentCapabilitiesUpdated, "orchestrator", eventPayload)) +} + +// handleSessionModelsEvent broadcasts session_models events to the WebSocket +// and persists the current model to the session snapshot so it survives page refresh. +func (s *Service) handleSessionModelsEvent(ctx context.Context, payload *lifecycle.AgentStreamEventPayload) { + sessionID := payload.SessionID + if sessionID == "" || s.eventBus == nil { + return + } + + // Persist the ACP-reported current model to the session snapshot so it's + // available after page refresh (SSR reads from the DB, not runtime state). + if currentModel := payload.Data.CurrentModelID; currentModel != "" { + s.persistSessionModel(ctx, sessionID, currentModel) + } + + eventPayload := lifecycle.SessionModelsEventPayload{ + TaskID: payload.TaskID, + SessionID: sessionID, + AgentID: payload.AgentID, + CurrentModelID: payload.Data.CurrentModelID, + Models: payload.Data.SessionModels, + ConfigOptions: payload.Data.ConfigOptions, + Timestamp: time.Now().UTC().Format(time.RFC3339), + } + subject := events.BuildSessionModelsSubject(sessionID) + _ = s.eventBus.Publish(ctx, subject, bus.NewEvent(events.SessionModelsUpdated, "orchestrator", eventPayload)) +} + +// persistSessionModel updates the session's AgentProfileSnapshot with the current model. +func (s *Service) persistSessionModel(ctx context.Context, sessionID, model string) { + session, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil { + return + } + if session.AgentProfileSnapshot == nil { + session.AgentProfileSnapshot = make(map[string]interface{}) + } + existing, _ := session.AgentProfileSnapshot["model"].(string) + if existing == model { + return + } + session.AgentProfileSnapshot["model"] = model + _ = s.repo.UpdateTaskSession(ctx, session) + // Invalidate the message creator's model cache so subsequent messages use the new model. + if s.messageCreator != nil { + s.messageCreator.InvalidateModelCache(sessionID) + } +} + +// handleSessionTodosEvent broadcasts plan/todo entries to the WebSocket and persists +// them as a chat message so they survive page refresh and appear in the chat timeline. +func (s *Service) handleSessionTodosEvent(ctx context.Context, payload *lifecycle.AgentStreamEventPayload) { + sessionID := payload.SessionID + if sessionID == "" || s.eventBus == nil { + return + } + entries := payload.Data.PlanEntries + + // Broadcast real-time update via event bus (updates the store's sessionTodos) + eventPayload := lifecycle.SessionTodosEventPayload{ + TaskID: payload.TaskID, + SessionID: sessionID, + AgentID: payload.AgentID, + Entries: entries, + Timestamp: time.Now().UTC().Format(time.RFC3339), + } + subject := events.BuildSessionTodosSubject(sessionID) + _ = s.eventBus.Publish(ctx, subject, bus.NewEvent(events.SessionTodosUpdated, "orchestrator", eventPayload)) + + // Persist as a chat message so todos appear in the timeline and survive refresh + s.persistTodoMessage(ctx, payload.TaskID, sessionID, entries) +} + +// persistTodoMessage creates a "todo" message with the todo entries as metadata. +// Empty entries are persisted too — they represent the agent clearing all todos. +func (s *Service) persistTodoMessage(ctx context.Context, taskID, sessionID string, entries []streams.PlanEntry) { + if s.messageCreator == nil { + return + } + todos := make([]map[string]interface{}, len(entries)) + for i, e := range entries { + todos[i] = map[string]interface{}{ + "text": e.Description, + "status": e.Status, + "done": e.Status == "completed", + } + } + metadata := map[string]interface{}{"todos": todos} + if err := s.messageCreator.CreateSessionMessage( + ctx, taskID, "Updated Todos", sessionID, + string(models.MessageTypeTodo), s.getActiveTurnID(sessionID), metadata, false, + ); err != nil { + s.logger.Warn("failed to create todo message", + zap.String("session_id", sessionID), + zap.Error(err)) + } +} + // handlePermissionCancelledEvent marks the pending permission message as expired. func (s *Service) handlePermissionCancelledEvent(ctx context.Context, payload *lifecycle.AgentStreamEventPayload) { sessionID := payload.SessionID diff --git a/apps/backend/internal/orchestrator/event_handlers_streaming_test.go b/apps/backend/internal/orchestrator/event_handlers_streaming_test.go index c0edc9b88d..dced66dfaf 100644 --- a/apps/backend/internal/orchestrator/event_handlers_streaming_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_streaming_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/kandev/kandev/internal/agent/lifecycle" + "github.com/kandev/kandev/internal/agentctl/types/streams" "github.com/kandev/kandev/internal/events/bus" ) @@ -52,7 +53,7 @@ func TestHandleSessionModeEvent(t *testing.T) { require.Len(t, eb.events, 1) }) - t.Run("skips default mode", func(t *testing.T) { + t.Run("publishes default mode without available modes (mode exit)", func(t *testing.T) { eb := &recordingEventBus{} svc := &Service{logger: testLogger(), eventBus: eb} @@ -63,7 +64,27 @@ func TestHandleSessionModeEvent(t *testing.T) { Data: &lifecycle.AgentStreamEventData{CurrentModeID: "default"}, }) - require.Empty(t, eb.events) + require.Len(t, eb.events, 1) + }) + + t.Run("publishes default mode with available modes (initial state)", func(t *testing.T) { + eb := &recordingEventBus{} + svc := &Service{logger: testLogger(), eventBus: eb} + + svc.handleSessionModeEvent(context.Background(), &lifecycle.AgentStreamEventPayload{ + TaskID: "t1", + SessionID: "s1", + AgentID: "a1", + Data: &lifecycle.AgentStreamEventData{ + CurrentModeID: "default", + AvailableModes: []streams.SessionModeInfo{ + {ID: "default", Name: "Default"}, + {ID: "plan", Name: "Plan"}, + }, + }, + }) + + require.Len(t, eb.events, 1) }) t.Run("publishes empty mode (mode exit)", func(t *testing.T) { diff --git a/apps/backend/internal/orchestrator/event_handlers_test.go b/apps/backend/internal/orchestrator/event_handlers_test.go index 61db9fce1a..1febe06a78 100644 --- a/apps/backend/internal/orchestrator/event_handlers_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_test.go @@ -165,9 +165,15 @@ func (m *mockAgentManager) RestartAgentProcess(_ context.Context, agentExecution m.restartProcessCalls = append(m.restartProcessCalls, agentExecutionID) return m.restartProcessErr } +func (m *mockAgentManager) ResetAgentContext(ctx context.Context, agentExecutionID string) error { + return m.RestartAgentProcess(ctx, agentExecutionID) +} func (m *mockAgentManager) SetExecutionDescription(_ context.Context, _, _ string) error { return nil } +func (m *mockAgentManager) SetSessionModelBySessionID(_ context.Context, _, _ string) error { + return fmt.Errorf("not supported") +} func (m *mockAgentManager) WasSessionInitialized(_ string) bool { return false } func (m *mockAgentManager) IsPassthroughSession(_ context.Context, _ string) bool { return m.isPassthrough diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow.go b/apps/backend/internal/orchestrator/event_handlers_workflow.go index e5b3160349..0ce1c15305 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow.go @@ -662,7 +662,7 @@ func (s *Service) resetAgentContext(ctx context.Context, taskID string, session s.setSessionResetInProgress(sessionID, true) defer s.setSessionResetInProgress(sessionID, false) - if err := s.agentManager.RestartAgentProcess(ctx, session.AgentExecutionID); err != nil { + if err := s.agentManager.ResetAgentContext(ctx, session.AgentExecutionID); err != nil { s.logger.Error("failed to reset agent context", zap.String("task_id", taskID), zap.String("session_id", sessionID), diff --git a/apps/backend/internal/orchestrator/executor/executor.go b/apps/backend/internal/orchestrator/executor/executor.go index e9449d1aa9..d96ced7850 100644 --- a/apps/backend/internal/orchestrator/executor/executor.go +++ b/apps/backend/internal/orchestrator/executor/executor.go @@ -100,6 +100,15 @@ type AgentManagerClient interface { // clearing the agent's conversation context. The execution environment (container/agentctl) is preserved. RestartAgentProcess(ctx context.Context, agentExecutionID string) error + // ResetAgentContext resets the agent's conversation context using the fastest available strategy. + // For ACP agents, this creates a new session without restarting the process. + // For other agents, this falls back to RestartAgentProcess. + ResetAgentContext(ctx context.Context, agentExecutionID string) error + + // SetSessionModelBySessionID attempts an in-place model switch via ACP session/set_model. + // Returns an error if the agent doesn't support in-place model switching. + SetSessionModelBySessionID(ctx context.Context, sessionID, modelID string) error + // WasSessionInitialized reports whether the given execution completed session initialization. // Used to distinguish launch-phase failures from normal prompt failures. WasSessionInitialized(executionID string) bool diff --git a/apps/backend/internal/orchestrator/executor/executor_interaction.go b/apps/backend/internal/orchestrator/executor/executor_interaction.go index 3c0c8514bf..4b4f0fbe4f 100644 --- a/apps/backend/internal/orchestrator/executor/executor_interaction.go +++ b/apps/backend/internal/orchestrator/executor/executor_interaction.go @@ -145,15 +145,27 @@ func (e *Executor) Prompt(ctx context.Context, taskID, sessionID string, prompt return result, nil } -// SwitchModel stops the current agent, restarts it with a new model, and sends the prompt. -// For agents that support session resume (can_recover: true), it attempts to resume context. -// For agents that don't support resume (can_recover: false), a fresh session is started. +// SwitchModel switches the model for a running session. It first attempts an in-place switch +// via ACP session/set_model (instant, no process restart). If the agent doesn't support +// in-place switching, it falls back to stopping and restarting the agent with the new model. func (e *Executor) SwitchModel(ctx context.Context, taskID, sessionID, newModel, prompt string) (*PromptResult, error) { e.logger.Info("switching model for session", zap.String("task_id", taskID), zap.String("session_id", sessionID), zap.String("new_model", newModel)) + // Try in-place model switch first (ACP agents support session/set_model) + if err := e.agentManager.SetSessionModelBySessionID(ctx, sessionID, newModel); err == nil { + e.logger.Info("model switched in-place via ACP session/set_model", + zap.String("session_id", sessionID), + zap.String("new_model", newModel)) + e.persistInPlaceModelSwitch(ctx, sessionID, newModel) + return &PromptResult{StopReason: "model_switched_in_place"}, nil + } + + e.logger.Debug("in-place model switch not available, falling back to agent restart", + zap.String("session_id", sessionID)) + session, task, acpSessionID, existingRunning, err := e.prepareModelSwitch(ctx, taskID, sessionID) if err != nil { return nil, err @@ -360,6 +372,27 @@ func (e *Executor) persistModelSwitchState(ctx context.Context, taskID, sessionI } } +// persistInPlaceModelSwitch updates the session snapshot model after a successful +// in-place model switch (no agent restart). Only the model field changes. +func (e *Executor) persistInPlaceModelSwitch(ctx context.Context, sessionID, newModel string) { + session, err := e.repo.GetTaskSession(ctx, sessionID) + if err != nil { + e.logger.Warn("failed to get session for in-place model switch persistence", + zap.String("session_id", sessionID), + zap.Error(err)) + return + } + if session.AgentProfileSnapshot == nil { + session.AgentProfileSnapshot = make(map[string]interface{}) + } + session.AgentProfileSnapshot["model"] = newModel + if err := e.repo.UpdateTaskSession(ctx, session); err != nil { + e.logger.Warn("failed to persist in-place model switch", + zap.String("session_id", sessionID), + zap.Error(err)) + } +} + // RespondToPermission sends a response to a permission request for a session func (e *Executor) RespondToPermission(ctx context.Context, sessionID, pendingID, optionID string, cancelled bool) error { e.logger.Debug("responding to permission request", diff --git a/apps/backend/internal/orchestrator/executor/executor_test.go b/apps/backend/internal/orchestrator/executor/executor_test.go index e776ca9703..c3173dabd3 100644 --- a/apps/backend/internal/orchestrator/executor/executor_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_test.go @@ -74,6 +74,13 @@ func (m *mockAgentManager) RespondToPermissionBySessionID(ctx context.Context, s func (m *mockAgentManager) RestartAgentProcess(ctx context.Context, agentExecutionID string) error { return nil } +func (m *mockAgentManager) ResetAgentContext(ctx context.Context, agentExecutionID string) error { + return nil +} + +func (m *mockAgentManager) SetSessionModelBySessionID(ctx context.Context, sessionID, modelID string) error { + return fmt.Errorf("not supported") +} func (m *mockAgentManager) IsAgentRunningForSession(ctx context.Context, sessionID string) bool { return false diff --git a/apps/backend/internal/orchestrator/scheduler/scheduler_test.go b/apps/backend/internal/orchestrator/scheduler/scheduler_test.go index 60c9f7e751..f0e083a05c 100644 --- a/apps/backend/internal/orchestrator/scheduler/scheduler_test.go +++ b/apps/backend/internal/orchestrator/scheduler/scheduler_test.go @@ -2,6 +2,7 @@ package scheduler import ( "context" + "errors" "path/filepath" "sync" "testing" @@ -72,6 +73,12 @@ func (m *mockAgentManager) RespondToPermissionBySessionID(ctx context.Context, s func (m *mockAgentManager) RestartAgentProcess(ctx context.Context, agentExecutionID string) error { return nil } +func (m *mockAgentManager) ResetAgentContext(ctx context.Context, agentExecutionID string) error { + return nil +} +func (m *mockAgentManager) SetSessionModelBySessionID(_ context.Context, _, _ string) error { + return errors.New("not supported") +} func (m *mockAgentManager) IsAgentRunningForSession(ctx context.Context, sessionID string) bool { return false diff --git a/apps/backend/internal/orchestrator/service.go b/apps/backend/internal/orchestrator/service.go index ca1ac7d1b9..a92b3d63ae 100644 --- a/apps/backend/internal/orchestrator/service.go +++ b/apps/backend/internal/orchestrator/service.go @@ -79,6 +79,9 @@ type MessageCreator interface { CreateThinkingMessageStreaming(ctx context.Context, messageID, taskID, content, agentSessionID, turnID string) error // AppendThinkingMessage appends additional content to an existing streaming thinking message AppendThinkingMessage(ctx context.Context, messageID, additionalContent string) error + // InvalidateModelCache clears any cached model for a session, forcing the next + // message to re-read the model from the DB. Called after model switches. + InvalidateModelCache(sessionID string) } // TurnService is an interface for managing session turns diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index ce71709495..3034eaa03e 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -1262,12 +1262,20 @@ func (s *Service) trySwitchModel(ctx context.Context, taskID, sessionID, model, zap.String("session_id", sessionID), zap.String("from", currentModel), zap.String("to", model)) - s.startTurnForSession(ctx, sessionID) switchCtx := context.WithoutCancel(ctx) switchResult, err := s.executor.SwitchModel(switchCtx, taskID, sessionID, model, effectivePrompt) if err != nil { return nil, true, fmt.Errorf("model switch failed: %w", err) } + if switchResult.StopReason == "model_switched_in_place" { + // Agent is still running with the new model — let PromptTask send the prompt normally. + // Invalidate the message creator's model cache so the next message picks up the new model. + if s.messageCreator != nil { + s.messageCreator.InvalidateModelCache(sessionID) + } + return nil, false, nil + } + s.startTurnForSession(ctx, sessionID) s.setSessionRunning(ctx, taskID, sessionID, session) return &PromptResult{ StopReason: switchResult.StopReason, diff --git a/apps/backend/internal/orchestrator/task_operations_test.go b/apps/backend/internal/orchestrator/task_operations_test.go index bfbe9c662e..3b3fc590b9 100644 --- a/apps/backend/internal/orchestrator/task_operations_test.go +++ b/apps/backend/internal/orchestrator/task_operations_test.go @@ -218,6 +218,7 @@ func (m *mockMessageCreator) CreateThinkingMessageStreaming(context.Context, str func (m *mockMessageCreator) AppendThinkingMessage(context.Context, string, string) error { return nil } +func (m *mockMessageCreator) InvalidateModelCache(string) {} func TestRecordInitialMessage_DoesNotChangeSessionState(t *testing.T) { ctx := context.Background() diff --git a/apps/backend/internal/task/handlers/process_handlers.go b/apps/backend/internal/task/handlers/process_handlers.go index 7835487df6..404ca4bbd5 100644 --- a/apps/backend/internal/task/handlers/process_handlers.go +++ b/apps/backend/internal/task/handlers/process_handlers.go @@ -59,6 +59,12 @@ func RegisterProcessRoutes( processes.POST("/:processId/stop", handlers.httpStopProcessByID) processes.GET("", handlers.httpListProcesses) processes.GET("/:processId", handlers.httpGetProcess) + + // Session-level ACP operations (mode/model switching) + session := api.Group("/task-sessions/:id") + session.POST("/set-mode", handlers.httpSetSessionMode) + session.POST("/set-model", handlers.httpSetSessionModel) + session.POST("/authenticate", handlers.httpAuthenticate) } type httpStartProcessRequest struct { @@ -470,3 +476,66 @@ func resolveScriptCommand( return "", "", "", fmt.Errorf("invalid script kind") } } + +// httpSetSessionMode sets the session mode for a running agent. +func (h *ProcessHandlers) httpSetSessionMode(c *gin.Context) { + sessionID := c.Param("id") + var req struct { + ModeID string `json:"mode_id"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": "invalid request: " + err.Error()}) + return + } + if err := h.lifecycleMgr.SetSessionModeBySessionID(c.Request.Context(), sessionID, req.ModeID); err != nil { + h.logger.Error("failed to set session mode", + zap.String("session_id", sessionID), + zap.String("mode_id", req.ModeID), + zap.Error(err)) + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{"ok": true}) +} + +// httpSetSessionModel sets the session model for a running agent. +func (h *ProcessHandlers) httpSetSessionModel(c *gin.Context) { + sessionID := c.Param("id") + var req struct { + ModelID string `json:"model_id"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": "invalid request: " + err.Error()}) + return + } + if err := h.lifecycleMgr.SetSessionModelBySessionID(c.Request.Context(), sessionID, req.ModelID); err != nil { + h.logger.Error("failed to set session model", + zap.String("session_id", sessionID), + zap.String("model_id", req.ModelID), + zap.Error(err)) + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{"ok": true}) +} + +// httpAuthenticate triggers authentication for a given auth method on a running agent. +func (h *ProcessHandlers) httpAuthenticate(c *gin.Context) { + sessionID := c.Param("id") + var req struct { + MethodID string `json:"method_id"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": "invalid request: " + err.Error()}) + return + } + if err := h.lifecycleMgr.AuthenticateBySessionID(c.Request.Context(), sessionID, req.MethodID); err != nil { + h.logger.Error("failed to authenticate", + zap.String("session_id", sessionID), + zap.String("method_id", req.MethodID), + zap.Error(err)) + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{"ok": true}) +} diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go index cf04ef3719..3d7aab79c0 100644 --- a/apps/backend/internal/task/models/models.go +++ b/apps/backend/internal/task/models/models.go @@ -116,6 +116,8 @@ const ( MessageTypeThinking MessageType = "thinking" // MessageTypeAgentPlan is for agent native plan content (e.g. ExitPlanMode) MessageTypeAgentPlan MessageType = "agent_plan" + // MessageTypeTodo is for agent todo/task list updates + MessageTypeTodo MessageType = "todo" ) // Message represents a message in a task session diff --git a/apps/backend/pkg/api/v1/task.go b/apps/backend/pkg/api/v1/task.go index 663610f382..2cbf279b7c 100644 --- a/apps/backend/pkg/api/v1/task.go +++ b/apps/backend/pkg/api/v1/task.go @@ -120,11 +120,14 @@ type TaskEvent struct { CreatedAt time.Time `json:"created_at"` } -// MessageAttachment represents an attachment (image, file, etc.) to a message +// MessageAttachment represents an attachment (image, file, etc.) to a message. +// Type determines the ACP content block: "image" → ImageBlock, "audio" → AudioBlock, +// "resource" → ResourceBlock (text or blob based on MIME type). type MessageAttachment struct { - Type string `json:"type"` // "image" - Data string `json:"data"` // Base64-encoded data - MimeType string `json:"mime_type"` // MIME type (e.g., "image/png") + Type string `json:"type"` // "image", "audio", "resource" + Data string `json:"data,omitempty"` // Base64-encoded data + MimeType string `json:"mime_type,omitempty"` // MIME type (e.g., "image/png") + Name string `json:"name,omitempty"` // Display name (e.g., filename) } // ContextFileMeta represents a context file reference attached to a message diff --git a/apps/backend/pkg/websocket/actions.go b/apps/backend/pkg/websocket/actions.go index be164ca7e6..c085f80e88 100644 --- a/apps/backend/pkg/websocket/actions.go +++ b/apps/backend/pkg/websocket/actions.go @@ -167,6 +167,11 @@ const ( ActionSessionTurnCompleted = "session.turn.completed" ActionSessionAvailableCommands = "session.available_commands" ActionSessionModeChanged = "session.mode_changed" + ActionSessionAgentCapabilities = "session.agent_capabilities" + ActionSessionModelsUpdated = "session.models_updated" + ActionSessionSetMode = "session.set_mode" + ActionSessionTodosUpdated = "session.todos_updated" + ActionSessionPromptUsage = "session.prompt_usage" ActionInputRequested = "input.requested" ActionRepositoryCreated = "repository.created" ActionRepositoryUpdated = "repository.updated" diff --git a/apps/web/components/combobox.tsx b/apps/web/components/combobox.tsx index 428354448a..6775733490 100644 --- a/apps/web/components/combobox.tsx +++ b/apps/web/components/combobox.tsx @@ -35,6 +35,59 @@ interface ComboboxProps { triggerClassName?: string; showSearch?: boolean; testId?: string; + popoverSide?: "top" | "right" | "bottom" | "left"; + popoverAlign?: "start" | "center" | "end"; + /** When true, the trigger always renders the plain label text instead of renderLabel. */ + plainTrigger?: boolean; +} + +function TriggerLabel({ + selectedOption, + plainTrigger, + placeholder, +}: { + selectedOption: ComboboxOption | undefined; + plainTrigger: boolean; + placeholder: string; +}) { + if (!plainTrigger && selectedOption?.renderLabel) { + return selectedOption.renderLabel(); + } + return {selectedOption?.label || placeholder}; +} + +function OptionsList({ + options, + value, + onSelect, +}: { + options: ComboboxOption[]; + value: string; + onSelect: (value: string) => void; +}) { + return ( + + {options.map((option) => ( + onSelect(option.value)} + className="relative pr-7" + > +
+ {option.renderLabel ? option.renderLabel() : option.label} +
+ +
+ ))} +
+ ); } export const Combobox = memo(function Combobox({ @@ -50,6 +103,9 @@ export const Combobox = memo(function Combobox({ triggerClassName, showSearch = true, testId, + popoverSide, + popoverAlign = "start", + plainTrigger = false, }: ComboboxProps) { const [open, setOpen] = useState(false); // Track the highlighted item. Defaults to the selected value so the current @@ -76,11 +132,11 @@ export const Combobox = memo(function Combobox({ data-testid={testId} >
- {selectedOption?.renderLabel ? ( - selectedOption.renderLabel() - ) : ( - {selectedOption?.label || placeholder} - )} +
@@ -91,7 +147,8 @@ export const Combobox = memo(function Combobox({ "w-[var(--radix-popover-trigger-width)] min-w-[300px] max-w-none p-0 max-h-[var(--radix-popover-content-available-height)]", className, )} - align="start" + side={popoverSide} + align={popoverAlign} > {dropdownLabel ? ( @@ -102,29 +159,14 @@ export const Combobox = memo(function Combobox({ {showSearch && } {emptyMessage} - - {options.map((option) => ( - { - onValueChange(option.value === value ? "" : option.value); - setOpen(false); - }} - className="relative pr-7" - > -
- {option.renderLabel ? option.renderLabel() : option.label} -
- -
- ))} -
+ { + onValueChange(v === value ? "" : v); + setOpen(false); + }} + />
diff --git a/apps/web/components/task/auth-methods-indicator.tsx b/apps/web/components/task/auth-methods-indicator.tsx new file mode 100644 index 0000000000..0480655f98 --- /dev/null +++ b/apps/web/components/task/auth-methods-indicator.tsx @@ -0,0 +1,82 @@ +"use client"; + +import { memo, useCallback } from "react"; +import { IconKey, IconTerminal2 } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover"; +import { useAppStore } from "@/components/state-provider"; +import { authenticateSession } from "@/lib/api/domains/session-api"; + +type AuthMethodsIndicatorProps = { + sessionId: string | null; +}; + +export const AuthMethodsIndicator = memo(function AuthMethodsIndicator({ + sessionId, +}: AuthMethodsIndicatorProps) { + const authMethods = useAppStore((state) => { + if (!sessionId) return undefined; + return state.agentCapabilities.bySessionId[sessionId]?.authMethods; + }); + + const handleAuthenticate = useCallback( + async (methodId: string) => { + if (!sessionId) return; + try { + await authenticateSession(sessionId, methodId); + } catch { + // Auth call failed — agent will report via events if successful + } + }, + [sessionId], + ); + + if (!sessionId || !authMethods || authMethods.length === 0) { + return null; + } + + return ( + + + + + +
+
Authentication
+ {authMethods.map((method) => ( +
+
{method.name}
+ {method.description && ( +
{method.description}
+ )} + {method.terminalAuth ? ( +
+ + + {method.terminalAuth.command} + {method.terminalAuth.args ? ` ${method.terminalAuth.args.join(" ")}` : ""} + +
+ ) : ( + + )} +
+ ))} +
+
+
+ ); +}); diff --git a/apps/web/components/task/chat/chat-input-area.tsx b/apps/web/components/task/chat/chat-input-area.tsx index 89ef7eeed5..291b150805 100644 --- a/apps/web/components/task/chat/chat-input-area.tsx +++ b/apps/web/components/task/chat/chat-input-area.tsx @@ -2,6 +2,7 @@ import { useCallback, useState } from "react"; import { IconBrain, IconGitMerge, IconX } from "@tabler/icons-react"; +import { TodoIndicator } from "./todo-indicator"; import { getWebSocketClient } from "@/lib/ws/connection"; import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"; import { SHORTCUTS } from "@/lib/keyboard/constants"; @@ -292,15 +293,32 @@ function PRMergedBanner({ taskId }: { taskId: string }) { ); } +type TodoDisplayItem = { + text: string; + done?: boolean; + status?: "pending" | "in_progress" | "completed" | "failed"; +}; + +function SessionStatusBar({ todoItems }: { todoItems: TodoDisplayItem[] }) { + const showTodos = todoItems.length > 0; + if (!showTodos) return null; + return ( +
+ +
+ ); +} + function AgentModeIndicator({ sessionId }: { sessionId: string | null }) { - const agentMode = useAppStore((state) => + const modeState = useAppStore((state) => sessionId ? state.sessionMode.bySessionId[sessionId] : undefined, ); - if (!agentMode || agentMode === "default") return null; + const modeId = modeState?.currentModeId; + if (!modeId || modeId === "default") return null; return (
- {agentMode} mode + {modeId} mode
); } @@ -374,6 +392,7 @@ export function ChatInputArea({ ); return (
+ {taskId && } diff --git a/apps/web/components/task/chat/chat-input-body.tsx b/apps/web/components/task/chat/chat-input-body.tsx index 12641ca95f..dec5b6ba25 100644 --- a/apps/web/components/task/chat/chat-input-body.tsx +++ b/apps/web/components/task/chat/chat-input-body.tsx @@ -1,18 +1,16 @@ "use client"; +import { useState, useCallback } from "react"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; import { cn } from "@/lib/utils"; import { TipTapInput } from "./tiptap-input"; import { ChatInputFocusHint } from "./chat-input-focus-hint"; import { ResizeHandle } from "./resize-handle"; -import { TodoSummary } from "./todo-summary"; import { ChatInputToolbar } from "./chat-input-toolbar"; import { ContextZone } from "./context-items/context-zone"; import type { ContextItem } from "@/lib/types/context"; import type { ContextFile } from "@/lib/state/context-files-store"; -type TodoItem = { text: string; done?: boolean }; - export type ChatInputEditorAreaProps = { inputRef: React.RefObject; value: string; @@ -32,7 +30,8 @@ export type ChatInputEditorAreaProps = { onToggleContextFile?: (file: ContextFile) => void; planContextEnabled: boolean; handleAgentCommand: (command: string) => void; - handleImagePaste: (files: File[]) => Promise; + addFiles: (files: File[]) => Promise; + fileInputRef: React.RefObject; showRequestChangesTooltip: boolean; hideSessionsDropdown?: boolean; isAgentBusy: boolean; @@ -50,71 +49,163 @@ export type ChatInputEditorAreaProps = { isEnhancingPrompt?: boolean; }; -export function ChatInputEditorArea({ inputRef, ...p }: ChatInputEditorAreaProps) { - const wrappedSubmit = p.isEnhancingPrompt ? () => {} : p.handleSubmitWithReset; - const inputDisabled = p.isDisabled || p.hasClarification; +function EditorWithTooltip({ + showTooltip, + isEnhancingPrompt, + children, +}: { + showTooltip: boolean; + isEnhancingPrompt?: boolean; + children: React.ReactNode; +}) { + return ( + + +
+ {children} +
+
+ +

Write your changes here

+
+
+ ); +} + +function FileInput({ + fileInputRef, + addFiles, +}: { + fileInputRef: React.RefObject; + addFiles: (files: File[]) => Promise; +}) { + const handleChange = useCallback( + (e: React.ChangeEvent) => { + const files = e.target.files; + if (files && files.length > 0) { + void addFiles(Array.from(files)); + } + // Reset so re-selecting the same file triggers onChange + e.target.value = ""; + }, + [addFiles], + ); + + return ( + + ); +} + +export function ChatInputEditorArea({ + inputRef, + value, + handleChange, + handleSubmitWithReset, + inputPlaceholder, + isDisabled, + hasClarification, + planModeEnabled, + planModeAvailable, + mcpServers, + submitKey, + setIsInputFocused, + sessionId, + taskId, + onAddContextFile, + onToggleContextFile, + planContextEnabled, + handleAgentCommand, + addFiles, + fileInputRef, + showRequestChangesTooltip, + isAgentBusy, + onPlanModeChange, + taskTitle, + taskDescription, + isSending, + onCancel, + contextCount, + contextPopoverOpen, + setContextPopoverOpen, + contextFiles, + onImplementPlan, + onEnhancePrompt, + isEnhancingPrompt, + hideSessionsDropdown, +}: ChatInputEditorAreaProps) { + // Block submit while enhancing prompt, but keep editor editable for programmatic updates + const wrappedSubmit = isEnhancingPrompt ? () => {} : handleSubmitWithReset; + + const handleAttachFiles = useCallback(() => { + fileInputRef.current?.click(); + }, [fileInputRef]); return (
- - -
- p.setIsInputFocused(true)} - onBlur={() => p.setIsInputFocused(false)} - sessionId={p.sessionId} - taskId={p.taskId} - onAddContextFile={p.onAddContextFile} - onToggleContextFile={p.onToggleContextFile} - planContextEnabled={p.planContextEnabled} - onAgentCommand={p.handleAgentCommand} - onImagePaste={p.handleImagePaste} - onPlanModeChange={p.onPlanModeChange} - /> -
-
- -

Write your changes here

-
-
+ + setIsInputFocused(true)} + onBlur={() => setIsInputFocused(false)} + sessionId={sessionId} + taskId={taskId} + onAddContextFile={onAddContextFile} + onToggleContextFile={onToggleContextFile} + planContextEnabled={planContextEnabled} + onAgentCommand={handleAgentCommand} + onImagePaste={addFiles} + onPlanModeChange={onPlanModeChange} + /> + +
); @@ -124,20 +215,15 @@ export type ChatInputContextAreaProps = { hasContextZone: boolean; allItems: ContextItem[]; sessionId: string | null; - hasTodos: boolean; - todoItems: TodoItem[]; }; export function ChatInputContextArea({ hasContextZone, allItems, sessionId, - hasTodos, - todoItems, }: ChatInputContextAreaProps) { if (!hasContextZone) return null; - const todoSlot = hasTodos ? : undefined; - return ; + return ; } export type ChatInputBodyProps = { @@ -152,6 +238,7 @@ export type ChatInputBodyProps = { planModeEnabled: boolean; showFocusHint: boolean; needsRecovery: boolean; + addFiles: (files: File[]) => Promise; contextAreaProps: ChatInputContextAreaProps; editorAreaProps: ChatInputEditorAreaProps; }; @@ -168,9 +255,54 @@ export function ChatInputBody({ planModeEnabled, showFocusHint, needsRecovery, + addFiles, contextAreaProps, editorAreaProps, }: ChatInputBodyProps) { + const [isDragging, setIsDragging] = useState(false); + + const handleDragOver = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + }, []); + + const handleDragEnter = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + if (e.dataTransfer.types.includes("Files")) { + setIsDragging(true); + } + }, []); + + const handleDragLeave = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + // Only set false when leaving the container (not entering a child) + const rect = e.currentTarget.getBoundingClientRect(); + const { clientX, clientY } = e; + if ( + clientX <= rect.left || + clientX >= rect.right || + clientY <= rect.top || + clientY >= rect.bottom + ) { + setIsDragging(false); + } + }, []); + + const handleDrop = useCallback( + (e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragging(false); + const files = Array.from(e.dataTransfer.files).filter((f) => f.size > 0 || f.type !== ""); + if (files.length > 0) { + void addFiles(files); + } + }, + [addFiles], + ); + return (
diff --git a/apps/web/components/task/chat/chat-input-container.tsx b/apps/web/components/task/chat/chat-input-container.tsx index e318eebb0a..e1771adfa7 100644 --- a/apps/web/components/task/chat/chat-input-container.tsx +++ b/apps/web/components/task/chat/chat-input-container.tsx @@ -22,9 +22,10 @@ export type { ImageAttachment } from "./image-attachment-preview"; // Type for message attachments sent to backend export type MessageAttachment = { - type: "image"; + type: "image" | "audio" | "resource"; data: string; mime_type: string; + name?: string; }; export type ChatInputContainerHandle = { @@ -36,8 +37,6 @@ export type ChatInputContainerHandle = { clear: () => void; }; -type TodoItem = { text: string; done?: boolean }; - type ChatInputContainerProps = { onSubmit: ( message: string, @@ -73,7 +72,6 @@ type ChatInputContainerProps = { contextFiles?: ContextFile[]; onToggleContextFile?: (file: ContextFile) => void; onAddContextFile?: (file: ContextFile) => void; - todoItems?: TodoItem[]; onImplementPlan?: () => void; hideSessionsDropdown?: boolean; }; @@ -135,8 +133,6 @@ function buildContextAreaProps( hasContextZone: s.hasContextZone, allItems: s.allItems, sessionId: p.sessionId, - hasTodos: s.hasTodos, - todoItems: p.todoItems ?? [], }; } @@ -169,7 +165,8 @@ function buildEditorAreaProps( onToggleContextFile: p.onToggleContextFile, planContextEnabled: p.planContextEnabled ?? false, handleAgentCommand: s.handleAgentCommand, - handleImagePaste: s.handleImagePaste, + addFiles: s.addFiles, + fileInputRef: s.fileInputRef, showRequestChangesTooltip: p.showRequestChangesTooltip ?? false, isAgentBusy: p.isAgentBusy, onPlanModeChange: p.onPlanModeChange, @@ -210,7 +207,6 @@ export const ChatInputContainer = forwardRef void; /** Whether prompt enhancement is in progress */ isEnhancingPrompt?: boolean; + /** Callback to open file picker for attaching files */ + onAttachFiles?: () => void; /** Hide the sessions dropdown (for quick chat) */ hideSessionsDropdown?: boolean; }; @@ -339,7 +344,10 @@ function ToolbarRightSection({ /> )} + + + {/* AuthMethodsIndicator hidden — UX needs rethinking */} {showEnhance && ( )} @@ -383,6 +391,7 @@ export const ChatInputToolbar = memo(function ChatInputToolbar({ onImplementPlan, onEnhancePrompt, isEnhancingPrompt = false, + onAttachFiles, hideSessionsDropdown, }: ChatInputToolbarProps) { const submitShortcut = submitKey === "enter" ? SHORTCUTS.SUBMIT_ENTER : SHORTCUTS.SUBMIT; @@ -398,6 +407,23 @@ export const ChatInputToolbar = memo(function ChatInputToolbar({ + {onAttachFiles && ( + + + + + Attach files + + )} + {})} diff --git a/apps/web/components/task/chat/context-items/context-chip.tsx b/apps/web/components/task/chat/context-items/context-chip.tsx index 29694a7897..3655b633ac 100644 --- a/apps/web/components/task/chat/context-items/context-chip.tsx +++ b/apps/web/components/task/chat/context-items/context-chip.tsx @@ -21,6 +21,7 @@ const ICON_BY_KIND: Record = { comment: IconMessageDots, "plan-comment": IconMessageDots, image: IconPhoto, + "file-attachment": IconFile, prompt: IconAt, "pr-feedback": IconGitPullRequest, }; diff --git a/apps/web/components/task/chat/context-items/context-item-renderer.tsx b/apps/web/components/task/chat/context-items/context-item-renderer.tsx index bf234634da..0105a7a53c 100644 --- a/apps/web/components/task/chat/context-items/context-item-renderer.tsx +++ b/apps/web/components/task/chat/context-items/context-item-renderer.tsx @@ -7,6 +7,7 @@ import { PromptItem } from "./prompt-item"; import { CommentItem } from "./comment-item"; import { PlanCommentItem } from "./plan-comment-item"; import { ImageItem } from "./image-item"; +import { FileAttachmentItem } from "./file-attachment-item"; import { PRFeedbackItem } from "./pr-feedback-item"; export function ContextItemRenderer({ @@ -29,6 +30,8 @@ export function ContextItemRenderer({ return ; case "image": return ; + case "file-attachment": + return ; case "pr-feedback": return ; } diff --git a/apps/web/components/task/chat/context-items/context-zone.tsx b/apps/web/components/task/chat/context-items/context-zone.tsx index 5f73cff1c1..af2e0d6c0d 100644 --- a/apps/web/components/task/chat/context-items/context-zone.tsx +++ b/apps/web/components/task/chat/context-items/context-zone.tsx @@ -1,30 +1,24 @@ "use client"; -import type { ReactNode } from "react"; import type { ContextItem } from "@/lib/types/context"; import { ContextItemRenderer } from "./context-item-renderer"; type ContextZoneProps = { items: ContextItem[]; sessionId?: string | null; - todoSlot?: ReactNode; }; -export function ContextZone({ items, sessionId, todoSlot }: ContextZoneProps) { - const hasContent = !!todoSlot || items.length > 0; - if (!hasContent) return null; +export function ContextZone({ items, sessionId }: ContextZoneProps) { + if (items.length === 0) return null; return (
- {todoSlot} - {items.length > 0 && ( -
- {items.map((item) => ( - - ))} -
- )} +
+ {items.map((item) => ( + + ))} +
); diff --git a/apps/web/components/task/chat/context-items/file-attachment-item.tsx b/apps/web/components/task/chat/context-items/file-attachment-item.tsx new file mode 100644 index 0000000000..17aee6776f --- /dev/null +++ b/apps/web/components/task/chat/context-items/file-attachment-item.tsx @@ -0,0 +1,20 @@ +"use client"; + +import { memo } from "react"; +import type { FileAttachmentContextItem } from "@/lib/types/context"; +import { formatBytes } from "../file-attachment"; +import { ContextChip } from "./context-chip"; + +export const FileAttachmentItem = memo(function FileAttachmentItem({ + item, +}: { + item: FileAttachmentContextItem; +}) { + const preview = ( +
+ {item.attachment.fileName} ({formatBytes(item.attachment.size)}) +
+ ); + + return ; +}); diff --git a/apps/web/components/task/chat/context-items/image-item.tsx b/apps/web/components/task/chat/context-items/image-item.tsx index f349cdf46e..68a62ba716 100644 --- a/apps/web/components/task/chat/context-items/image-item.tsx +++ b/apps/web/components/task/chat/context-items/image-item.tsx @@ -20,9 +20,6 @@ export const ImageItem = memo(function ImageItem({ item }: { item: ImageContextI alt="Preview" className="max-w-full max-h-48 rounded object-contain" /> -
- {item.attachment.width} × {item.attachment.height} -
); diff --git a/apps/web/components/task/chat/file-attachment-preview.tsx b/apps/web/components/task/chat/file-attachment-preview.tsx new file mode 100644 index 0000000000..491b679a71 --- /dev/null +++ b/apps/web/components/task/chat/file-attachment-preview.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { memo } from "react"; +import { IconFile, IconX } from "@tabler/icons-react"; +import { cn } from "@/lib/utils"; +import { formatBytes, type FileAttachment } from "./file-attachment"; + +type FileAttachmentPreviewProps = { + attachments: FileAttachment[]; + onRemove: (id: string) => void; + disabled?: boolean; +}; + +export const FileAttachmentPreview = memo(function FileAttachmentPreview({ + attachments, + onRemove, + disabled = false, +}: FileAttachmentPreviewProps) { + if (attachments.length === 0) return null; + + return ( +
+ {attachments.map((attachment) => ( +
+ {attachment.isImage && attachment.preview ? ( + /* eslint-disable-next-line @next/next/no-img-element -- base64/blob preview URLs are not compatible with next/image */ + Attachment preview + ) : ( +
+ +
+ + {attachment.fileName} + + + {formatBytes(attachment.size)} + +
+
+ )} + + {!disabled && ( + + )} +
+ ))} +
+ ); +}); diff --git a/apps/web/components/task/chat/file-attachment.ts b/apps/web/components/task/chat/file-attachment.ts new file mode 100644 index 0000000000..6b8e3095f1 --- /dev/null +++ b/apps/web/components/task/chat/file-attachment.ts @@ -0,0 +1,101 @@ +/** + * Unified file attachment type and processing utilities. + * Handles both images (with preview) and arbitrary files (code, docs, etc.). + */ + +export type FileAttachment = { + id: string; + data: string; // Base64-encoded content (without data: prefix) + mimeType: string; // MIME type + fileName: string; // Original file name + size: number; // File size in bytes + preview?: string; // Data URL for image preview (only for images) + isImage: boolean; // Whether this is a previewable image +}; + +export const PREVIEWABLE_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"]; + +export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB per file +export const MAX_TOTAL_SIZE = 20 * 1024 * 1024; // 20MB total +export const MAX_FILES = 10; + +export function formatBytes(bytes: number): string { + if (bytes === 0) return "0 B"; + const k = 1024; + const sizes = ["B", "KB", "MB", "GB"]; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`; +} + +function isPreviewableImage(mimeType: string): boolean { + return PREVIEWABLE_IMAGE_TYPES.includes(mimeType); +} + +/** + * Process a file into a FileAttachment. + * Images get a preview data URL; other files just get base64 data. + * Returns null if the file is invalid (too large, etc.) + */ +export function processFile(file: File): Promise { + return new Promise((resolve) => { + if (file.size > MAX_FILE_SIZE) { + console.warn( + `File too large: ${formatBytes(file.size)} (max: ${formatBytes(MAX_FILE_SIZE)})`, + ); + resolve(null); + return; + } + + // Skip directories and empty files + if (file.size === 0 && file.type === "") { + resolve(null); + return; + } + + const reader = new FileReader(); + reader.onload = (event) => { + const dataUrl = event.target?.result as string; + if (!dataUrl) { + resolve(null); + return; + } + + const base64 = dataUrl.split(",")[1]; + const mimeType = + file.type || dataUrl.split(";")[0].split(":")[1] || "application/octet-stream"; + const isImage = isPreviewableImage(mimeType); + + if (isImage) { + // For images, load to verify and generate preview + const img = new Image(); + img.onload = () => { + resolve({ + id: crypto.randomUUID(), + data: base64, + mimeType, + fileName: file.name, + size: file.size, + preview: dataUrl, + isImage: true, + }); + }; + img.onerror = () => resolve(null); + img.src = dataUrl; + } else { + resolve({ + id: crypto.randomUUID(), + data: base64, + mimeType, + fileName: file.name, + size: file.size, + isImage: false, + }); + } + }; + reader.onerror = () => { + console.error("Failed to read file:", file.name); + resolve(null); + }; + reader.readAsDataURL(file); + }); +} diff --git a/apps/web/components/task/chat/messages/chat-message.tsx b/apps/web/components/task/chat/messages/chat-message.tsx index 0e86e67c0c..3ecfd23974 100644 --- a/apps/web/components/task/chat/messages/chat-message.tsx +++ b/apps/web/components/task/chat/messages/chat-message.tsx @@ -99,7 +99,7 @@ type UserMessageProps = { }; type UserMessageMetadata = { - attachments?: Array<{ type: string; data: string; mime_type: string }>; + attachments?: Array<{ type: string; data: string; mime_type: string; name?: string }>; plan_mode?: boolean; has_review_comments?: boolean; has_hidden_prompts?: boolean; @@ -109,14 +109,16 @@ type UserMessageMetadata = { function parseUserMessageMetadata(comment: Message) { const metadata = comment.metadata as UserMessageMetadata | undefined; const imageAttachments = (metadata?.attachments || []).filter((att) => att.type === "image"); + const fileAttachments = (metadata?.attachments || []).filter((att) => att.type === "resource"); const contextFiles = metadata?.context_files || []; const hasPlanMode = !!metadata?.plan_mode; const hasReviewComments = !!metadata?.has_review_comments; const hasHiddenPrompts = !!metadata?.has_hidden_prompts; const hasContent = !!(comment.content && comment.content.trim() !== ""); - const hasAttachments = imageAttachments.length > 0; + const hasAttachments = imageAttachments.length > 0 || fileAttachments.length > 0; return { imageAttachments, + fileAttachments, contextFiles, hasPlanMode, hasReviewComments, @@ -179,6 +181,7 @@ function UserMessageContent({ const userNavigation = useMessageNavigation(allMessages || [], comment.id, "user"); const { imageAttachments, + fileAttachments, contextFiles, hasPlanMode, hasReviewComments, @@ -208,6 +211,15 @@ function UserMessageContent({ onClick={() => openImageInWindow(att.mime_type, att.data)} /> ))} + {fileAttachments.map((att, index) => ( + + + {att.name || "Attachment"} + + ))}
)} {renderUserMessageBody( diff --git a/apps/web/components/task/chat/messages/rich-blocks.tsx b/apps/web/components/task/chat/messages/rich-blocks.tsx index 156fae0e27..05af19e233 100644 --- a/apps/web/components/task/chat/messages/rich-blocks.tsx +++ b/apps/web/components/task/chat/messages/rich-blocks.tsx @@ -1,16 +1,10 @@ "use client"; -import { - IconBrain, - IconCode, - IconExternalLink, - IconListCheck, - IconPhoto, -} from "@tabler/icons-react"; -import { cn } from "@/lib/utils"; +import { IconBrain, IconCode, IconExternalLink, IconPhoto } from "@tabler/icons-react"; import type { Message } from "@/lib/types/http"; import type { ContentBlock, RichMetadata } from "@/components/task/chat/types"; import { DiffViewBlock } from "@/components/task/chat/messages/diff-view-block"; +import { TodoMessage } from "@/components/task/chat/messages/todo-message"; import { normalizeDiffString } from "@/lib/diff"; import type { FileDiffData } from "@/lib/diff/types"; @@ -79,10 +73,7 @@ export function RichBlocks({ comment }: { comment: Message }) { const metadata = comment.metadata as RichMetadata | undefined; if (!metadata) return null; - const todos = metadata.todos ?? []; - const todoItems = todos - .map((item) => (typeof item === "string" ? { text: item, done: false } : item)) - .filter((item) => item.text); + const hasTodos = (metadata.todos ?? []).length > 0; const diffData = resolveDiffPayload(metadata.diff); const diffText = typeof metadata.diff === "string" ? metadata.diff : null; const contentBlocks = (metadata.content_blocks ?? []).filter( @@ -100,27 +91,9 @@ export function RichBlocks({ comment }: { comment: Message }) {
{metadata.thinking}
)} - {todoItems.length > 0 && ( -
-
- - Todos -
-
- {todoItems.map((todo) => ( -
- - - {todo.text} - -
- ))} -
+ {hasTodos && ( +
+
)} {diffData && } diff --git a/apps/web/components/task/chat/messages/todo-message.tsx b/apps/web/components/task/chat/messages/todo-message.tsx index 6d1892f50c..62067cc57f 100644 --- a/apps/web/components/task/chat/messages/todo-message.tsx +++ b/apps/web/components/task/chat/messages/todo-message.tsx @@ -1,59 +1,73 @@ "use client"; +import { useState } from "react"; import { IconListCheck } from "@tabler/icons-react"; import { cn } from "@/lib/utils"; import type { Message } from "@/lib/types/http"; import type { RichMetadata } from "@/components/task/chat/types"; +import { ExpandableRow } from "./expandable-row"; +import { StatusIcon, resolveStatus } from "../todo-indicator"; -export function TodoMessage({ comment }: { comment: Message }) { +type TodoItem = { + text: string; + done?: boolean; + status?: "pending" | "in_progress" | "completed" | "failed"; +}; + +function parseTodos(comment: Message): TodoItem[] { const metadata = comment.metadata as RichMetadata | undefined; const todos = metadata?.todos ?? []; - const todoItems = todos + return todos .map((item) => (typeof item === "string" ? { text: item, done: false } : item)) .filter((item) => item.text); +} - if (!todoItems.length) { - return null; - } +export function TodoMessage({ + comment, + defaultExpanded = false, +}: { + comment: Message; + defaultExpanded?: boolean; +}) { + const todoItems = parseTodos(comment); + const [isExpanded, setIsExpanded] = useState(defaultExpanded); - const completed = todoItems.filter((todo) => todo.done).length; - const progress = Math.round((completed / todoItems.length) * 100); + if (!todoItems.length) return null; + + const completed = todoItems.filter((t) => resolveStatus(t) === "completed").length; return ( -
-
- - Todos -
-
-
- - {completed} of {todoItems.length} done - - {progress}% -
-
-
-
-
-
- {todoItems.map((todo) => ( -
- - - {todo.text} +
+ } + header={ +
+ + Updated Todos + + + {completed}/{todoItems.length}
- ))} -
+ } + hasExpandableContent={todoItems.length > 0} + isExpanded={isExpanded} + onToggle={() => setIsExpanded((prev) => !prev)} + > +
+ {todoItems.map((todo, idx) => { + const s = resolveStatus(todo); + return ( +
+ + + {todo.text} + +
+ ); + })} +
+
); } diff --git a/apps/web/components/task/chat/tiptap-helpers.ts b/apps/web/components/task/chat/tiptap-helpers.ts index e8ecd27f7b..352a3620a9 100644 --- a/apps/web/components/task/chat/tiptap-helpers.ts +++ b/apps/web/components/task/chat/tiptap-helpers.ts @@ -120,10 +120,10 @@ export function parseCodeFences(text: string): FenceSegment[] { // ── Paste handler ─────────────────────────────────────────────────── -function extractImageFiles(items: DataTransferItemList): File[] { +function extractFiles(items: DataTransferItemList): File[] { const files: File[] = []; for (const item of items) { - if (item.type.startsWith("image/")) { + if (item.kind === "file") { const file = item.getAsFile(); if (file) files.push(file); } @@ -167,13 +167,13 @@ export function handleEditorPaste( event: ClipboardEvent, onImagePasteRef: React.RefObject<((files: File[]) => void) | undefined>, ): boolean { - // 1. Image paste + // 1. File paste (images and other files) const items = event.clipboardData?.items; if (items) { - const imageFiles = extractImageFiles(items); - if (imageFiles.length > 0) { + const files = extractFiles(items); + if (files.length > 0) { event.preventDefault(); - onImagePasteRef.current?.(imageFiles); + onImagePasteRef.current?.(files); return true; } } diff --git a/apps/web/components/task/chat/todo-indicator.tsx b/apps/web/components/task/chat/todo-indicator.tsx new file mode 100644 index 0000000000..1d51d269c2 --- /dev/null +++ b/apps/web/components/task/chat/todo-indicator.tsx @@ -0,0 +1,92 @@ +"use client"; + +import { IconCheck, IconCircle, IconCircleFilled, IconListCheck, IconX } from "@tabler/icons-react"; +import { HoverCard, HoverCardTrigger, HoverCardContent } from "@kandev/ui/hover-card"; +import { cn } from "@/lib/utils"; + +type TodoDisplayItem = { + text: string; + done?: boolean; + status?: "pending" | "in_progress" | "completed" | "failed"; +}; + +type TodoIndicatorProps = { + todos: TodoDisplayItem[]; +}; + +function resolveStatus(todo: TodoDisplayItem): "pending" | "in_progress" | "completed" | "failed" { + if (todo.status) return todo.status; + return todo.done ? "completed" : "pending"; +} + +function StatusIcon({ status, className }: { status: string; className?: string }) { + switch (status) { + case "completed": + return ; + case "in_progress": + return ; + case "failed": + return ; + default: + return ; + } +} + +export function TodoIndicator({ todos }: TodoIndicatorProps) { + if (!todos.length) return null; + + const completed = todos.filter((t) => resolveStatus(t) === "completed").length; + const allComplete = completed === todos.length; + const progress = Math.round((completed / todos.length) * 100); + + return ( + + + + + +
+ Todos + + {completed}/{todos.length} completed + +
+
+
+
+
+ {todos.map((todo, idx) => { + const s = resolveStatus(todo); + return ( +
+ + + {todo.text} + +
+ ); + })} +
+ + + ); +} + +export { StatusIcon, resolveStatus }; +export type { TodoDisplayItem }; diff --git a/apps/web/components/task/chat/todo-summary.tsx b/apps/web/components/task/chat/todo-summary.tsx deleted file mode 100644 index 8c3698f56b..0000000000 --- a/apps/web/components/task/chat/todo-summary.tsx +++ /dev/null @@ -1,45 +0,0 @@ -"use client"; - -import { IconCheck, IconChevronDown } from "@tabler/icons-react"; -import { cn } from "@/lib/utils"; - -type TodoItem = { - text: string; - done?: boolean; -}; - -type TodoSummaryProps = { - todos: TodoItem[]; -}; - -export function TodoSummary({ todos }: TodoSummaryProps) { - if (!todos.length) return null; - - const completed = todos.filter((todo) => todo.done).length; - - return ( -
-
- Todos ({todos.length}) - -
-
- {todos.map((todo) => ( -
- {todo.done ? ( - - ) : ( - - )} - - {todo.text} - -
- ))} -
-
- {completed} of {todos.length} completed -
-
- ); -} diff --git a/apps/web/components/task/chat/use-chat-input-container.ts b/apps/web/components/task/chat/use-chat-input-container.ts index b9df9c4d88..d4309a89c6 100644 --- a/apps/web/components/task/chat/use-chat-input-container.ts +++ b/apps/web/components/task/chat/use-chat-input-container.ts @@ -26,7 +26,6 @@ type UseChatInputContainerParams = { onClarificationResolved: (() => void) | undefined; pendingCommentsByFile: Record | undefined; hasContextComments: boolean; - todoItems: { text: string; done?: boolean }[]; showRequestChangesTooltip: boolean; onRequestChangesTooltipDismiss: (() => void) | undefined; onSubmit: ( @@ -78,7 +77,6 @@ function computeDerivedState(params: { pendingClarification: Message | null | undefined; onClarificationResolved: (() => void) | undefined; pendingCommentsByFile: Record | undefined; - todoItems: { text: string }[]; allItemsLength: number; isInputFocused: boolean; placeholder: string | undefined; @@ -91,8 +89,7 @@ function computeDerivedState(params: { const hasPendingComments = !!( params.pendingCommentsByFile && Object.keys(params.pendingCommentsByFile).length > 0 ); - const hasTodos = params.todoItems.length > 0; - const hasContextZone = hasTodos || params.allItemsLength > 0; + const hasContextZone = params.allItemsLength > 0; const showFocusHint = !params.isInputFocused && !hasClarification && !hasPendingComments; const inputPlaceholder = getInputPlaceholder( params.placeholder, @@ -104,7 +101,6 @@ function computeDerivedState(params: { isDisabled, hasClarification, hasPendingComments, - hasTodos, hasContextZone, showFocusHint, inputPlaceholder, @@ -126,7 +122,6 @@ export function useChatInputContainer(params: UseChatInputContainerParams) { pendingClarification, onClarificationResolved, pendingCommentsByFile, - todoItems, showRequestChangesTooltip, onRequestChangesTooltipDismiss, onSubmit, @@ -142,17 +137,17 @@ export function useChatInputContainer(params: UseChatInputContainerParams) { sessionId ?? undefined, getContentElement, ); - const { value, inputRef, handleImagePaste, handleChange, handleSubmit, allItems } = - useChatInputState({ - sessionId, - isSending, - contextItems, - pendingCommentsByFile, - hasContextComments: params.hasContextComments, - showRequestChangesTooltip, - onRequestChangesTooltipDismiss, - onSubmit, - }); + const fileInputRef = useRef(null); + const { value, inputRef, addFiles, handleChange, handleSubmit, allItems } = useChatInputState({ + sessionId, + isSending, + contextItems, + pendingCommentsByFile, + hasContextComments: params.hasContextComments, + showRequestChangesTooltip, + onRequestChangesTooltipDismiss, + onSubmit, + }); useEffect(() => { tiptapRef.current = inputRef.current; @@ -192,7 +187,6 @@ export function useChatInputContainer(params: UseChatInputContainerParams) { pendingClarification, onClarificationResolved, pendingCommentsByFile, - todoItems, allItemsLength: allItems.length, isInputFocused, placeholder, @@ -212,7 +206,8 @@ export function useChatInputContainer(params: UseChatInputContainerParams) { resizeHandleProps, value, inputRef, - handleImagePaste, + addFiles, + fileInputRef, handleChange: handleChangeWithAutoExpand, handleSubmitWithReset, handleAgentCommand, diff --git a/apps/web/components/task/chat/use-chat-input-state.ts b/apps/web/components/task/chat/use-chat-input-state.ts index 92d6d01435..f7082be03f 100644 --- a/apps/web/components/task/chat/use-chat-input-state.ts +++ b/apps/web/components/task/chat/use-chat-input-state.ts @@ -8,13 +8,13 @@ import { restoreAttachmentPreview, } from "@/lib/local-storage"; import { - processImageFile, + processFile, formatBytes, - MAX_IMAGES, + MAX_FILES, MAX_TOTAL_SIZE, - type ImageAttachment, -} from "./image-attachment-preview"; -import type { ContextItem, ImageContextItem } from "@/lib/types/context"; + type FileAttachment, +} from "./file-attachment"; +import type { ContextItem, ImageContextItem, FileAttachmentContextItem } from "@/lib/types/context"; import type { ContextFile } from "@/lib/state/context-files-store"; import type { DiffComment } from "@/lib/diff/types"; import type { MessageAttachment } from "./chat-input-container"; @@ -47,12 +47,12 @@ function collectComments( return allComments; } -function toMessageAttachments(attachments: ImageAttachment[]): MessageAttachment[] { - return attachments.map((att) => ({ - type: "image" as const, - data: att.data, - mime_type: att.mimeType, - })); +function toMessageAttachments(attachments: FileAttachment[]): MessageAttachment[] { + return attachments.map((att) => + att.isImage + ? { type: "image" as const, data: att.data, mime_type: att.mimeType } + : { type: "resource" as const, data: att.data, mime_type: att.mimeType, name: att.fileName }, + ); } function clearDraft(sessionId: string | null) { @@ -63,7 +63,7 @@ function clearDraft(sessionId: string | null) { } function useAttachments(sessionId: string | null) { - const [attachments, setAttachments] = useState(() => + const [attachments, setAttachments] = useState(() => sessionId ? getChatDraftAttachments(sessionId).map(restoreAttachmentPreview) : [], ); const attachmentsRef = useRef(attachments); @@ -75,20 +75,20 @@ function useAttachments(sessionId: string | null) { setChatDraftAttachments(sessionId, attachments); }, [attachments, sessionId]); - const handleImagePaste = useCallback( + const addFiles = useCallback( async (files: File[]) => { - if (attachments.length >= MAX_IMAGES) { - console.warn(`Maximum ${MAX_IMAGES} images allowed`); + if (attachments.length >= MAX_FILES) { + console.warn(`Maximum ${MAX_FILES} files allowed`); return; } const currentTotalSize = attachments.reduce((sum, att) => sum + att.size, 0); for (const file of files) { - if (attachments.length >= MAX_IMAGES) break; + if (attachments.length >= MAX_FILES) break; if (currentTotalSize + file.size > MAX_TOTAL_SIZE) { console.warn("Total attachment size limit exceeded"); break; } - const attachment = await processImageFile(file); + const attachment = await processFile(file); if (attachment) setAttachments((prev) => [...prev, attachment]); } }, @@ -104,7 +104,7 @@ function useAttachments(sessionId: string | null) { attachmentsRef, prevSessionIdRef, setAttachments, - handleImagePaste, + addFiles, handleRemoveAttachment, }; } @@ -130,7 +130,7 @@ export function useChatInputState({ attachmentsRef, prevSessionIdRef, setAttachments, - handleImagePaste, + addFiles, handleRemoveAttachment, } = useAttachments(sessionId); @@ -188,15 +188,26 @@ export function useChatInputState({ ); const allItems = useMemo((): ContextItem[] => { - const imageItems: ImageContextItem[] = attachments.map((att) => ({ - kind: "image" as const, - id: `image:${att.id}`, - label: `Image (${formatBytes(att.size)})`, - attachment: att, - onRemove: () => handleRemoveAttachment(att.id), - })); - return [...contextItems, ...imageItems]; + const attachmentItems: (ImageContextItem | FileAttachmentContextItem)[] = attachments.map( + (att) => + att.isImage + ? ({ + kind: "image" as const, + id: `image:${att.id}`, + label: `Image (${formatBytes(att.size)})`, + attachment: att, + onRemove: () => handleRemoveAttachment(att.id), + } as ImageContextItem) + : ({ + kind: "file-attachment" as const, + id: `file:${att.id}`, + label: att.fileName, + attachment: att, + onRemove: () => handleRemoveAttachment(att.id), + } as FileAttachmentContextItem), + ); + return [...contextItems, ...attachmentItems]; }, [contextItems, attachments, handleRemoveAttachment]); - return { value, attachments, inputRef, handleImagePaste, handleChange, handleSubmit, allItems }; + return { value, attachments, inputRef, addFiles, handleChange, handleSubmit, allItems }; } diff --git a/apps/web/components/task/chat/use-chat-panel-state.ts b/apps/web/components/task/chat/use-chat-panel-state.ts index 1e30285246..1c8f3e20ce 100644 --- a/apps/web/components/task/chat/use-chat-panel-state.ts +++ b/apps/web/components/task/chat/use-chat-panel-state.ts @@ -422,6 +422,27 @@ function useSessionData( }; } +type TodoStatus = "pending" | "in_progress" | "completed" | "failed"; + +function useSessionTodoItems( + resolvedSessionId: string | null, + messageTodos: Array<{ text: string; done?: boolean }>, +) { + const storeTodos = useAppStore((s) => + resolvedSessionId ? s.sessionTodos.bySessionId[resolvedSessionId] : undefined, + ); + return useMemo(() => { + if (storeTodos && storeTodos.length > 0) { + return storeTodos.map((e: { description: string; status: string }) => ({ + text: e.description, + done: e.status === "completed", + status: e.status as TodoStatus, + })); + } + return messageTodos; + }, [storeTodos, messageTodos]); +} + export type UseChatPanelStateOptions = { sessionId: string | null; onOpenFile?: (path: string) => void; @@ -515,6 +536,8 @@ export function useChatPanelState({ onOpenFileAtLine, }); + const todoItems = useSessionTodoItems(resolvedSessionId, sessionData.todoItems); + return { ...sessionState, ...planMode, @@ -527,5 +550,6 @@ export function useChatPanelState({ planModeAvailable, mcpServers, prompts, + todoItems, }; } diff --git a/apps/web/components/task/config-options-display.tsx b/apps/web/components/task/config-options-display.tsx new file mode 100644 index 0000000000..e270f91a4c --- /dev/null +++ b/apps/web/components/task/config-options-display.tsx @@ -0,0 +1,49 @@ +"use client"; + +import { memo } from "react"; +import { IconSettings } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover"; +import { useAppStore } from "@/components/state-provider"; + +type ConfigOptionsDisplayProps = { + sessionId: string | null; +}; + +export const ConfigOptionsDisplay = memo(function ConfigOptionsDisplay({ + sessionId, +}: ConfigOptionsDisplayProps) { + const configOptions = useAppStore((state) => { + if (!sessionId) return undefined; + return state.sessionModels.bySessionId[sessionId]?.configOptions; + }); + + if (!sessionId || !configOptions || configOptions.length === 0) { + return null; + } + + return ( + + + + + +
+
Config Options
+ {configOptions.map((option) => ( +
+ {option.name} + {option.currentValue} +
+ ))} +
+
+
+ ); +}); diff --git a/apps/web/components/task/dockview-header-actions.tsx b/apps/web/components/task/dockview-header-actions.tsx index c403e94d67..3c223d1ed2 100644 --- a/apps/web/components/task/dockview-header-actions.tsx +++ b/apps/web/components/task/dockview-header-actions.tsx @@ -349,16 +349,16 @@ function RightTopGroupActions() { function SessionModeBadge() { const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); - const modeId = useAppStore((state) => { + const modeState = useAppStore((state) => { if (!activeSessionId) return null; return state.sessionMode.bySessionId[activeSessionId] ?? null; }); - if (!modeId) return null; + if (!modeState?.currentModeId) return null; return ( - {modeId} + {modeState.currentModeId} ); } diff --git a/apps/web/components/task/mode-selector.tsx b/apps/web/components/task/mode-selector.tsx new file mode 100644 index 0000000000..fd0a976233 --- /dev/null +++ b/apps/web/components/task/mode-selector.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { memo, useCallback } from "react"; +import { IconChevronDown } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@kandev/ui/dropdown-menu"; +import { useAppStore } from "@/components/state-provider"; +import { setSessionMode } from "@/lib/api/domains/session-api"; + +type ModeSelectorProps = { + sessionId: string | null; +}; + +export const ModeSelector = memo(function ModeSelector({ sessionId }: ModeSelectorProps) { + const modeState = useAppStore((state) => + sessionId ? state.sessionMode.bySessionId[sessionId] : undefined, + ); + + const handleModeChange = useCallback( + async (modeId: string) => { + if (!sessionId) return; + try { + await setSessionMode(sessionId, modeId); + } catch (err) { + console.error("[ModeSelector] set-mode API failed:", err); + } + }, + [sessionId], + ); + + if ( + !sessionId || + !modeState || + !modeState.availableModes || + modeState.availableModes.length <= 1 + ) { + return null; + } + + const currentMode = modeState.availableModes.find((m) => m.id === modeState.currentModeId); + const displayName = currentMode?.name || modeState.currentModeId || "Mode"; + + return ( + + + + + + {modeState.availableModes.map((mode) => ( + handleModeChange(mode.id)} + className={mode.id === modeState.currentModeId ? "bg-muted" : ""} + > +
+
{mode.name}
+ {mode.description && ( +
{mode.description}
+ )} +
+
+ ))} +
+
+ ); +}); diff --git a/apps/web/components/task/model-selector.tsx b/apps/web/components/task/model-selector.tsx index 25c323ddc5..44b16a4306 100644 --- a/apps/web/components/task/model-selector.tsx +++ b/apps/web/components/task/model-selector.tsx @@ -1,18 +1,13 @@ "use client"; -import { memo } from "react"; -import { IconChevronDown } from "@tabler/icons-react"; -import { Button } from "@kandev/ui/button"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@kandev/ui/dropdown-menu"; +import { memo, useCallback, useMemo } from "react"; import { useAppStore } from "@/components/state-provider"; +import { Combobox, type ComboboxOption } from "@/components/combobox"; import { useAvailableAgents } from "@/hooks/domains/settings/use-available-agents"; import { useSettingsData } from "@/hooks/domains/settings/use-settings-data"; import type { Agent, AgentProfile, AvailableAgent } from "@/lib/types/http"; +import { setSessionModel } from "@/lib/api/domains/session-api"; +import type { SessionModelEntry } from "@/lib/state/slices/session-runtime/types"; type ModelSelectorProps = { sessionId: string | null; @@ -24,6 +19,8 @@ type ModelOption = { provider: string; context_window: number; is_default: boolean; + description?: string; + usageMultiplier?: string; }; function resolveSnapshotModel(snapshot: unknown): string | null { @@ -32,7 +29,7 @@ function resolveSnapshotModel(snapshot: unknown): string | null { return typeof model === "string" && model ? model : null; } -function resolveAvailableModels( +function resolveStaticModels( agents: Agent[], profileId: string | null | undefined, availableAgents: AvailableAgent[], @@ -42,11 +39,28 @@ function resolveAvailableModels( const profile = agent.profiles.find((p: AgentProfile) => p.id === profileId); if (!profile) continue; const available = availableAgents.find((a: AvailableAgent) => a.name === agent.name); - return available?.model_config?.available_models ?? []; + const models = available?.model_config?.available_models ?? []; + // Static models don't include description — use model ID as subtitle when it differs from name + return models.map((m) => ({ + ...m, + description: m.id !== m.name ? m.id : undefined, + })); } return []; } +function sessionModelsToOptions(models: SessionModelEntry[]): ModelOption[] { + return models.map((m) => ({ + id: m.modelId, + name: m.name, + provider: "", + context_window: 0, + is_default: false, + description: m.description, + usageMultiplier: m.usageMultiplier, + })); +} + function buildModelOptions( availableModels: ModelOption[], currentModel: string | null, @@ -64,7 +78,8 @@ function buildModelOptions( return options; } -export const ModelSelector = memo(function ModelSelector({ sessionId }: ModelSelectorProps) { +/** Resolves available models and current model from store state. */ +function useModelSelectorState(sessionId: string | null) { useSettingsData(true); const settingsAgents = useAppStore((state) => state.settingsAgents.items); @@ -72,50 +87,89 @@ export const ModelSelector = memo(function ModelSelector({ sessionId }: ModelSel const activeModels = useAppStore((state) => state.activeModel.bySessionId); const setActiveModel = useAppStore((state) => state.setActiveModel); const { items: availableAgents } = useAvailableAgents(); + const sessionModelsData = useAppStore((state) => + sessionId ? state.sessionModels.bySessionId[sessionId] : undefined, + ); const session = sessionId ? (taskSessions[sessionId] ?? null) : null; const snapshotModel = resolveSnapshotModel(session?.agent_profile_snapshot); - const availableModels = resolveAvailableModels( - settingsAgents as Agent[], - session?.agent_profile_id, - availableAgents, - ); + + // Prefer dynamic ACP session models when available, fall back to static registry models + const availableModels = sessionModelsData?.models?.length + ? sessionModelsToOptions(sessionModelsData.models) + : resolveStaticModels(settingsAgents as Agent[], session?.agent_profile_id, availableAgents); + const activeModel = sessionId ? activeModels[sessionId] || null : null; - const currentModel = activeModel || snapshotModel; + const acpCurrentModel = sessionModelsData?.currentModelId || null; + const currentModel = activeModel || acpCurrentModel || snapshotModel; const modelOptions = buildModelOptions(availableModels, currentModel); - const handleModelChange = (modelId: string) => { - if (!sessionId) return; - setActiveModel(sessionId, modelId); + const handleModelChange = useCallback( + (sid: string, modelId: string) => { + setActiveModel(sid, modelId); + setSessionModel(sid, modelId).catch((err) => { + console.error("[ModelSelector] set-model API failed:", err); + }); + }, + [setActiveModel], + ); + + return { currentModel, modelOptions, handleModelChange }; +} + +function modelToComboboxOption(model: ModelOption): ComboboxOption { + return { + value: model.id, + label: model.name, + description: model.description, + renderLabel: () => ( + <> +
+
{model.name}
+ {model.description && ( +
+ {model.description} +
+ )} +
+ {model.usageMultiplier && ( + {model.usageMultiplier} + )} + + ), }; +} + +export const ModelSelector = memo(function ModelSelector({ sessionId }: ModelSelectorProps) { + const { currentModel, modelOptions, handleModelChange } = useModelSelectorState(sessionId); + + const comboboxOptions = useMemo(() => modelOptions.map(modelToComboboxOption), [modelOptions]); + + const onValueChange = useCallback( + (value: string) => { + // Don't allow deselecting — always keep a model selected + if (!value || !sessionId) return; + handleModelChange(sessionId, value); + }, + [sessionId, handleModelChange], + ); if (!sessionId || !currentModel) return null; - const displayName = modelOptions.find((m) => m.id === currentModel)?.name || currentModel; - return ( - - - - - - {modelOptions.map((model) => ( - handleModelChange(model.id)} - className={model.id === currentModel ? "bg-accent" : ""} - > - {model.name} - - ))} - - + 5} + triggerClassName="h-7 gap-1 px-2 text-xs w-auto hover:bg-muted/40 whitespace-nowrap" + className="min-w-[280px]" + plainTrigger + popoverSide="top" + popoverAlign="end" + /> ); }); diff --git a/apps/web/hooks/use-message-handler.ts b/apps/web/hooks/use-message-handler.ts index 4499eaf6ec..78a60ec744 100644 --- a/apps/web/hooks/use-message-handler.ts +++ b/apps/web/hooks/use-message-handler.ts @@ -172,6 +172,7 @@ export function useMessageHandler({ type: att.type, data: att.data, mime_type: att.mime_type, + name: att.name, })); await queue(taskId, finalMessage, modelToSend, planModeEnabled, queueAttachments); return; diff --git a/apps/web/lib/api/domains/session-api.ts b/apps/web/lib/api/domains/session-api.ts index 4d5a6e66fa..7e6329cbbc 100644 --- a/apps/web/lib/api/domains/session-api.ts +++ b/apps/web/lib/api/domains/session-api.ts @@ -58,6 +58,24 @@ export async function openSessionFolder(sessionId: string, options?: ApiRequestO }); } +export async function setSessionMode(sessionId: string, modeId: string) { + return fetchJson<{ ok: boolean }>(`/api/v1/task-sessions/${sessionId}/set-mode`, { + init: { method: "POST", body: JSON.stringify({ mode_id: modeId }) }, + }); +} + +export async function setSessionModel(sessionId: string, modelId: string) { + return fetchJson<{ ok: boolean }>(`/api/v1/task-sessions/${sessionId}/set-model`, { + init: { method: "POST", body: JSON.stringify({ model_id: modelId }) }, + }); +} + +export async function authenticateSession(sessionId: string, methodId: string) { + return fetchJson<{ ok: boolean }>(`/api/v1/task-sessions/${sessionId}/authenticate`, { + init: { method: "POST", body: JSON.stringify({ method_id: methodId }) }, + }); +} + export { launchSession, type LaunchSessionResponse } from "@/lib/services/session-launch-service"; export { buildPRPrepareRequest, diff --git a/apps/web/lib/local-storage.ts b/apps/web/lib/local-storage.ts index 5f343fe735..2d19c0519f 100644 --- a/apps/web/lib/local-storage.ts +++ b/apps/web/lib/local-storage.ts @@ -490,14 +490,14 @@ const CHAT_DRAFT_CONTENT_KEY = "kandev.chatDraft.content"; const CHAT_DRAFT_ATTACHMENTS_KEY = "kandev.chatDraft.attachments"; const CHAT_INPUT_HEIGHT_KEY = "kandev.chatInput.height"; -/** Stored attachment — same as ImageAttachment but without `preview` (reconstructed on load) */ -type StoredImageAttachment = { +/** Stored attachment — same as FileAttachment but without `preview` (reconstructed on load) */ +type StoredFileAttachment = { id: string; data: string; mimeType: string; + fileName: string; size: number; - width: number; - height: number; + isImage: boolean; }; export function getChatDraftText(sessionId: string): string { @@ -525,8 +525,8 @@ export function setChatDraftContent(sessionId: string, content: unknown): void { } } -export function getChatDraftAttachments(sessionId: string): StoredImageAttachment[] { - return getSessionStorage( +export function getChatDraftAttachments(sessionId: string): StoredFileAttachment[] { + return getSessionStorage( `${CHAT_DRAFT_ATTACHMENTS_KEY}.${sessionId}`, [], ); @@ -538,24 +538,24 @@ export function setChatDraftAttachments( id: string; data: string; mimeType: string; + fileName: string; size: number; - width: number; - height: number; + isImage: boolean; preview?: string; }>, ): void { if (attachments.length === 0) { removeSessionStorage(`${CHAT_DRAFT_ATTACHMENTS_KEY}.${sessionId}`); } else { - // Strip `preview` to halve storage cost — reconstructed on load - const stored: StoredImageAttachment[] = attachments.map( - ({ id, data, mimeType, size, width, height }) => ({ + // Strip `preview` to halve storage cost — reconstructed on load for images + const stored: StoredFileAttachment[] = attachments.map( + ({ id, data, mimeType, fileName, size, isImage }) => ({ id, data, mimeType, + fileName, size, - width, - height, + isImage, }), ); setSessionStorage(`${CHAT_DRAFT_ATTACHMENTS_KEY}.${sessionId}`, stored); @@ -563,12 +563,15 @@ export function setChatDraftAttachments( } /** - * Reconstruct the `preview` data URL from stored attachment data. + * Reconstruct the `preview` data URL from stored attachment data (images only). */ export function restoreAttachmentPreview( - att: StoredImageAttachment, -): StoredImageAttachment & { preview: string } { - return { ...att, preview: `data:${att.mimeType};base64,${att.data}` }; + att: StoredFileAttachment, +): StoredFileAttachment & { preview?: string } { + if (att.isImage) { + return { ...att, preview: `data:${att.mimeType};base64,${att.data}` }; + } + return att; } export function getChatInputHeight(sessionId: string): number | null { diff --git a/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts b/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts index a6f8ae5ce2..5e4ba6ef6c 100644 --- a/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts +++ b/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts @@ -82,6 +82,10 @@ export const defaultSessionRuntimeState: SessionRuntimeSliceState = { agents: { agents: [] }, availableCommands: { bySessionId: {} }, sessionMode: { bySessionId: {} }, + agentCapabilities: { bySessionId: {} }, + sessionModels: { bySessionId: {} }, + promptUsage: { bySessionId: {} }, + sessionTodos: { bySessionId: {} }, userShells: { bySessionId: {}, loading: {}, loaded: {} }, prepareProgress: { bySessionId: {} }, }; @@ -228,13 +232,33 @@ export const createSessionRuntimeSlice: StateCreator< set((draft) => { delete draft.availableCommands.bySessionId[sessionId]; }), - setSessionMode: (sessionId, modeId) => + setSessionMode: (sessionId, modeId, availableModes) => set((draft) => { - draft.sessionMode.bySessionId[sessionId] = modeId; + const existing = draft.sessionMode.bySessionId[sessionId]; + draft.sessionMode.bySessionId[sessionId] = { + currentModeId: modeId, + availableModes: availableModes ?? existing?.availableModes ?? [], + }; }), clearSessionMode: (sessionId) => set((draft) => { delete draft.sessionMode.bySessionId[sessionId]; }), + setAgentCapabilities: (sessionId, caps) => + set((draft) => { + draft.agentCapabilities.bySessionId[sessionId] = caps; + }), + setSessionModels: (sessionId, data) => + set((draft) => { + draft.sessionModels.bySessionId[sessionId] = data; + }), + setPromptUsage: (sessionId, usage) => + set((draft) => { + draft.promptUsage.bySessionId[sessionId] = usage; + }), + setSessionTodos: (sessionId, entries) => + set((draft) => { + draft.sessionTodos.bySessionId[sessionId] = entries; + }), ...buildUserShellActions(set), }); diff --git a/apps/web/lib/state/slices/session-runtime/types.ts b/apps/web/lib/state/slices/session-runtime/types.ts index ed0684013b..3a4c41477b 100644 --- a/apps/web/lib/state/slices/session-runtime/types.ts +++ b/apps/web/lib/state/slices/session-runtime/types.ts @@ -123,8 +123,79 @@ export type AvailableCommandsState = { bySessionId: Record; }; +export type SessionModeEntry = { + id: string; + name: string; + description?: string; +}; + export type SessionModeState = { - bySessionId: Record; + bySessionId: Record< + string, + { + currentModeId: string; + availableModes: SessionModeEntry[]; + } + >; +}; + +export type AuthMethodEntry = { + id: string; + name: string; + description?: string; + terminalAuth?: { command: string; args?: string[]; label?: string }; + meta?: Record; +}; + +export type SessionModelEntry = { + modelId: string; + name: string; + description?: string; + usageMultiplier?: string; + meta?: Record; +}; + +export type ConfigOptionEntry = { + type: string; + id: string; + name: string; + currentValue: string; + category?: string; + options?: { value: string; name: string }[]; +}; + +export type AgentCapabilitiesEntry = { + supportsImage: boolean; + supportsAudio: boolean; + supportsEmbeddedContext: boolean; + authMethods: AuthMethodEntry[]; +}; + +export type PromptUsageEntry = { + inputTokens: number; + outputTokens: number; + cachedReadTokens?: number; + cachedWriteTokens?: number; + totalTokens: number; +}; + +export type AgentCapabilitiesState = { + bySessionId: Record; +}; + +export type SessionModelsState = { + bySessionId: Record< + string, + { + currentModelId: string; + models: SessionModelEntry[]; + configOptions: ConfigOptionEntry[]; + } + >; +}; + +export type PromptUsageState = { + bySessionId: Record; }; export type UserShellInfo = { @@ -163,6 +234,16 @@ export type PrepareProgressState = { bySessionId: Record; }; +export type TodoEntry = { + description: string; + status: "pending" | "in_progress" | "completed" | "failed"; + priority?: string; +}; + +export type SessionTodosState = { + bySessionId: Record; +}; + export type SessionRuntimeSliceState = { terminal: TerminalState; shell: ShellState; @@ -173,6 +254,10 @@ export type SessionRuntimeSliceState = { agents: AgentState; availableCommands: AvailableCommandsState; sessionMode: SessionModeState; + agentCapabilities: AgentCapabilitiesState; + sessionModels: SessionModelsState; + promptUsage: PromptUsageState; + sessionTodos: SessionTodosState; userShells: UserShellsState; prepareProgress: PrepareProgressState; }; @@ -201,8 +286,23 @@ export type SessionRuntimeSliceActions = { setAvailableCommands: (sessionId: string, commands: AvailableCommand[]) => void; clearAvailableCommands: (sessionId: string) => void; // Session mode actions - setSessionMode: (sessionId: string, modeId: string) => void; + setSessionMode: (sessionId: string, modeId: string, availableModes?: SessionModeEntry[]) => void; clearSessionMode: (sessionId: string) => void; + // Agent capabilities actions + setAgentCapabilities: (sessionId: string, caps: AgentCapabilitiesEntry) => void; + // Session models actions + setSessionModels: ( + sessionId: string, + data: { + currentModelId: string; + models: SessionModelEntry[]; + configOptions: ConfigOptionEntry[]; + }, + ) => void; + // Prompt usage actions + setPromptUsage: (sessionId: string, usage: PromptUsageEntry) => void; + // Session todos actions + setSessionTodos: (sessionId: string, entries: TodoEntry[]) => void; // User shells actions setUserShells: (sessionId: string, shells: UserShellInfo[]) => void; setUserShellsLoading: (sessionId: string, loading: boolean) => void; diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts index df602a68b0..f36b0bae57 100644 --- a/apps/web/lib/state/store.ts +++ b/apps/web/lib/state/store.ts @@ -55,6 +55,16 @@ import { type PreviewDevicePreset, type ConnectionState, } from "./slices"; +import type { + AvailableCommand, + SessionModeEntry, + AgentCapabilitiesEntry, + SessionModelEntry, + ConfigOptionEntry, + PromptUsageEntry, + TodoEntry, + UserShellInfo, +} from "./slices/session-runtime/types"; // Re-export all types from slices for backwards compatibility export type { @@ -172,6 +182,10 @@ export type AppState = { sessionMode: (typeof defaultSessionRuntimeState)["sessionMode"]; userShells: (typeof defaultSessionRuntimeState)["userShells"]; prepareProgress: (typeof defaultSessionRuntimeState)["prepareProgress"]; + sessionTodos: (typeof defaultSessionRuntimeState)["sessionTodos"]; + agentCapabilities: (typeof defaultSessionRuntimeState)["agentCapabilities"]; + sessionModels: (typeof defaultSessionRuntimeState)["sessionModels"]; + promptUsage: (typeof defaultSessionRuntimeState)["promptUsage"]; // GitHub slice githubStatus: (typeof defaultGitHubState)["githubStatus"]; @@ -353,24 +367,30 @@ export type AppState = { setQueueLoading: (sessionId: string, loading: boolean) => void; clearQueueStatus: (sessionId: string) => void; // Available commands actions - setAvailableCommands: ( - sessionId: string, - commands: import("./slices/session-runtime/types").AvailableCommand[], - ) => void; + setAvailableCommands: (sessionId: string, commands: AvailableCommand[]) => void; clearAvailableCommands: (sessionId: string) => void; // Session mode actions - setSessionMode: (sessionId: string, modeId: string) => void; + setSessionMode: (sessionId: string, modeId: string, availableModes?: SessionModeEntry[]) => void; clearSessionMode: (sessionId: string) => void; + // Agent capabilities actions + setAgentCapabilities: (sessionId: string, caps: AgentCapabilitiesEntry) => void; + // Session models actions + setSessionModels: ( + sessionId: string, + data: { + currentModelId: string; + models: SessionModelEntry[]; + configOptions: ConfigOptionEntry[]; + }, + ) => void; + // Prompt usage actions + setPromptUsage: (sessionId: string, usage: PromptUsageEntry) => void; + // Session todos actions + setSessionTodos: (sessionId: string, entries: TodoEntry[]) => void; // User shells actions - setUserShells: ( - sessionId: string, - shells: import("./slices/session-runtime/types").UserShellInfo[], - ) => void; + setUserShells: (sessionId: string, shells: UserShellInfo[]) => void; setUserShellsLoading: (sessionId: string, loading: boolean) => void; - addUserShell: ( - sessionId: string, - shell: import("./slices/session-runtime/types").UserShellInfo, - ) => void; + addUserShell: (sessionId: string, shell: UserShellInfo) => void; removeUserShell: (sessionId: string, terminalId: string) => void; }; @@ -418,6 +438,10 @@ const defaultState = { sessionMode: defaultSessionRuntimeState.sessionMode, userShells: defaultSessionRuntimeState.userShells, prepareProgress: defaultSessionRuntimeState.prepareProgress, + sessionTodos: defaultSessionRuntimeState.sessionTodos, + agentCapabilities: defaultSessionRuntimeState.agentCapabilities, + sessionModels: defaultSessionRuntimeState.sessionModels, + promptUsage: defaultSessionRuntimeState.promptUsage, githubStatus: defaultGitHubState.githubStatus, taskPRs: defaultGitHubState.taskPRs, prWatches: defaultGitHubState.prWatches, @@ -488,6 +512,10 @@ function mergeInitialState(initialState?: Partial): typeof defaultStat sessionMode: { ...defaultState.sessionMode, ...initialState.sessionMode }, userShells: { ...defaultState.userShells, ...initialState.userShells }, prepareProgress: { ...defaultState.prepareProgress, ...initialState.prepareProgress }, + sessionTodos: { ...defaultState.sessionTodos, ...initialState.sessionTodos }, + agentCapabilities: { ...defaultState.agentCapabilities, ...initialState.agentCapabilities }, + sessionModels: { ...defaultState.sessionModels, ...initialState.sessionModels }, + promptUsage: { ...defaultState.promptUsage, ...initialState.promptUsage }, githubStatus: { ...defaultState.githubStatus, ...initialState.githubStatus }, taskPRs: { ...defaultState.taskPRs, ...initialState.taskPRs }, prWatches: { ...defaultState.prWatches, ...initialState.prWatches }, @@ -567,6 +595,10 @@ export function createAppStore(initialState?: Partial) { sessionMode: merged.sessionMode, userShells: merged.userShells, prepareProgress: merged.prepareProgress, + sessionTodos: merged.sessionTodos, + agentCapabilities: merged.agentCapabilities, + sessionModels: merged.sessionModels, + promptUsage: merged.promptUsage, githubStatus: merged.githubStatus, taskPRs: merged.taskPRs, prWatches: merged.prWatches, diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts index a516feceed..444caf709d 100644 --- a/apps/web/lib/types/backend.ts +++ b/apps/web/lib/types/backend.ts @@ -33,6 +33,10 @@ export type BackendMessageType = | "session.turn.completed" | "session.available_commands" | "session.mode_changed" + | "session.agent_capabilities" + | "session.models_updated" + | "session.todos_updated" + | "session.prompt_usage" | "executor.created" | "executor.updated" | "executor.deleted" @@ -76,6 +80,13 @@ import type { import type { SecretListItem } from "@/lib/types/http-secrets"; import type { GitEventPayload } from "@/lib/types/git-events"; import type { TaskPR } from "@/lib/types/github"; +import type { FileChangeNotificationPayload } from "./workspace-files"; +import type { + AgentCapabilitiesPayload, + SessionModelsPayload, + SessionPromptUsagePayload, + SessionTodosPayload, +} from "./session-runtime-payloads"; export type KanbanUpdatePayload = { workflowId: string; @@ -416,9 +427,24 @@ export type SessionModeChangedPayload = { session_id: string; agent_id: string; current_mode_id: string; + available_modes?: { + id: string; + name: string; + description?: string; + }[]; timestamp?: string; }; +// Session runtime payload types (extracted to reduce file size) +export { + type AuthMethodInfoPayload, + type AgentCapabilitiesPayload, + type SessionModelInfoPayload, + type ConfigOptionPayload, + type SessionModelsPayload, + type SessionTodosPayload, +} from "./session-runtime-payloads"; + export type TaskPlanEventPayload = { id: string; task_id: string; @@ -491,6 +517,13 @@ export type BackendMessageMap = { AvailableCommandsPayload >; "session.mode_changed": BackendMessage<"session.mode_changed", SessionModeChangedPayload>; + "session.agent_capabilities": BackendMessage< + "session.agent_capabilities", + AgentCapabilitiesPayload + >; + "session.models_updated": BackendMessage<"session.models_updated", SessionModelsPayload>; + "session.todos_updated": BackendMessage<"session.todos_updated", SessionTodosPayload>; + "session.prompt_usage": BackendMessage<"session.prompt_usage", SessionPromptUsagePayload>; "executor.created": BackendMessage<"executor.created", ExecutorPayload>; "executor.updated": BackendMessage<"executor.updated", ExecutorPayload>; "executor.deleted": BackendMessage<"executor.deleted", ExecutorPayload>; @@ -526,74 +559,14 @@ export type BackendMessageMap = { "github.task_pr.updated": BackendMessage<"github.task_pr.updated", TaskPR>; }; -// Workspace file types -export type FileTreeNode = { - name: string; - path: string; - is_dir: boolean; - size?: number; - children?: FileTreeNode[]; -}; - -export type FileTreeResponse = { - request_id?: string; - root: FileTreeNode; - error?: string; -}; - -export type FileContentResponse = { - request_id?: string; - path: string; - content: string; - size: number; - is_binary?: boolean; - resolved_path?: string; - error?: string; -}; - -export type FileSearchResponse = { - files: string[]; - error?: string; -}; - -// Single file change event (used within batched notifications) -export type FileChangeEvent = { - timestamp: string; - path: string; - operation: "create" | "write" | "remove" | "rename" | "chmod" | "refresh"; - session_id: string; - task_id: string; - agent_id: string; -}; - -// Batched file change notification payload (multiple changes batched for efficiency) -export type FileChangeNotificationPayload = { - session_id: string; - changes: FileChangeEvent[]; -}; - -// Open file tab for file viewer -export type OpenFileTab = { - path: string; - name: string; - content: string; - originalContent: string; // For diff generation - originalHash: string; // SHA256 for conflict detection - isDirty: boolean; // Has unsaved changes - isBinary?: boolean; // Binary file (content is base64-encoded) -}; - -// File extension to color mapping for file type indicators -export const FILE_EXTENSION_COLORS: Record = { - ts: "bg-blue-500", - tsx: "bg-blue-400", - js: "bg-yellow-500", - jsx: "bg-yellow-400", - go: "bg-cyan-500", - py: "bg-green-500", - rs: "bg-orange-500", - json: "bg-amber-400", - css: "bg-purple-500", - html: "bg-red-500", - md: "bg-gray-400", -}; +// Workspace file types (extracted to reduce file size) +export { + type FileTreeNode, + type FileTreeResponse, + type FileContentResponse, + type FileSearchResponse, + type FileChangeEvent, + type FileChangeNotificationPayload, + type OpenFileTab, + FILE_EXTENSION_COLORS, +} from "./workspace-files"; diff --git a/apps/web/lib/types/context.ts b/apps/web/lib/types/context.ts index d706d22761..c6391dcb39 100644 --- a/apps/web/lib/types/context.ts +++ b/apps/web/lib/types/context.ts @@ -1,5 +1,5 @@ import type { DiffComment, PlanComment, PRFeedbackComment } from "@/lib/state/slices/comments"; -import type { ImageAttachment } from "@/components/task/chat/image-attachment-preview"; +import type { FileAttachment } from "@/components/task/chat/file-attachment"; type ContextItemBase = { id: string; @@ -43,7 +43,12 @@ export type PlanCommentContextItem = ContextItemBase & { export type ImageContextItem = ContextItemBase & { kind: "image"; - attachment: ImageAttachment; + attachment: FileAttachment; +}; + +export type FileAttachmentContextItem = ContextItemBase & { + kind: "file-attachment"; + attachment: FileAttachment; }; export type PRFeedbackContextItem = ContextItemBase & { @@ -59,6 +64,7 @@ export type ContextItem = | CommentContextItem | PlanCommentContextItem | ImageContextItem + | FileAttachmentContextItem | PRFeedbackContextItem; export type ContextItemKind = ContextItem["kind"]; diff --git a/apps/web/lib/types/session-runtime-payloads.ts b/apps/web/lib/types/session-runtime-payloads.ts new file mode 100644 index 0000000000..007f201f54 --- /dev/null +++ b/apps/web/lib/types/session-runtime-payloads.ts @@ -0,0 +1,75 @@ +export type AuthMethodInfoPayload = { + id: string; + name: string; + description?: string; + terminal_auth?: { + command: string; + args?: string[]; + label?: string; + }; + meta?: Record; +}; + +export type AgentCapabilitiesPayload = { + task_id: string; + session_id: string; + agent_id: string; + supports_image: boolean; + supports_audio: boolean; + supports_embedded_context: boolean; + auth_methods: AuthMethodInfoPayload[]; + timestamp: string; +}; + +export type SessionModelInfoPayload = { + model_id: string; + name: string; + description?: string; + usage_multiplier?: string; + meta?: Record; +}; + +export type ConfigOptionPayload = { + type: string; + id: string; + name: string; + current_value: string; + category?: string; + options?: { value: string; name: string }[]; +}; + +export type SessionModelsPayload = { + task_id: string; + session_id: string; + agent_id: string; + current_model_id: string; + models: SessionModelInfoPayload[]; + config_options: ConfigOptionPayload[]; + timestamp: string; +}; + +export type SessionPromptUsagePayload = { + task_id: string; + session_id: string; + agent_id: string; + usage: { + input_tokens: number; + output_tokens: number; + cached_read_tokens?: number; + cached_write_tokens?: number; + total_tokens: number; + }; + timestamp: string; +}; + +export type SessionTodosPayload = { + task_id: string; + session_id: string; + agent_id: string; + entries: Array<{ + description: string; + status: string; + priority: string; + }>; + timestamp: string; +}; diff --git a/apps/web/lib/types/workspace-files.ts b/apps/web/lib/types/workspace-files.ts new file mode 100644 index 0000000000..6bb4e2d562 --- /dev/null +++ b/apps/web/lib/types/workspace-files.ts @@ -0,0 +1,66 @@ +export type FileTreeNode = { + name: string; + path: string; + is_dir: boolean; + size?: number; + children?: FileTreeNode[]; +}; + +export type FileTreeResponse = { + request_id?: string; + root: FileTreeNode; + error?: string; +}; + +export type FileContentResponse = { + request_id?: string; + path: string; + content: string; + size: number; + is_binary?: boolean; + resolved_path?: string; + error?: string; +}; + +export type FileSearchResponse = { + files: string[]; + error?: string; +}; + +export type FileChangeEvent = { + timestamp: string; + path: string; + operation: "create" | "write" | "remove" | "rename" | "chmod" | "refresh"; + session_id: string; + task_id: string; + agent_id: string; +}; + +export type FileChangeNotificationPayload = { + session_id: string; + changes: FileChangeEvent[]; +}; + +export type OpenFileTab = { + path: string; + name: string; + content: string; + originalContent: string; + originalHash: string; + isDirty: boolean; + isBinary?: boolean; +}; + +export const FILE_EXTENSION_COLORS: Record = { + ts: "bg-blue-500", + tsx: "bg-blue-400", + js: "bg-yellow-500", + jsx: "bg-yellow-400", + go: "bg-cyan-500", + py: "bg-green-500", + rs: "bg-orange-500", + json: "bg-amber-400", + css: "bg-purple-500", + html: "bg-red-500", + md: "bg-gray-400", +}; diff --git a/apps/web/lib/ws/handlers/agent-capabilities.ts b/apps/web/lib/ws/handlers/agent-capabilities.ts new file mode 100644 index 0000000000..1ec152cb2a --- /dev/null +++ b/apps/web/lib/ws/handlers/agent-capabilities.ts @@ -0,0 +1,33 @@ +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import type { WsHandlers } from "@/lib/ws/handlers/types"; +import type { AgentCapabilitiesPayload } from "@/lib/types/backend"; + +export function registerAgentCapabilitiesHandlers(store: StoreApi): WsHandlers { + return { + "session.agent_capabilities": (message) => { + const payload = message.payload as AgentCapabilitiesPayload | undefined; + if (!payload?.session_id) { + return; + } + store.getState().setAgentCapabilities(payload.session_id, { + supportsImage: payload.supports_image, + supportsAudio: payload.supports_audio, + supportsEmbeddedContext: payload.supports_embedded_context, + authMethods: (payload.auth_methods ?? []).map((m) => ({ + id: m.id, + name: m.name, + description: m.description, + terminalAuth: m.terminal_auth + ? { + command: m.terminal_auth.command, + args: m.terminal_auth.args, + label: m.terminal_auth.label, + } + : undefined, + meta: m.meta, + })), + }); + }, + }; +} diff --git a/apps/web/lib/ws/handlers/prompt-usage.ts b/apps/web/lib/ws/handlers/prompt-usage.ts new file mode 100644 index 0000000000..2051a52107 --- /dev/null +++ b/apps/web/lib/ws/handlers/prompt-usage.ts @@ -0,0 +1,22 @@ +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import type { WsHandlers } from "@/lib/ws/handlers/types"; +import type { SessionPromptUsagePayload } from "@/lib/types/session-runtime-payloads"; + +export function registerPromptUsageHandlers(store: StoreApi): WsHandlers { + return { + "session.prompt_usage": (message) => { + const payload = message.payload as SessionPromptUsagePayload | undefined; + if (!payload?.session_id || !payload?.usage) { + return; + } + store.getState().setPromptUsage(payload.session_id, { + inputTokens: payload.usage.input_tokens, + outputTokens: payload.usage.output_tokens, + cachedReadTokens: payload.usage.cached_read_tokens, + cachedWriteTokens: payload.usage.cached_write_tokens, + totalTokens: payload.usage.total_tokens, + }); + }, + }; +} diff --git a/apps/web/lib/ws/handlers/session-mode.ts b/apps/web/lib/ws/handlers/session-mode.ts index fd5df74bc7..39ec219260 100644 --- a/apps/web/lib/ws/handlers/session-mode.ts +++ b/apps/web/lib/ws/handlers/session-mode.ts @@ -1,22 +1,29 @@ import type { StoreApi } from "zustand"; import type { AppState } from "@/lib/state/store"; import type { WsHandlers } from "@/lib/ws/handlers/types"; +import type { SessionModeChangedPayload } from "@/lib/types/backend"; export function registerSessionModeHandlers(store: StoreApi): WsHandlers { return { "session.mode_changed": (message) => { - const payload = message.payload; + const payload = message.payload as SessionModeChangedPayload | undefined; if (!payload?.session_id) { return; } - const sessionId = payload.session_id as string; + const sessionId = payload.session_id; // Empty current_mode_id means the agent exited its special mode - const modeId = (payload.current_mode_id as string) || ""; + const modeId = payload.current_mode_id || ""; + const availableModes = payload.available_modes?.map((m) => ({ + id: m.id, + name: m.name, + description: m.description, + })); if (modeId) { - store.getState().setSessionMode(sessionId, modeId); + store.getState().setSessionMode(sessionId, modeId, availableModes); } else { - store.getState().clearSessionMode(sessionId); + // Keep availableModes so the UI still knows what modes exist + store.getState().setSessionMode(sessionId, "", availableModes); } }, }; diff --git a/apps/web/lib/ws/handlers/session-models.ts b/apps/web/lib/ws/handlers/session-models.ts new file mode 100644 index 0000000000..30637dc3c7 --- /dev/null +++ b/apps/web/lib/ws/handlers/session-models.ts @@ -0,0 +1,33 @@ +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import type { WsHandlers } from "@/lib/ws/handlers/types"; +import type { SessionModelsPayload } from "@/lib/types/backend"; + +export function registerSessionModelsHandlers(store: StoreApi): WsHandlers { + return { + "session.models_updated": (message) => { + const payload = message.payload as SessionModelsPayload | undefined; + if (!payload?.session_id) { + return; + } + store.getState().setSessionModels(payload.session_id, { + currentModelId: payload.current_model_id, + models: (payload.models ?? []).map((m) => ({ + modelId: m.model_id, + name: m.name, + description: m.description, + usageMultiplier: m.usage_multiplier, + meta: m.meta, + })), + configOptions: (payload.config_options ?? []).map((o) => ({ + type: o.type, + id: o.id, + name: o.name, + currentValue: o.current_value, + category: o.category, + options: o.options, + })), + }); + }, + }; +} diff --git a/apps/web/lib/ws/handlers/session-todos.ts b/apps/web/lib/ws/handlers/session-todos.ts new file mode 100644 index 0000000000..f17835809f --- /dev/null +++ b/apps/web/lib/ws/handlers/session-todos.ts @@ -0,0 +1,26 @@ +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import type { WsHandlers } from "@/lib/ws/handlers/types"; +import type { SessionTodosPayload } from "@/lib/types/backend"; +import type { TodoEntry } from "@/lib/state/slices/session-runtime/types"; + +export function registerSessionTodosHandlers(store: StoreApi): WsHandlers { + return { + "session.todos_updated": (message) => { + const payload = message.payload as SessionTodosPayload | undefined; + if (!payload?.session_id) { + return; + } + store.getState().setSessionTodos( + payload.session_id, + (payload.entries ?? []).map( + (e): TodoEntry => ({ + description: e.description, + status: e.status as TodoEntry["status"], + priority: e.priority, + }), + ), + ); + }, + }; +} diff --git a/apps/web/lib/ws/router.ts b/apps/web/lib/ws/router.ts index 823d8ef8e7..778d42ed67 100644 --- a/apps/web/lib/ws/router.ts +++ b/apps/web/lib/ws/router.ts @@ -4,6 +4,10 @@ import { registerAgentsHandlers } from "@/lib/ws/handlers/agents"; import { registerTaskSessionHandlers } from "@/lib/ws/handlers/agent-session"; import { registerAvailableCommandsHandlers } from "@/lib/ws/handlers/available-commands"; import { registerSessionModeHandlers } from "@/lib/ws/handlers/session-mode"; +import { registerAgentCapabilitiesHandlers } from "@/lib/ws/handlers/agent-capabilities"; +import { registerSessionModelsHandlers } from "@/lib/ws/handlers/session-models"; +import { registerSessionTodosHandlers } from "@/lib/ws/handlers/session-todos"; +import { registerPromptUsageHandlers } from "@/lib/ws/handlers/prompt-usage"; import { registerWorkflowsHandlers } from "@/lib/ws/handlers/workflows"; import { registerMessagesHandlers } from "@/lib/ws/handlers/messages"; @@ -39,6 +43,10 @@ export function registerWsHandlers(store: StoreApi) { ...registerTaskSessionHandlers(store), ...registerAvailableCommandsHandlers(store), ...registerSessionModeHandlers(store), + ...registerAgentCapabilitiesHandlers(store), + ...registerSessionModelsHandlers(store), + ...registerSessionTodosHandlers(store), + ...registerPromptUsageHandlers(store), ...registerUsersHandlers(store), ...registerTerminalsHandlers(store), ...registerDiffsHandlers(store),