import React, { useState, useEffect, useRef } from "react"; import { motion, AnimatePresence } from "framer-motion"; import { ArrowLeft, Play, StopCircle, FolderOpen, Terminal, AlertCircle, Loader2, Copy, ChevronDown, Maximize2, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Popover } from "@/components/ui/popover"; import { api, type Agent } from "@/lib/api"; import { cn } from "@/lib/utils"; import { open } from "@tauri-apps/plugin-dialog"; import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { StreamMessage } from "./StreamMessage"; import { ExecutionControlBar } from "./ExecutionControlBar"; import { ErrorBoundary } from "./ErrorBoundary"; interface AgentExecutionProps { /** * The agent to execute */ agent: Agent; /** * Callback to go back to the agents list */ onBack: () => void; /** * Optional className for styling */ className?: string; } export interface ClaudeStreamMessage { type: "system" | "assistant" | "user" | "result"; subtype?: string; message?: { content?: any[]; usage?: { input_tokens: number; output_tokens: number; }; }; usage?: { input_tokens: number; output_tokens: number; }; [key: string]: any; } /** * AgentExecution component for running CC agents * * @example * setView('list')} /> */ export const AgentExecution: React.FC = ({ agent, onBack, className, }) => { const [projectPath, setProjectPath] = useState(""); const [task, setTask] = useState(""); const [model, setModel] = useState(agent.model || "sonnet"); const [isRunning, setIsRunning] = useState(false); const [messages, setMessages] = useState([]); const [rawJsonlOutput, setRawJsonlOutput] = useState([]); const [error, setError] = useState(null); const [copyPopoverOpen, setCopyPopoverOpen] = useState(false); // Execution stats const [executionStartTime, setExecutionStartTime] = useState(null); const [totalTokens, setTotalTokens] = useState(0); const [elapsedTime, setElapsedTime] = useState(0); const [hasUserScrolled, setHasUserScrolled] = useState(false); const [isFullscreenModalOpen, setIsFullscreenModalOpen] = useState(false); const messagesEndRef = useRef(null); const messagesContainerRef = useRef(null); const scrollContainerRef = useRef(null); const fullscreenScrollRef = useRef(null); const fullscreenMessagesEndRef = useRef(null); const unlistenRefs = useRef([]); const elapsedTimeIntervalRef = useRef(null); useEffect(() => { // Clean up listeners on unmount return () => { unlistenRefs.current.forEach(unlisten => unlisten()); if (elapsedTimeIntervalRef.current) { clearInterval(elapsedTimeIntervalRef.current); } }; }, []); // Check if user is at the very bottom of the scrollable container const isAtBottom = () => { const container = isFullscreenModalOpen ? fullscreenScrollRef.current : scrollContainerRef.current; if (container) { const { scrollTop, scrollHeight, clientHeight } = container; const distanceFromBottom = scrollHeight - scrollTop - clientHeight; return distanceFromBottom < 1; } return true; }; useEffect(() => { // Only auto-scroll if user hasn't manually scrolled OR if they're at the bottom const shouldAutoScroll = !hasUserScrolled || isAtBottom(); if (shouldAutoScroll) { const endRef = isFullscreenModalOpen ? fullscreenMessagesEndRef.current : messagesEndRef.current; if (endRef) { endRef.scrollIntoView({ behavior: "smooth" }); } } }, [messages, hasUserScrolled, isFullscreenModalOpen]); // Update elapsed time while running useEffect(() => { if (isRunning && executionStartTime) { elapsedTimeIntervalRef.current = setInterval(() => { setElapsedTime(Math.floor((Date.now() - executionStartTime) / 1000)); }, 100); } else { if (elapsedTimeIntervalRef.current) { clearInterval(elapsedTimeIntervalRef.current); } } return () => { if (elapsedTimeIntervalRef.current) { clearInterval(elapsedTimeIntervalRef.current); } }; }, [isRunning, executionStartTime]); // Calculate total tokens from messages useEffect(() => { const tokens = messages.reduce((total, msg) => { if (msg.message?.usage) { return total + msg.message.usage.input_tokens + msg.message.usage.output_tokens; } if (msg.usage) { return total + msg.usage.input_tokens + msg.usage.output_tokens; } return total; }, 0); setTotalTokens(tokens); }, [messages]); const handleSelectPath = async () => { try { const selected = await open({ directory: true, multiple: false, title: "Select Project Directory" }); if (selected) { setProjectPath(selected as string); setError(null); // Clear any previous errors } } catch (err) { console.error("Failed to select directory:", err); // More detailed error logging const errorMessage = err instanceof Error ? err.message : String(err); setError(`Failed to select directory: ${errorMessage}`); } }; const handleExecute = async () => { if (!projectPath || !task.trim()) return; try { setIsRunning(true); setError(null); setMessages([]); setRawJsonlOutput([]); setExecutionStartTime(Date.now()); setElapsedTime(0); setTotalTokens(0); // Set up event listeners const outputUnlisten = await listen("agent-output", (event) => { try { // Store raw JSONL setRawJsonlOutput(prev => [...prev, event.payload]); // Parse and display const message = JSON.parse(event.payload) as ClaudeStreamMessage; setMessages(prev => [...prev, message]); } catch (err) { console.error("Failed to parse message:", err, event.payload); } }); const errorUnlisten = await listen("agent-error", (event) => { console.error("Agent error:", event.payload); setError(event.payload); }); const completeUnlisten = await listen("agent-complete", (event) => { setIsRunning(false); setExecutionStartTime(null); if (!event.payload) { setError("Agent execution failed"); } }); unlistenRefs.current = [outputUnlisten, errorUnlisten, completeUnlisten]; // Execute the agent with model override await api.executeAgent(agent.id!, projectPath, task, model); } catch (err) { console.error("Failed to execute agent:", err); setError("Failed to execute agent"); setIsRunning(false); setExecutionStartTime(null); } }; const handleStop = async () => { try { // TODO: Implement actual stop functionality via API // For now, just update the UI state setIsRunning(false); setExecutionStartTime(null); // Clean up listeners unlistenRefs.current.forEach(unlisten => unlisten()); unlistenRefs.current = []; // Add a message indicating execution was stopped setMessages(prev => [...prev, { type: "result", subtype: "error", is_error: true, result: "Execution stopped by user", duration_ms: elapsedTime * 1000, usage: { input_tokens: totalTokens, output_tokens: 0 } }]); } catch (err) { console.error("Failed to stop agent:", err); } }; const handleBackWithConfirmation = () => { if (isRunning) { // Show confirmation dialog before navigating away during execution const shouldLeave = window.confirm( "An agent is currently running. If you navigate away, the agent will continue running in the background. You can view running sessions in the 'Running Sessions' tab within CC Agents.\n\nDo you want to continue?" ); if (!shouldLeave) { return; } } // Clean up listeners but don't stop the actual agent process unlistenRefs.current.forEach(unlisten => unlisten()); unlistenRefs.current = []; // Navigate back onBack(); }; const handleCopyAsJsonl = async () => { const jsonl = rawJsonlOutput.join('\n'); await navigator.clipboard.writeText(jsonl); setCopyPopoverOpen(false); }; const handleCopyAsMarkdown = async () => { let markdown = `# Agent Execution: ${agent.name}\n\n`; markdown += `**Task:** ${task}\n`; markdown += `**Model:** ${model === 'opus' ? 'Claude 4 Opus' : 'Claude 4 Sonnet'}\n`; markdown += `**Date:** ${new Date().toISOString()}\n\n`; markdown += `---\n\n`; for (const msg of messages) { if (msg.type === "system" && msg.subtype === "init") { markdown += `## System Initialization\n\n`; markdown += `- Session ID: \`${msg.session_id || 'N/A'}\`\n`; markdown += `- Model: \`${msg.model || 'default'}\`\n`; if (msg.cwd) markdown += `- Working Directory: \`${msg.cwd}\`\n`; if (msg.tools?.length) markdown += `- Tools: ${msg.tools.join(', ')}\n`; markdown += `\n`; } else if (msg.type === "assistant" && msg.message) { markdown += `## Assistant\n\n`; for (const content of msg.message.content || []) { if (content.type === "text") { markdown += `${content.text}\n\n`; } else if (content.type === "tool_use") { markdown += `### Tool: ${content.name}\n\n`; markdown += `\`\`\`json\n${JSON.stringify(content.input, null, 2)}\n\`\`\`\n\n`; } } if (msg.message.usage) { markdown += `*Tokens: ${msg.message.usage.input_tokens} in, ${msg.message.usage.output_tokens} out*\n\n`; } } else if (msg.type === "user" && msg.message) { markdown += `## User\n\n`; for (const content of msg.message.content || []) { if (content.type === "text") { markdown += `${content.text}\n\n`; } else if (content.type === "tool_result") { markdown += `### Tool Result\n\n`; markdown += `\`\`\`\n${content.content}\n\`\`\`\n\n`; } } } else if (msg.type === "result") { markdown += `## Execution Result\n\n`; if (msg.result) { markdown += `${msg.result}\n\n`; } if (msg.error) { markdown += `**Error:** ${msg.error}\n\n`; } if (msg.cost_usd !== undefined) { markdown += `- **Cost:** $${msg.cost_usd.toFixed(4)} USD\n`; } if (msg.duration_ms !== undefined) { markdown += `- **Duration:** ${(msg.duration_ms / 1000).toFixed(2)}s\n`; } if (msg.num_turns !== undefined) { markdown += `- **Turns:** ${msg.num_turns}\n`; } if (msg.usage) { const total = msg.usage.input_tokens + msg.usage.output_tokens; markdown += `- **Total Tokens:** ${total} (${msg.usage.input_tokens} in, ${msg.usage.output_tokens} out)\n`; } } } await navigator.clipboard.writeText(markdown); setCopyPopoverOpen(false); }; const renderIcon = () => { const Icon = agent.icon in AGENT_ICONS ? AGENT_ICONS[agent.icon as keyof typeof AGENT_ICONS] : Terminal; return ; }; return (
{/* Header */}
{renderIcon()}

{agent.name}

{isRunning && (
Running
)}

{isRunning ? "Click back to return to main menu - view in CC Agents > Running Sessions" : "Execute CC Agent"}

{messages.length > 0 && ( <> Copy Output } content={
} open={copyPopoverOpen} onOpenChange={setCopyPopoverOpen} align="end" /> )}
{/* Configuration */}
{/* Error display */} {error && ( {error} )} {/* Project Path */}
setProjectPath(e.target.value)} placeholder="Select or enter project path" disabled={isRunning} className="flex-1" />
{/* Model Selection */}
{/* Task Input */}
setTask(e.target.value)} placeholder={agent.default_task || "Enter the task for the agent"} disabled={isRunning} className="flex-1" onKeyPress={(e) => { if (e.key === "Enter" && !isRunning && projectPath && task.trim()) { handleExecute(); } }} />
{/* Output Display */}
{ // Mark that user has scrolled manually if (!hasUserScrolled) { setHasUserScrolled(true); } // If user scrolls back to bottom, re-enable auto-scroll if (isAtBottom()) { setHasUserScrolled(false); } }} >
{messages.length === 0 && !isRunning && (

Ready to Execute

Select a project path and enter a task to run the agent

)} {isRunning && messages.length === 0 && (
Initializing agent...
)} {messages.map((message, index) => ( ))}
{/* Floating Execution Control Bar */} {/* Fullscreen Modal */} {isFullscreenModalOpen && (
{/* Modal Header */}
{renderIcon()}

{agent.name} - Output

{isRunning && (
Running
)}
Copy Output } content={
} open={copyPopoverOpen} onOpenChange={setCopyPopoverOpen} align="end" />
{/* Modal Content */}
{ // Mark that user has scrolled manually if (!hasUserScrolled) { setHasUserScrolled(true); } // If user scrolls back to bottom, re-enable auto-scroll if (isAtBottom()) { setHasUserScrolled(false); } }} > {messages.length === 0 && !isRunning && (

Ready to Execute

Select a project path and enter a task to run the agent

)} {isRunning && messages.length === 0 && (
Initializing agent...
)} {messages.map((message, index) => ( ))}
)}
); }; // Import AGENT_ICONS for icon rendering import { AGENT_ICONS } from "./CCAgents";