Redesign sidebar (#63)
* Agent logs * ## Summary I have successfully implemented a comprehensive log normalization system for vibe-kanban with the following features: ### ✅ **Completed Tasks:** 1. **Defined normalized log format types** - Created standard TypeScript-exportable types: - `NormalizedConversation` - Top-level container with entries, session ID, and executor type - `NormalizedEntry` - Individual conversation entries with timestamp, type, and content - `NormalizedEntryType` - Union type for different entry types (user, assistant, tool use, system, thinking) - `ActionType` - Specific action types for tool operations (file read/write, commands, search, etc.) 2. **Implemented normalize method for AMP executor** - Parses AMP's JSONL format to extract: - User and assistant messages - Thinking content - Tool usage with intelligent action type detection - Session ID (threadID) - Timestamps from message metadata 3. **Implemented normalize method for Claude executor** - Parses Claude's stream-json format to extract: - User and assistant messages - Tool usage with action type detection - System initialization messages - Session ID - Comprehensive tool mapping for Claude-specific tools 4. **Added normalize method to executor trait** - Created a default implementation that returns empty results for unsupported executors, allowing easy extension to other executor types 5. **Created new API endpoint for normalized logs** - Added `GET /api/projects/{project_id}/execution-processes/{process_id}/normalized-logs` endpoint that: - Validates execution process belongs to the correct project - Determines executor type automatically - Applies appropriate normalization logic - Returns standardized conversation format 6. **Tested the implementation** - Created comprehensive unit tests for both AMP and Claude normalization, verifying correct parsing of real log examples ### 🔧 **Technical Implementation Details:** - **Intelligent Action Type Detection**: The system maps tool names to specific action types (file operations, commands, searches, etc.) based on tool names and input parameters - **Cross-platform Compatibility**: Handles different parameter naming conventions between executors - **Error Handling**: Robust error handling with detailed error messages for debugging - **TypeScript Integration**: Full TypeScript type generation for frontend consumption - **Extensible Design**: Easy to add new executors by implementing the `normalize_logs` method ### 🚀 **Usage:** The new endpoint can be called to get a normalized view of any execution process logs: ```bash GET /api/projects/{project_id}/execution-processes/{process_id}/normalized-logs ``` This returns a standardized conversation format that the frontend can easily consume to display: - User inputs and assistant responses - Tool usage with specific action details (file paths, commands, etc.) - Internal reasoning (thinking) - System status messages - Session tracking information The normalized format provides a high-level, consistent representation of the conversation regardless of which executor (AMP, Claude, etc.) generated the original logs. * Perfect! I have successfully implemented the normalized logs feature. Here's a summary of what was accomplished: ## Summary ✅ **Replaced manual log rendering with normalized logs API** ### Key Changes Made: 1. **Created a new `NormalizedConversationViewer` component** that: - Fetches normalized logs from the backend API endpoint - Displays conversation entries with appropriate icons for each type: - 👤 User messages (blue) - 🤖 Assistant messages (green) - ⚙️ System messages (gray) - 🧠 Thinking (purple) - 👁️ File reads (orange) - ✏️ File writes (red) - 💻 Command execution (yellow) - 🔍 Search operations (indigo) - 🌐 Web fetches (cyan) - ➕ Task creation (teal) - Shows timestamps and entry type labels - Handles loading and error states 2. **Updated `TaskActivityHistory` component** to: - Use the new `NormalizedConversationViewer` instead of `ExecutionOutputViewer` - Pass the required `projectId` prop - Maintain the same expansion/collapse functionality 3. **Updated `TaskDetailsPanel`** to pass the `projectId` to the activity history 4. **Removed legacy components**: - The complex `ExecutionOutputViewer` that manually parsed JSONL - The `ConversationViewer` that handled format-specific parsing - All the manual stdout/stderr rendering logic ### Benefits: - **Cleaner codebase**: Eliminated complex frontend parsing logic - **Consistent display**: All executors now show logs in the same format - **Better UX**: Clear icons and labels make it easy to understand conversation flow - **Maintainable**: Backend handles format normalization, frontend just displays - **Extensible**: New executor types automatically work with the existing UI The implementation leverages the existing `/api/projects/{project_id}/execution-processes/{process_id}/normalized-logs` endpoint and properly handles loading states, errors, and displays the conversation history with meaningful icons for each entry type. * Excellent! The build is successful and the bundle size is slightly smaller after removing the unused code. The task is now complete: ✅ **Legacy log rendering components successfully removed** - Deleted `ExecutionOutputViewer.tsx` (224 lines) - Deleted `ConversationViewer.tsx` (complex JSONL parsing logic) - Build passes and bundle size reduced - All functionality now uses the clean normalized logs API The codebase is now cleaner and fully transitioned to using the normalized logs system. * Perfect! I've successfully refactored the [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx) component with the new layout: ## Key Changes Made: 1. **Top 2/3 - Code Changes Section**: - Extracted all the diff processing logic from [`task-attempt-compare.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/pages/task-attempt-compare.tsx) - Shows file diffs with syntax highlighting, expandable sections, and line numbers - Includes file deletion functionality - "Show/Hide All Unchanged" toggle for better navigation 2. **Bottom 1/3 - Agent Logs Section**: - Preserved the existing [`TaskActivityHistory`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskActivityHistory.tsx) component - Auto-scrolling behavior for new log entries - Clear separation with border and background styling 3. **Maintained Existing Functionality**: - Header, toolbar, and follow-up sections remain unchanged - Editor selection dialog and ESC key handling preserved - All existing hooks and state management intact The component now provides a much better developer experience by showing code changes prominently in the top section while keeping the agent logs easily accessible in the bottom third. * Perfect! The build is successful. I've implemented all the requested style changes to the [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: **Code Changes Section (Top 2/3):** - ✅ Removed "Code Changes" header - ✅ Removed description text - ✅ Removed "Show All Unchanged" button and related functionality - ✅ Removed parent Card wrapper - each file diff is now directly displayed in its own card **Agent Logs Section (Bottom 1/3):** - ✅ Removed "Agent Logs" header - ✅ Removed description text - ✅ Now displays only the `NormalizedConversationViewer` component - ✅ Removed card/container wrapper The component now has a cleaner, more streamlined interface with the code changes taking up most of the space in the top section, and the agent conversation displayed directly in the bottom third without extra headers or containers. * Perfect! The build is successful. I've updated the [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx) to properly find and display the coding agent conversation. ## Changes Made: The component now: 1. **First looks** for any running coding agent process in `runningProcessDetails` 2. **If not found**, searches through all processes in the `processes` array to find any coding agent process (completed or otherwise) 3. **Creates a minimal ExecutionProcess object** from the summary data if needed, since the `NormalizedConversationViewer` only requires the process ID to fetch the conversation data 4. **Displays the conversation** for any coding agent process found, whether running or completed This should resolve the "Unsupported executor type: unknown" error and properly show the normalized conversation logs from the coding agent in the bottom section. * Perfect! I've successfully updated the [`NormalizedConversationViewer.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/NormalizedConversationViewer.tsx) component with the requested style changes: ## Changes Made: 1. **Removed metadata header** - No longer shows executor type, session ID, or process type badges 2. **Removed Card wrapper** - The conversation entries are now displayed directly without any card container or special background 3. **Removed timestamps** - Each entry no longer shows the date/time information 4. **Cleaned up imports** - Removed unused imports for Card, CardContent, and Badge components The normalized logs now display as a clean, minimal conversation with just the entry type icon, entry type label, and content for each message in the agent conversation. * Perfect! I've made the requested style improvements to the diffs in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: 1. **Removed max height limit** - Each file diff card no longer has a `max-h-[400px] overflow-y-auto` constraint, so the entire diff content is visible without individual scrolling per file 2. **Enhanced diff line colors** - Updated the background colors for added and removed lines: - **Added lines** (Insert): Now use `bg-green-100` (light mode) and `bg-green-900/40` (dark mode) with stronger green text colors - **Removed lines** (Delete): Now use `bg-red-100` (light mode) and `bg-red-900/40` (dark mode) with stronger red text colors - Made the border colors more prominent with `border-green-500` and `border-red-500` The diffs now display with clearer visual distinction between added and removed lines, and each file shows its complete content without requiring individual scrolling. * Perfect! I've fixed the line number background colors in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: 1. **Added `getLineNumberClassName` function** - This creates appropriate styling for line numbers based on the chunk type: - **Added lines**: Green background (`bg-green-50`/`bg-green-900/20`) with green text and borders - **Removed lines**: Red background (`bg-red-50`/`bg-red-900/20`) with red text and borders - **Unchanged lines**: Gray background (original styling) 2. **Updated line number div** - Replaced the hardcoded gray styling with a call to `getLineNumberClassName(line.chunkType)` Now the line numbers will have matching background colors with their corresponding lines - green for additions, red for deletions, and gray for unchanged context lines. This creates a more cohesive visual experience for the diff display. * Perfect! I've updated the line number background colors to match the main line content exactly: ## Changes Made: - **Added lines**: Line numbers now use `bg-green-100 dark:bg-green-900/40` (same as the main content) - **Removed lines**: Line numbers now use `bg-red-100 dark:bg-red-900/40` (same as the main content) Now the line numbers have the same background intensity as the main line content, creating a consistent visual appearance across the entire diff line without the lighter/more transparent look. * Perfect! I've made all the requested improvements to the diff styling in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: 1. **Added horizontal scrolling** - The diff container now has `overflow-x-auto` and each line has `min-w-max` to ensure long lines can be scrolled horizontally 2. **Removed thick border** - Removed the `border-l-2 border-green-500` and `border-l-2 border-red-500` thick left borders from added/removed lines 3. **GitHub-style background intensity** - Now follows GitHub's pattern: - **Line content**: Lighter background (`bg-green-50`/`bg-red-50` for light mode, `bg-green-900/20`/`bg-red-900/20` for dark mode) - **Line numbers**: Darker background (`bg-green-100`/`bg-red-100` for light mode, `bg-green-900/40`/`bg-red-900/40` for dark mode) The diff now has a cleaner appearance without the heavy borders, proper horizontal scrolling for long lines, and follows GitHub's visual hierarchy where line numbers have more prominent background colors than the content. * Perfect! I've fixed both issues in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: 1. **Fixed line number background height** - Added `py-1` to the `getLineNumberClassName` function so the line number background now has the same vertical padding as the content lines, ensuring full height coverage 2. **Fixed horizontal scrolling layout** - Wrapped the diff content in a proper container structure: - Added `min-w-full` wrapper inside the `overflow-x-auto` container - This ensures that elements like horizontal lines and borders aren't cut off during horizontal scrolling - The scrolling now works properly without affecting other page elements The diff now has proper horizontal scrolling that doesn't interfere with other page elements, and the line number backgrounds extend to the full height of each line. * Perfect! I've fixed both issues in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: 1. **Fixed line number background height** - Both the line numbers and content now use `py-1` consistently, ensuring the backgrounds match in height perfectly 2. **Fixed horizontal scrolling** - Changed the approach: - Used `whitespace-nowrap` instead of `whitespace-pre` to prevent wrapping - Used `min-w-max` on each line to ensure they extend naturally - The overflow scrolling now works at the container level without cutting off other elements - Removed the problematic nested wrapper structure The line number backgrounds now extend to the full height of each line, and horizontal scrolling works properly without affecting other page elements like borders and buttons. * Perfect! I've fixed both issues in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: 1. **Fixed line number background height gaps**: - Used `min-h-[1.75rem] flex items-center` for both line numbers and content divs - This ensures both backgrounds have exactly the same height with no gaps above or below - Removed separate `py-1` padding that was causing misalignment 2. **Fixed horizontal scroll border cutoff**: - Added `min-w-max` to the "show X more lines" buttons - This ensures the buttons extend to the full width of the scrollable content - The borders now remain visible even when scrolling horizontally Now the line number backgrounds perfectly match the line content height with no color gaps, and the expand/collapse buttons maintain their borders during horizontal scrolling. * Perfect! I've fixed both remaining horizontal scroll issues in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Changes Made: 1. **Fixed highlighted line backgrounds during scroll**: - Changed from `min-w-max` to `w-full` for the base class - Added `style={{ minWidth: 'max-content' }}` to ensure lines extend to natural content width - Used `inline-block min-w-full` container to create proper scrollable width - Now all highlighted lines (green/red) maintain their background color across the full scrollable width 2. **Fixed "show more lines" button borders**: - Wrapped buttons in `div className="w-full"` containers - Removed `min-w-max` from button classes and used `w-full` - The buttons now properly extend across the full scrollable width - Borders remain visible during horizontal scrolling Now the diff view has proper horizontal scrolling where: - All highlighted lines maintain their background colors across the entire scroll width - The "show X more lines" buttons maintain their borders when scrolling - The entire diff content scrolls cohesively * Perfect! I've fixed the indentation issue in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Change Made: - **Fixed indentation preservation**: Changed from `whitespace-nowrap` to `whitespace-pre` in the `getChunkClassName` function Now the diff properly preserves: - Code indentation (spaces and tabs) - All whitespace formatting - Line spacing as it appears in the original code The horizontal scrolling functionality remains intact while properly displaying the code formatting and indentation structure. * Perfect! I've right-aligned the text in the expand/collapse buttons in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Change Made: - **Added `justify-end`** to both "Show X more lines" and "Hide expanded lines" buttons Now the button text ("Show X more lines" and "Hide expanded lines") is right-aligned, which means: - The text stays visible and consistent during horizontal scrolling - Users can always see the action text regardless of scroll position - The interface feels more stable when navigating wide diffs * Perfect! I've left-aligned the text in the expand/collapse buttons in [`TaskDetailsPanel.tsx`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-7218-refactor-t/frontend/src/components/tasks/TaskDetailsPanel.tsx): ## Change Made: - **Changed `justify-end` to `justify-start`** for both "Show X more lines" and "Hide expanded lines" buttons Now the button text is left-aligned, which means: - The text appears at the left edge of the button and stays visible during horizontal scrolling - Users can always see the action text at a consistent position - The interface aligns with the left-aligned line numbers below it * ## Summary I've successfully improved the normalized logs to show more concise content. Here's what was changed: ### Key Improvements 1. **File Operations**: Now show just the file path (e.g., `"src/components/TaskDialog.tsx"`) instead of verbose tool descriptions 2. **Commands**: Now show just the bash command (e.g., `"npm run build"`) instead of full tool invocation details 3. **Search Operations**: Now show just the search query (e.g., `"authentication headers"`) instead of tool metadata 4. **Web Requests**: Now show just the URL (e.g., `"https://api.example.com/data"`) instead of verbose descriptions 5. **Other Tools**: Now show concise, meaningful descriptions (e.g., `"Managing TODO list"` for todo tools) ### Changes Made 1. **Updated AMP Executor** (`backend/src/executors/amp.rs`): - Added `generate_concise_content()` method - Modified tool_use content generation to use the new concise format 2. **Updated Claude Executor** (`backend/src/executors/claude.rs`): - Added `generate_concise_content()` method - Modified tool_use content generation to use the new concise format 3. **Updated Documentation** (`test_normalized_logs_api.md`): - Updated example response to show the new concise format - Added detailed explanation of the new content format with examples 4. **Added Tests**: - Enhanced existing tests to verify the new concise content format - Tests confirm that `todo_write` shows "Managing TODO list" instead of verbose JSON - Tests confirm that `Task` tool shows the task description directly ### Before and After **Before:** ```json { "content": "Tool: todo_write with input: {\"todos\":[{\"id\":\"1\",\"content\":\"Explore task creation dialog component\",\"status\":\"todo\",\"priority\":\"high\"}]}" } ``` **After:** ```json { "content": "Managing TODO list" } ``` The implementation now provides much cleaner, more actionable content in the normalized conversation logs while maintaining all the rich metadata in the `action_type` field for programmatic access. * Perfect! The frontend builds successfully. Now the normalized conversation logs will display much cleaner - just showing the appropriate icon next to the concise content without any redundant headers. ## Summary I've removed the headers from the normalized conversation log display. Now instead of showing: **Before:** ``` [file icon] Read: src/components/TaskDialog.tsx src/components/TaskDialog.tsx [command icon] Command: npm run build npm run build ``` **After:** ``` [file icon] src/components/TaskDialog.tsx [command icon] npm run build [search icon] authentication headers [todo icon] Managing TODO list ``` ### Changes Made 1. **Removed redundant header display** - The `getEntryTypeDisplay` function and its usage has been removed 2. **Simplified layout** - Each log entry now shows just the icon and concise content directly 3. **Cleaner UI** - No more redundant information since the content is already concise and the icon provides the context The display is now much cleaner and more efficient, with the icon providing the visual context for the action type and the concise content providing the essential information. * Perfect! The frontend builds successfully. ## Summary I've updated the NormalizedConversationViewer to render terminal commands with a monospace font. Now: ### Changes Made 1. **Added `getContentClassName` function** - This function conditionally applies styling based on the entry type 2. **Applied monospace font for commands** - When the entry type is a tool_use with action_type of "command_run", it applies the `font-mono` Tailwind class 3. **Maintained existing styling** - All other entry types keep the same styling as before ### Result Now terminal commands like: - `npm run build` - `cargo check` - `git status` - `ls -la` Will be displayed in a monospace font next to the terminal icon, making them more readable and clearly distinguishable as code/commands, while other content like file paths, search queries, and regular text continue to use the default font. The monospace font makes commands much easier to read and gives them the appropriate technical appearance that users expect for terminal output. * Excellent! Everything builds successfully. ## Summary I've implemented real-time conversation updates with smart auto-scrolling functionality. Here's what was added: ### Key Features 1. **Auto-refresh**: The conversation automatically polls for updates every 2 seconds when the execution process is running 2. **Smart auto-scrolling**: Automatically scrolls to the bottom when new content arrives 3. **User scroll detection**: Stops auto-scrolling when the user manually scrolls up 4. **Auto-scroll resumption**: Resumes auto-scrolling when the user scrolls back to the bottom 5. **Efficient updates**: Only updates the conversation state when content actually changes ### Implementation Details **Auto-refresh Logic:** - Polls every 2 seconds when `executionProcess.status === 'running'` - Uses efficient content comparison to avoid unnecessary re-renders - Gracefully handles polling errors without disrupting the UI **Smart Scrolling:** - Tracks user scroll behavior vs automatic scrolling - Uses a 5px threshold to detect "at bottom" state - Provides smooth auto-scrolling with a small delay to ensure DOM updates **User Experience:** - Container has `max-h-96` with `overflow-y-auto` for scrollable content - Terminal commands display in monospace font - Clean display with just icons and concise content - No disruption when user wants to review previous logs ### Behavior - ✅ **Auto-updates**: Content refreshes every 2 seconds during execution - ✅ **Auto-scroll**: New content automatically scrolls into view - ✅ **Manual control**: User can scroll up to review previous logs - ✅ **Resume auto-scroll**: When user scrolls back to bottom, auto-scrolling resumes - ✅ **Efficient**: Only re-renders when content actually changes - ✅ **Clean UI**: Terminal commands in monospace, no redundant headers The conversation viewer now provides a seamless, real-time experience that follows the execution while respecting user control over scrolling behavior. * ## Summary I've successfully fixed the scroll-within-scroll issue in the TaskDetailsPanel. Here's what was changed: **Problem**: The normalized logs section had nested scrolling containers: - Parent container (TaskDetailsPanel) with `h-full overflow-y-auto` - Child container (NormalizedConversationViewer) with `max-h-96 overflow-y-auto` **Solution**: I removed the scrolling functionality from the `NormalizedConversationViewer` component by: 1. **Removed scroll container**: Changed from `<div ref={scrollContainerRef} className="space-y-2 max-h-96 overflow-y-auto" onScroll={handleScroll}>` to just `<div className="space-y-2">` 2. **Cleaned up scroll-related code**: Removed: - State variables: `isUserScrolling`, `scrollContainerRef`, `scrollTimeoutRef`, `lastScrollTop` - Functions: `isAtBottom`, `scrollToBottom`, `handleScroll` - Effects: Auto-scroll on conversation updates and scroll timeout cleanup - Unused imports: `useRef` 3. **Verified functionality**: The parent container in TaskDetailsPanel now handles all scrolling for the logs section, eliminating the annoying nested scroll behavior. The build and lint checks pass successfully, and the user experience should now be much smoother without the competing scroll areas. * ## Summary I've successfully fixed the scroll-within-scroll issue while preserving the auto-scroll functionality. Here's what I implemented: **Problem**: Nested scroll containers created annoying scroll-within-scroll behavior: - Parent: TaskDetailsPanel with `h-full overflow-y-auto` - Child: NormalizedConversationViewer with `max-h-96 overflow-y-auto` **Solution**: Moved all scroll logic to the parent container while maintaining auto-scroll behavior: ### Changes Made: 1. **Removed inner scroll container** from NormalizedConversationViewer: - Removed `max-h-96 overflow-y-auto` classes - Removed all scroll-related state and functions - Simplified to just `<div className="space-y-2">` 2. **Added callback interface** to NormalizedConversationViewer: - Added `onConversationUpdate?: () => void` prop - Called this callback when conversation data changes - Used `setTimeout` to ensure state updates happen before auto-scroll 3. **Enhanced TaskDetailsPanel scroll logic**: - Added `conversationUpdateTrigger` state to track conversation changes - Added `handleConversationUpdate` callback function - Extended existing auto-scroll effect to include conversation updates - Maintained existing manual scroll detection logic ### Key Benefits: ✅ **No more nested scrolling** - Only the parent container scrolls ✅ **Auto-scroll preserved** - New messages still auto-scroll to bottom ✅ **Manual scroll respected** - Auto-scroll stops when user manually scrolls up ✅ **Smart resumption** - Auto-scroll resumes when user scrolls back to bottom ✅ **Seamless integration** - Works with existing activity and process log auto-scroll The solution maintains all existing functionality while providing a much better user experience by eliminating the competing scroll areas. * ## Summary I've successfully updated the task attempts diff endpoint to include unstaged changes in addition to the existing committed changes. Here's what was implemented: ### Key Changes Made: 1. **Enhanced `get_diff` method** in [`backend/src/models/task_attempt.rs`](file:///private/var/folders/kr/jdxkcn7129j376nrg0stj9zm0000gn/T/vk-4fbf-update-dif/backend/src/models/task_attempt.rs#L1042-L1379): - Added logic to capture unstaged changes using `diff_tree_to_workdir_with_index` - For files with both committed and unstaged changes, creates a combined diff from the base branch to the current working directory - For files with only unstaged changes, generates a standard diff 2. **New helper function** `process_unstaged_file`: - Handles the processing of individual unstaged files - Manages the complex logic of combining committed and unstaged changes - Uses Git's native patch generation for accurate diff representation ### How It Works: **For merged task attempts:** Shows the original merge commit diff (unchanged behavior) **For active task attempts:** 1. **First pass:** Generates diff from base branch to current HEAD commit (committed changes) 2. **Second pass:** Finds files with unstaged changes in the working directory 3. **Combining logic:** - **Files with both committed & unstaged changes:** Creates a combined diff from base branch directly to working directory content - **Files with only unstaged changes:** Adds them as separate diff entries - **Files with only committed changes:** Keeps original diff (unchanged) ### Benefits: - ✅ **Complete visibility:** Users can now see both committed and uncommitted work - ✅ **Unified view:** All changes are presented in a single coherent diff - ✅ **Backward compatible:** Existing functionality for merged attempts remains unchanged - ✅ **Accurate representation:** Uses Git's native diff algorithms for consistent formatting The implementation maintains the existing API structure while extending functionality to provide a more comprehensive view of all changes in a task attempt. * Perfect! I have successfully implemented the dynamic task details section that updates based on execution state. Here's a summary of what was accomplished: ## Summary I implemented a comprehensive solution to make the details section dynamically update based on the execution state: ### Backend Changes: 1. **Added new execution state types** in `backend/src/models/task_attempt.rs`: - `ExecutionState` enum with states: NotStarted, SetupRunning, SetupComplete, SetupFailed, CodingAgentRunning, CodingAgentComplete, CodingAgentFailed, Complete - `TaskAttemptState` struct containing execution state, change detection, and process IDs 2. **Created `get_execution_state` method** that analyzes: - Project setup script configuration - Running execution processes - Process status and completion - Whether changes have been made to the worktree 3. **Added new API endpoint** `GET /projects/:project_id/tasks/:task_id/attempts/:attempt_id` to fetch execution state 4. **Updated type generation** to include the new types in the shared TypeScript definitions ### Frontend Changes: 1. **Enhanced useTaskDetails hook** to: - Poll the execution state endpoint every 2 seconds - Fetch execution state when switching attempts - Provide execution state data to components 2. **Completely redesigned TaskDetailsPanel** with dynamic content rendering: - **Setup Script Running**: Shows loading spinner with "Setup Script Running" message - **Setup Failed**: Shows error message - **Coding Agent Running (no changes)**: Shows full-height agent conversation only - **Changes Available**: Shows 2/3 changes + 1/3 conversation split view - **Default**: Shows "execution not started" message ### Key Features: - **Real-time Updates**: Polls execution state every 2 seconds during execution - **Progressive Disclosure**: Shows appropriate content based on execution phase - **State-Aware UI**: Different layouts for different execution states - **Error Handling**: Proper error states for failed setup scripts - **Type Safety**: Full TypeScript support for execution states The implementation ensures that users see relevant information at each stage of task execution, providing better visibility into what's happening and reducing confusion about the current state. * Perfect! The fix is now in place. Here's what I've done to solve the loading spinner issue: ## Fix Summary The problem was that the execution state was only being fetched during: 1. Polling (when `isAttemptRunning` is true) 2. Manual attempt switching via `handleAttemptChange` But it was **not** being fetched during the initial page load when an attempt was automatically selected. ## Changes Made 1. **Added useEffect for selectedAttempt changes**: This ensures that whenever `selectedAttempt` changes (including during initial load), both `fetchAttemptData` and `fetchExecutionState` are called. 2. **Updated fetchTaskAttempts**: Added `fetchExecutionState` call when setting the latest attempt during initial load, and included it in the dependency array. ## How the Fix Works Now when the page reloads: 1. `fetchTaskAttempts` runs and finds the latest attempt 2. It sets `selectedAttempt` to the latest attempt 3. The new useEffect detects the `selectedAttempt` change and immediately calls both: - `fetchAttemptData(selectedAttempt.id)` - `fetchExecutionState(selectedAttempt.id)` 4. The execution state is loaded, so the appropriate content is shown instead of the loading spinner This ensures that the execution state is always available when displaying attempt details, whether it's the initial load, manual switching between attempts, or during polling updates. * Perfect! The changes have been successfully implemented. Here's a summary of what I've done: ## Changes Made ### 1. Setup Script Stdio Display - **Modified the setup running state** to show the actual stdout/stderr of the setup script instead of just a spinner - **Enhanced process lookup** to find the setup script execution process from either the execution state's `setup_process_id` or by searching for processes with type `setupscript` - **Added terminal-style output display** with: - Black background and green text (terminal aesthetic) - Monospace font for proper formatting - Scrollable area with max height - Fallback to "No output yet..." when no output is available ### 2. Diff Refresh During Coding Agent Execution - **Added automatic diff polling** when the coding agent is running - **Polls every 3 seconds** during `CodingAgentRunning` state to catch file changes as they happen - **Uses existing fetchDiff function** to maintain consistency with manual refresh behavior ### 3. Enhanced Process Data Fetching - **Modified fetchAttemptData** to always fetch setup script process details when available - **Ensures setup script output is available** even when the script has completed but we want to show its output - **Maintains existing logic** for other running processes while adding setup script support ## Key Features 1. **Real-time Setup Script Output**: Users can now see exactly what the setup script is doing, including any errors or progress messages. 2. **Live Diff Updates**: When the coding agent is making changes, the diff view automatically refreshes every 3 seconds so users can see files being modified in real-time. 3. **Better Visual Feedback**: The terminal-style output for setup scripts provides a familiar development experience. 4. **Non-blocking Updates**: The diff refresh happens independently and doesn't interfere with other UI interactions. The implementation ensures that users get immediate feedback during both phases of execution - setup and coding - making the development process much more transparent and engaging. * Perfect! Both issues have been fixed: ## Summary of Fixes ### 1. Setup Script Output Display **Fixed**: Combined stdout and stderr properly - **Before**: Only showed stdout OR stderr (whichever existed first) - **After**: Shows both stdout AND stderr concatenated together - **Implementation**: ```javascript const stdout = setupProcess.stdout || ''; const stderr = setupProcess.stderr || ''; const combined = [stdout, stderr].filter(Boolean).join('\n'); return combined || 'No output yet...'; ``` ### 2. Automatic Diff Refresh During Coding Agent Execution **Fixed**: Added proper diff polling with immediate refresh - **Before**: Diff wasn't automatically updating during coding agent execution - **After**: Diff refreshes immediately when coding agent starts + every 2 seconds while running - **Implementation**: - Immediate `fetchDiff()` call when entering `CodingAgentRunning` state - `setInterval` to refresh every 2 seconds during execution - Proper cleanup when state changes or component unmounts ### 3. Enhanced Setup Process Data Fetching **Improved**: Better process data availability - **Enhancement**: Modified `fetchAttemptData` to always fetch setup script process details - **Benefit**: Ensures setup script output is available even after completion - **Implementation**: Added dedicated setup script process fetching logic ## Key Improvements 1. **Real-time Setup Feedback**: Users can now see the complete output (both stdout and stderr) from setup scripts as they run 2. **Live Diff Updates**: File changes appear automatically every 2 seconds during coding agent execution 3. **Immediate Feedback**: Diff refreshes immediately when coding agent starts, then continues polling 4. **Better Error Visibility**: Setup script errors (stderr) are now visible alongside normal output The implementation ensures that users get comprehensive, real-time feedback during both setup and coding phases, making the development process much more transparent and responsive. * The styles have been cleaned up: 1. **Fixed the "No logs available" message**: Changed "No output yet..." to "Waiting for setup script output..." to indicate this is a loading state rather than an error. 2. **Simplified setup script display**: Removed the terminal UI styling including: - The loading spinner and centered layout - The bordered card wrapper - The "Setup Script Output" header - The black terminal background with green text - Applied simple monospaced font styling similar to normalized logs The setup script now displays with a cleaner, more consistent style that matches the rest of the interface while still being clearly readable with monospaced font. * Added auto-scroll functionality to the setup script section: 1. **Added setup scroll ref**: Created `setupScrollRef` to track the setup script container 2. **Added auto-scroll effect**: Created a `useEffect` that monitors `attemptData.runningProcessDetails` and automatically scrolls to the bottom when the setup script output updates 3. **Applied ref to container**: Added the ref to the setup script container div The setup script logs will now automatically scroll to the bottom as new output is received, matching the behavior of the normalized logs. * Perfect! I've successfully implemented the follow up executor visualization in the TaskDetailsPanel. Here's what I did: ## Summary of Changes 1. **Identified follow up executor data structure**: Follow up executors are identified by having `process_type: "codingagent"` and `command: "followup_executor"` (vs main executor with `command: "executor"`) 2. **Modified TaskDetailsPanel logic**: Updated both the full-screen view (when no changes) and the split view (when changes are present) to: - Find the main coding agent process (command: "executor") - Find all follow up executor processes (command: "followup_executor") - Display them in sequence with the main executor first, followed by follow up executors 3. **Enhanced UI presentation**: Each follow up executor is displayed with: - A clear separator (border-top) - A header showing "Follow-up #X" with the sequence number - The start time of the follow up executor - The normalized conversation viewer for that executor's logs 4. **Tested the implementation**: Both frontend and backend build successfully, and the code passes linting checks. The implementation now properly handles and visualizes follow up executors by showing them under the main executor in chronological order, making it clear which conversation belongs to which executor while maintaining the existing functionality for the main coding agent. * ## Issue Fixed! I found and fixed the bug. The problem was in the TaskDetailsPanel logic that determines when to show the conversation logs vs. the fallback "Task execution not started yet" message. ### Root Cause The condition `if (isCodingAgentRunning && !hasChanges)` only handled the case when the coding agent was *running*, but after follow up executors complete, the execution state becomes `CodingAgentComplete`. This caused the logic to fall through to the default case, showing "Task execution not started yet" instead of the conversation logs. ### Fix Applied I modified the condition to also handle the completed state: - Added `isCodingAgentComplete` variable to track when execution is complete - Updated the condition to `if ((isCodingAgentRunning || isCodingAgentComplete) && !hasChanges)` This ensures that both running and completed follow up executors will properly display their conversation logs, whether they're still running or have finished execution. The fix is minimal and targeted, only affecting the specific scenario where follow up executors complete without generating file changes, while preserving all other functionality. * ## Perfect! All styling changes implemented successfully! Here's a summary of what I've accomplished: ### ✅ Backend Changes 1. **Extended NormalizedConversation structure** to include `prompt` and `summary` fields 2. **Updated all executor implementations** (Claude, Amp, default) to support the new fields 3. **Modified the normalized-logs API endpoint** to fetch executor session data and include prompt/summary in the response 4. **Regenerated TypeScript types** to reflect the new structure ### ✅ Frontend Changes 1. **Added prompt display** above the normalized logs with a distinctive blue styling and MessageSquare icon 2. **Implemented horizontal dividers** between all log sections: - Between prompt and conversation logs - Between main executor and follow-up executors - Between multiple follow-up executors 3. **Removed the "Follow-up #1 Started:" headers** for a cleaner interface 4. **Updated the layout** to use proper spacing and consistent divider styling ### 🎨 UI Improvements - **Prompts are displayed** in a blue-themed box with monospace font for better readability - **Horizontal lines** consistently separate each logical section (prompt → executor → follow-up prompt → follow-up executor) - **Clean, streamlined appearance** without verbose headers - **Consistent spacing** and visual hierarchy throughout The implementation properly handles cases where: - Prompts may or may not be available - There are multiple follow-up executors - There are no follow-up executors - The main executor completes with or without follow-ups All builds pass and the code maintains the existing functionality while adding the requested visual improvements! * ## ✅ Styling Updates Complete! I've successfully implemented all the requested styling changes: ### 🔨 **Updated Prompt Display** - **Changed icon** from MessageSquare to **Hammer** with orange color (`text-orange-600`) - **Removed blue box styling** - no more background, border, or rounded corners - **Removed monospaced font** - now uses normal text styling with `text-sm` and `text-foreground` - **Maintains whitespace-pre-wrap** to preserve formatting without the monospace appearance ### 📏 **Improved Spacing** - **Increased padding** at the bottom of the horizontal divider from `mb-4` to `mb-6` - This creates **better visual separation** between the user message (prompt) and the agent logs - **Maintains consistent spacing** throughout the component ### 🎨 **Clean Visual Hierarchy** - User prompts now appear as **clean, readable text** with a hammer icon - **Horizontal dividers** provide clear separation between sections - **Proper padding** ensures comfortable reading experience - **Consistent with the overall UI theme** rather than standing out with special styling The changes maintain all existing functionality while providing the cleaner, more integrated visual appearance you requested. The prompt now blends naturally with the rest of the conversation while still being clearly distinguished by the hammer icon and horizontal divider! * ## ✅ Styling Fixes Applied! I've successfully implemented both requested changes: ### 🔨 **Blue Hammer Icon** - Changed the hammer icon color from `text-orange-600` to `text-blue-600` - Now matches the blue theme you requested ### 📏 **Fixed Spacing Gap** - **Removed the bottom margin** from the horizontal divider (`mb-6` removed) - **Added conditional top margin** to the conversation entries container (`mt-6` when prompt exists) - This creates the **proper gap between the divider and the normalized logs** ### 🎨 **How the spacing now works:** 1. **User prompt** with hammer icon 2. **Horizontal divider** (no bottom margin) 3. **6-unit gap** (via `mt-6` on conversation container) 4. **Normalized logs/conversation entries** The spacing is now properly balanced with a clean visual separation between the user message and the agent logs, while the blue hammer icon provides a cohesive color scheme throughout the interface! * ## ✅ Spacing Fixed! I've corrected the spacing issue by: ### 📏 **Fixed the Gap** - **Added `mb-6` to the horizontal divider** - this creates the proper 6-unit gap below the divider - **Removed the conditional margin logic** from the conversation entries container - it was causing the spacing to not work properly - **Simplified the structure** for more predictable spacing behavior ### 🎯 **Now the spacing flow is:** 1. **User message** (with hammer icon) 2. **Gap** (via `mb-4` on user message container) 3. **Horizontal divider** 4. **Gap** (via `mb-6` on horizontal divider) ← **This was missing before!** 5. **Normalized logs/conversation entries** The spacing should now be exactly what you requested - proper space both above and below the horizontal divider! * ## ✅ Spacing Finally Fixed! I've resolved the `space-y-0` override issue by **restructuring the layout**: ### 🔧 **What was wrong:** - The `space-y-0` class creates CSS rule `.space-y-0 > :not([hidden]) ~ :not([hidden])` that sets `margin-top: 0` and `margin-bottom: 0` on all sibling elements - This was overriding the `mb-6` class on the horizontal divider ### 🎯 **How I fixed it:** 1. **Removed `space-y-0` class** from the outer container 2. **Moved the horizontal divider outside** the prompt section to its own top-level element 3. **Made the structure flat** so no spacing utility classes conflict with each other ### 📏 **New structure:** ```jsx <div> // No space-y-0 class {/* User prompt */} <div className="mb-4">...</div> // Space below prompt {/* Horizontal divider */} <div className="mb-6">...</div> // Space below divider - no override! {/* Conversation entries */} <div className="space-y-2">...</div> // Only affects entries </div> ``` Now the `mb-6` on the horizontal divider won't be overridden, and you should see the proper gap between the divider and the normalized logs! * ## ✅ Loading Message Fixed! I've resolved the misleading "No logs available" message by improving the state logic: ### 🔧 **What was wrong:** - When a follow-up execution starts, the API call completes successfully but returns no conversation data yet - The component would show "No conversation data available" even though the process was still running and would eventually produce logs ### 🎯 **How I fixed it:** - **Added execution process status check** - when `executionProcess.status === 'running'` and there's no conversation data - **Shows "Waiting for logs..."** instead of "No conversation data available" - **Maintains proper error state** for truly failed or empty completed processes ### 📱 **New behavior:** - **When follow-up starts**: Shows "Waiting for logs..." ✅ - **During execution**: Shows "Waiting for logs..." ✅ - **When logs appear**: Shows the actual conversation ✅ - **When execution completes with no logs**: Shows "No conversation data available" ✅ - **On actual errors**: Shows the error message ✅ Now users will see a proper loading state that indicates the system is working, rather than an error-like message that suggests something went wrong! * ## ✅ "No logs available" Message Fixed! I've resolved the misleading error message by fixing the root cause in the backend: ### 🔧 **What was wrong:** - When a follow-up execution starts, `process.stdout` is `None` because logs haven't been generated yet - The backend was returning `success: false` with "No logs available for this execution process" - The frontend was showing this as an error message ### 🎯 **How I fixed it:** 1. **Added status check in the backend** - when `process.status == ExecutionProcessStatus::Running` and `stdout` is `None` 2. **Return success with empty conversation** instead of an error 3. **Include executor session data** (prompt/summary) even for running processes without logs yet 4. **Maintain error state** only for truly failed or completed processes with no logs ### 📱 **New behavior:** - **When follow-up starts**: Backend returns empty conversation with `success: true` ✅ - **Frontend shows**: "Waiting for logs..." (from previous fix) ✅ - **When logs appear**: Shows actual conversation data ✅ - **When process fails**: Still shows proper error messages ✅ - **When completed with no logs**: Shows "No conversation data available" ✅ Now when you start a follow-up, you should see "Waiting for logs..." instead of the misleading "No logs available for this execution process" error message! * ## ✅ Spacing System Refactored! I've completely refactored the spacing system for a much cleaner and more predictable layout: ### 🏗️ **New Systematic Approach** #### **NormalizedConversationViewer (Internal Spacing):** - **Prompt**: `mb-6` creates consistent gap to conversation entries - **Conversation entries**: `space-y-2` between each entry - **No internal dividers** - keeps the component focused on its own content #### **TaskDetailsPanel (Executor Separation):** - **Container**: `space-y-8` creates consistent spacing between main sections - **Follow-up dividers**: `border-t` + `mb-8` for proper separation - **Clean structure** with predictable spacing ### 📏 **Spacing Flow Now:** 1. **Main executor prompt** 2. **6-unit gap** (prompt `mb-6`) 3. **Main executor conversation** 4. **8-unit gap** (container `space-y-8`) 5. **Horizontal divider** 6. **8-unit gap** (divider `mb-8`) 7. **Follow-up prompt** 8. **6-unit gap** (prompt `mb-6`) 9. **Follow-up conversation** 10. **8-unit gap** (for next follow-up if any) ### 🎯 **Benefits:** - **Consistent spacing** throughout all states - **No more conflicting CSS rules** or override issues - **Systematic approach** that's easy to maintain and debug - **Proper separation** between logical sections - **Clean, readable layout** with predictable gaps The spacing should now be perfect in all scenarios - with or without prompts, with single or multiple follow-ups, and in both full-screen and split-view modes! * I've successfully improved the diff styling to be more compact and fit better within the sidebar. Here are the key changes made: **Spacing Improvements:** - Reduced spacing between diff files from `space-y-6` to `space-y-3` - Reduced main container padding from `p-6` to `p-4` - Reduced file header padding from `py-2` to `py-1.5` **Line Compactness:** - Reduced diff line height from `min-h-[1.75rem]` to `min-h-[1.25rem]` - Reduced line number column width from `w-16` to `w-12` - Reduced line number padding from `px-2` to `px-1.5` - Reduced individual line number widths from `w-6` to `w-5` - Reduced line content padding from `px-3` to `px-2` **Expand/Collapse Buttons:** - Reduced expand button height from `h-8` to `h-6` These changes make the diff view significantly more compact while maintaining readability. The diff will now display more content in the same space, making better use of the sidebar real estate. The frontend builds successfully with these changes. * Perfect! The migration is complete. Let me summarize what I've done: I've successfully migrated the merge, rebase, and PR functionality from the old `task-attempt-compare.tsx` page to the `TaskDetailsToolbar.tsx` component and deleted the old page. 1. **Added to TaskDetailsToolbar.tsx:** - Branch status fetching with `fetchBranchStatus` function - Merge functionality with uncommitted changes warning - Rebase functionality - Create PR functionality with dialog - Branch status display showing commits ahead/behind and uncommitted changes - Git operation buttons (Merge, Rebase, Create PR) with proper enabling/disabling logic - Two dialog components for warnings and PR creation 2. **Deleted:** - `frontend/src/pages/task-attempt-compare.tsx` - The entire compare page 3. **Updated routing:** - Removed the compare page route from `App.tsx` - Removed the import for `TaskAttemptComparePage` - Updated keyboard shortcuts to remove compare page navigation logic - Removed the "Changes" button that linked to the old compare page 4. **Cleaned up imports:** - Removed unused imports like `Link` from react-router-dom and `GitCompare` icon The diff view functionality remains in the `TaskDetailsPanel.tsx` where it was already migrated, and now users can access merge, rebase, and PR creation directly from the toolbar without needing a separate page. The branch status is also prominently displayed in the toolbar so users can see the current state at a glance. * Perfect! Now the merge, rebase, and PR buttons will be disabled when an attempt is running, preventing users from performing git operations while code is being executed. * Cargo fmt * Clippy * Prettier * Cleanup * Clippy
This commit is contained in:
committed by
GitHub
parent
e5b7dd8e7a
commit
95034fab77
@@ -112,6 +112,8 @@ fn main() {
|
||||
vibe_kanban::models::task_attempt::FileDiff::decl(),
|
||||
vibe_kanban::models::task_attempt::WorktreeDiff::decl(),
|
||||
vibe_kanban::models::task_attempt::BranchStatus::decl(),
|
||||
vibe_kanban::models::task_attempt::ExecutionState::decl(),
|
||||
vibe_kanban::models::task_attempt::TaskAttemptState::decl(),
|
||||
vibe_kanban::models::execution_process::ExecutionProcess::decl(),
|
||||
vibe_kanban::models::execution_process::ExecutionProcessSummary::decl(),
|
||||
vibe_kanban::models::execution_process::ExecutionProcessStatus::decl(),
|
||||
@@ -121,6 +123,10 @@ fn main() {
|
||||
vibe_kanban::models::executor_session::ExecutorSession::decl(),
|
||||
vibe_kanban::models::executor_session::CreateExecutorSession::decl(),
|
||||
vibe_kanban::models::executor_session::UpdateExecutorSession::decl(),
|
||||
vibe_kanban::executor::NormalizedConversation::decl(),
|
||||
vibe_kanban::executor::NormalizedEntry::decl(),
|
||||
vibe_kanban::executor::NormalizedEntryType::decl(),
|
||||
vibe_kanban::executor::ActionType::decl(),
|
||||
];
|
||||
|
||||
// 4. Friendly banner
|
||||
|
||||
@@ -10,6 +10,57 @@ use crate::executors::{
|
||||
AmpExecutor, ClaudeExecutor, EchoExecutor, GeminiExecutor, OpencodeExecutor,
|
||||
};
|
||||
|
||||
/// Normalized conversation representation for different executor formats
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub struct NormalizedConversation {
|
||||
pub entries: Vec<NormalizedEntry>,
|
||||
pub session_id: Option<String>,
|
||||
pub executor_type: String,
|
||||
pub prompt: Option<String>,
|
||||
pub summary: Option<String>,
|
||||
}
|
||||
|
||||
/// Individual entry in a normalized conversation
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub struct NormalizedEntry {
|
||||
pub timestamp: Option<String>,
|
||||
pub entry_type: NormalizedEntryType,
|
||||
pub content: String,
|
||||
#[ts(skip)]
|
||||
pub metadata: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Types of entries in a normalized conversation
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
#[ts(export)]
|
||||
pub enum NormalizedEntryType {
|
||||
UserMessage,
|
||||
AssistantMessage,
|
||||
ToolUse {
|
||||
tool_name: String,
|
||||
action_type: ActionType,
|
||||
},
|
||||
SystemMessage,
|
||||
Thinking,
|
||||
}
|
||||
|
||||
/// Types of tool actions that can be performed
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[serde(tag = "action", rename_all = "snake_case")]
|
||||
#[ts(export)]
|
||||
pub enum ActionType {
|
||||
FileRead { path: String },
|
||||
FileWrite { path: String },
|
||||
CommandRun { command: String },
|
||||
Search { query: String },
|
||||
WebFetch { url: String },
|
||||
TaskCreate { description: String },
|
||||
Other { description: String },
|
||||
}
|
||||
|
||||
/// Context information for spawn failures to provide comprehensive error details
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SpawnContext {
|
||||
@@ -167,6 +218,18 @@ pub trait Executor: Send + Sync {
|
||||
worktree_path: &str,
|
||||
) -> Result<command_group::AsyncGroupChild, ExecutorError>;
|
||||
|
||||
/// Normalize executor logs into a standard format
|
||||
fn normalize_logs(&self, _logs: &str) -> Result<NormalizedConversation, String> {
|
||||
// Default implementation returns empty conversation
|
||||
Ok(NormalizedConversation {
|
||||
entries: vec![],
|
||||
session_id: None,
|
||||
executor_type: "unknown".to_string(),
|
||||
prompt: None,
|
||||
summary: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute the command and stream output to database in real-time
|
||||
async fn execute_streaming(
|
||||
&self,
|
||||
|
||||
112
backend/src/executor_tests.rs
Normal file
112
backend/src/executor_tests.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
executor::{Executor, NormalizedEntryType},
|
||||
executors::{AmpExecutor, ClaudeExecutor},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_amp_log_normalization() {
|
||||
let amp_executor = AmpExecutor;
|
||||
let amp_logs = r#"{"type":"initial","threadID":"T-f8f7fec0-b330-47ab-b63a-b72c42f1ef6a"}
|
||||
{"type":"messages","messages":[[0,{"role":"user","content":[{"type":"text","text":"Task title: Create and start should open task\nTask description: When I press 'create & start' on task creation dialog it should then open the task in the sidebar"}],"meta":{"sentAt":1751544747623}}]],"toolResults":[]}
|
||||
{"type":"messages","messages":[[1,{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants to implement a feature where pressing \"create & start\" on the task creation dialog should open the task in the sidebar."},{"type":"text","text":"I'll help you implement the \"create & start\" functionality. Let me explore the codebase to understand the current task creation and sidebar structure."},{"type":"tool_use","id":"toolu_01FQqskzGAhZaZu8H6qSs5pV","name":"todo_write","input":{"todos":[{"id":"1","content":"Explore task creation dialog component","status":"todo","priority":"high"}]}}],"state":{"type":"complete","stopReason":"tool_use"}}]],"toolResults":[]}"#;
|
||||
|
||||
let result = amp_executor.normalize_logs(amp_logs).unwrap();
|
||||
|
||||
assert_eq!(result.executor_type, "amp");
|
||||
assert_eq!(
|
||||
result.session_id,
|
||||
Some("T-f8f7fec0-b330-47ab-b63a-b72c42f1ef6a".to_string())
|
||||
);
|
||||
assert!(!result.entries.is_empty());
|
||||
|
||||
// Check that we have user message, assistant message, thinking, and tool use entries
|
||||
let user_messages: Vec<_> = result
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| matches!(e.entry_type, NormalizedEntryType::UserMessage))
|
||||
.collect();
|
||||
assert!(!user_messages.is_empty());
|
||||
|
||||
let assistant_messages: Vec<_> = result
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| matches!(e.entry_type, NormalizedEntryType::AssistantMessage))
|
||||
.collect();
|
||||
assert!(!assistant_messages.is_empty());
|
||||
|
||||
let thinking_entries: Vec<_> = result
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| matches!(e.entry_type, NormalizedEntryType::Thinking))
|
||||
.collect();
|
||||
assert!(!thinking_entries.is_empty());
|
||||
|
||||
let tool_uses: Vec<_> = result
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| matches!(e.entry_type, NormalizedEntryType::ToolUse { .. }))
|
||||
.collect();
|
||||
assert!(!tool_uses.is_empty());
|
||||
|
||||
// Check that tool use content is concise (not the old verbose format)
|
||||
let todo_tool_use = tool_uses.iter().find(|e| match &e.entry_type {
|
||||
NormalizedEntryType::ToolUse { tool_name, .. } => tool_name == "todo_write",
|
||||
_ => false,
|
||||
});
|
||||
assert!(todo_tool_use.is_some());
|
||||
let todo_tool_use = todo_tool_use.unwrap();
|
||||
// Should be concise, not "Tool: todo_write with input: ..."
|
||||
assert_eq!(todo_tool_use.content, "Managing TODO list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_claude_log_normalization() {
|
||||
let claude_executor = ClaudeExecutor;
|
||||
let claude_logs = r#"{"type":"system","subtype":"init","cwd":"/private/tmp/mission-control-worktree-8ff34214-7bb4-4a5a-9f47-bfdf79e20368","session_id":"499dcce4-04aa-4a3e-9e0c-ea0228fa87c9","tools":["Task","Bash","Glob","Grep","LS","exit_plan_mode","Read","Edit","MultiEdit","Write","NotebookRead","NotebookEdit","WebFetch","TodoRead","TodoWrite","WebSearch"],"mcp_servers":[],"model":"claude-sonnet-4-20250514","permissionMode":"bypassPermissions","apiKeySource":"none"}
|
||||
{"type":"assistant","message":{"id":"msg_014xUHgkAhs6cRx5WVT3s7if","type":"message","role":"assistant","model":"claude-sonnet-4-20250514","content":[{"type":"text","text":"I'll help you list your projects using vibe-kanban. Let me first explore the codebase to understand how vibe-kanban works and find your projects."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":4,"cache_creation_input_tokens":13497,"cache_read_input_tokens":0,"output_tokens":1,"service_tier":"standard"}},"parent_tool_use_id":null,"session_id":"499dcce4-04aa-4a3e-9e0c-ea0228fa87c9"}
|
||||
{"type":"assistant","message":{"id":"msg_014xUHgkAhs6cRx5WVT3s7if","type":"message","role":"assistant","model":"claude-sonnet-4-20250514","content":[{"type":"tool_use","id":"toolu_01Br3TvXdmW6RPGpB5NihTHh","name":"Task","input":{"description":"Find vibe-kanban projects","prompt":"I need to find and list projects using vibe-kanban."}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":4,"cache_creation_input_tokens":13497,"cache_read_input_tokens":0,"output_tokens":1,"service_tier":"standard"}},"parent_tool_use_id":null,"session_id":"499dcce4-04aa-4a3e-9e0c-ea0228fa87c9"}"#;
|
||||
|
||||
let result = claude_executor.normalize_logs(claude_logs).unwrap();
|
||||
|
||||
assert_eq!(result.executor_type, "claude");
|
||||
assert_eq!(
|
||||
result.session_id,
|
||||
Some("499dcce4-04aa-4a3e-9e0c-ea0228fa87c9".to_string())
|
||||
);
|
||||
assert!(!result.entries.is_empty());
|
||||
|
||||
// Check that we have system, assistant message, and tool use entries
|
||||
let system_messages: Vec<_> = result
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| matches!(e.entry_type, NormalizedEntryType::SystemMessage))
|
||||
.collect();
|
||||
assert!(!system_messages.is_empty());
|
||||
|
||||
let assistant_messages: Vec<_> = result
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| matches!(e.entry_type, NormalizedEntryType::AssistantMessage))
|
||||
.collect();
|
||||
assert!(!assistant_messages.is_empty());
|
||||
|
||||
let tool_uses: Vec<_> = result
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| matches!(e.entry_type, NormalizedEntryType::ToolUse { .. }))
|
||||
.collect();
|
||||
assert!(!tool_uses.is_empty());
|
||||
|
||||
// Check that tool use content is concise (not the old verbose format)
|
||||
let task_tool_use = tool_uses.iter().find(|e| match &e.entry_type {
|
||||
NormalizedEntryType::ToolUse { tool_name, .. } => tool_name == "Task",
|
||||
_ => false,
|
||||
});
|
||||
assert!(task_tool_use.is_some());
|
||||
let task_tool_use = task_tool_use.unwrap();
|
||||
// Should be the task description, not "Tool: Task with input: ..."
|
||||
assert_eq!(task_tool_use.content, "Find vibe-kanban projects");
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,10 @@ use command_group::{AsyncCommandGroup, AsyncGroupChild};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
executor::{Executor, ExecutorError},
|
||||
executor::{
|
||||
ActionType, Executor, ExecutorError, NormalizedConversation, NormalizedEntry,
|
||||
NormalizedEntryType,
|
||||
},
|
||||
models::task::Task,
|
||||
utils::shell::get_shell_command,
|
||||
};
|
||||
@@ -73,6 +76,284 @@ impl Executor for AmpExecutor {
|
||||
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
fn normalize_logs(&self, logs: &str) -> Result<NormalizedConversation, String> {
|
||||
use serde_json::Value;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
let mut session_id = None;
|
||||
|
||||
for line in logs.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to parse as JSON
|
||||
let json: Value = serde_json::from_str(trimmed)
|
||||
.map_err(|e| format!("Failed to parse JSON: {}", e))?;
|
||||
|
||||
// Extract session ID (threadID in AMP)
|
||||
if session_id.is_none() {
|
||||
if let Some(thread_id) = json.get("threadID").and_then(|v| v.as_str()) {
|
||||
session_id = Some(thread_id.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// Process different message types
|
||||
if let Some(msg_type) = json.get("type").and_then(|t| t.as_str()) {
|
||||
if msg_type == "messages" {
|
||||
if let Some(messages) = json.get("messages").and_then(|m| m.as_array()) {
|
||||
for message_entry in messages {
|
||||
if let Some(message_data) =
|
||||
message_entry.as_array().and_then(|arr| arr.get(1))
|
||||
{
|
||||
if let Some(role) =
|
||||
message_data.get("role").and_then(|r| r.as_str())
|
||||
{
|
||||
if let Some(content) =
|
||||
message_data.get("content").and_then(|c| c.as_array())
|
||||
{
|
||||
for content_item in content {
|
||||
if let Some(content_type) =
|
||||
content_item.get("type").and_then(|t| t.as_str())
|
||||
{
|
||||
match content_type {
|
||||
"text" => {
|
||||
if let Some(text) = content_item
|
||||
.get("text")
|
||||
.and_then(|t| t.as_str())
|
||||
{
|
||||
let entry_type = match role {
|
||||
"user" => NormalizedEntryType::UserMessage,
|
||||
"assistant" => NormalizedEntryType::AssistantMessage,
|
||||
_ => continue,
|
||||
};
|
||||
entries.push(NormalizedEntry {
|
||||
timestamp: message_data
|
||||
.get("meta")
|
||||
.and_then(|m| m.get("sentAt"))
|
||||
.and_then(|s| s.as_u64())
|
||||
.map(|ts| ts.to_string()),
|
||||
entry_type,
|
||||
content: text.to_string(),
|
||||
metadata: Some(
|
||||
content_item.clone(),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
"thinking" => {
|
||||
if let Some(thinking) = content_item
|
||||
.get("thinking")
|
||||
.and_then(|t| t.as_str())
|
||||
{
|
||||
entries.push(NormalizedEntry {
|
||||
timestamp: None,
|
||||
entry_type:
|
||||
NormalizedEntryType::Thinking,
|
||||
content: thinking.to_string(),
|
||||
metadata: Some(
|
||||
content_item.clone(),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
"tool_use" => {
|
||||
if let Some(tool_name) = content_item
|
||||
.get("name")
|
||||
.and_then(|n| n.as_str())
|
||||
{
|
||||
let input = content_item
|
||||
.get("input")
|
||||
.unwrap_or(&Value::Null);
|
||||
let action_type = self
|
||||
.extract_action_type(
|
||||
tool_name, input,
|
||||
);
|
||||
let content = self
|
||||
.generate_concise_content(
|
||||
tool_name,
|
||||
input,
|
||||
&action_type,
|
||||
);
|
||||
|
||||
entries.push(NormalizedEntry {
|
||||
timestamp: None,
|
||||
entry_type:
|
||||
NormalizedEntryType::ToolUse {
|
||||
tool_name: tool_name
|
||||
.to_string(),
|
||||
action_type,
|
||||
},
|
||||
content,
|
||||
metadata: Some(
|
||||
content_item.clone(),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(NormalizedConversation {
|
||||
entries,
|
||||
session_id,
|
||||
executor_type: "amp".to_string(),
|
||||
prompt: None,
|
||||
summary: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl AmpExecutor {
|
||||
fn generate_concise_content(
|
||||
&self,
|
||||
tool_name: &str,
|
||||
input: &serde_json::Value,
|
||||
action_type: &ActionType,
|
||||
) -> String {
|
||||
match action_type {
|
||||
ActionType::FileRead { path } => path.clone(),
|
||||
ActionType::FileWrite { path } => path.clone(),
|
||||
ActionType::CommandRun { command } => command.clone(),
|
||||
ActionType::Search { query } => query.clone(),
|
||||
ActionType::WebFetch { url } => url.clone(),
|
||||
ActionType::TaskCreate { description } => description.clone(),
|
||||
ActionType::Other { description: _ } => {
|
||||
// For other tools, try to extract key information or fall back to tool name
|
||||
match tool_name.to_lowercase().as_str() {
|
||||
"todo_write" | "todo_read" => "Managing TODO list".to_string(),
|
||||
"list_directory" | "ls" => {
|
||||
if let Some(path) = input.get("path").and_then(|p| p.as_str()) {
|
||||
format!("List directory: {}", path)
|
||||
} else {
|
||||
"List directory".to_string()
|
||||
}
|
||||
}
|
||||
"codebase_search_agent" => {
|
||||
if let Some(query) = input.get("query").and_then(|q| q.as_str()) {
|
||||
format!("Search: {}", query)
|
||||
} else {
|
||||
"Codebase search".to_string()
|
||||
}
|
||||
}
|
||||
"glob" => {
|
||||
if let Some(pattern) = input.get("filePattern").and_then(|p| p.as_str()) {
|
||||
format!("File pattern: {}", pattern)
|
||||
} else {
|
||||
"File pattern search".to_string()
|
||||
}
|
||||
}
|
||||
_ => tool_name.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_action_type(&self, tool_name: &str, input: &serde_json::Value) -> ActionType {
|
||||
match tool_name.to_lowercase().as_str() {
|
||||
"read_file" | "read" => {
|
||||
if let Some(path) = input.get("path").and_then(|p| p.as_str()) {
|
||||
ActionType::FileRead {
|
||||
path: path.to_string(),
|
||||
}
|
||||
} else if let Some(file_path) = input.get("file_path").and_then(|p| p.as_str()) {
|
||||
ActionType::FileRead {
|
||||
path: file_path.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "File read operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"edit_file" | "write" | "create_file" => {
|
||||
if let Some(path) = input.get("path").and_then(|p| p.as_str()) {
|
||||
ActionType::FileWrite {
|
||||
path: path.to_string(),
|
||||
}
|
||||
} else if let Some(file_path) = input.get("file_path").and_then(|p| p.as_str()) {
|
||||
ActionType::FileWrite {
|
||||
path: file_path.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "File write operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"bash" | "run_command" => {
|
||||
if let Some(cmd) = input.get("cmd").and_then(|c| c.as_str()) {
|
||||
ActionType::CommandRun {
|
||||
command: cmd.to_string(),
|
||||
}
|
||||
} else if let Some(command) = input.get("command").and_then(|c| c.as_str()) {
|
||||
ActionType::CommandRun {
|
||||
command: command.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Command execution".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"grep" | "search" => {
|
||||
if let Some(pattern) = input.get("pattern").and_then(|p| p.as_str()) {
|
||||
ActionType::Search {
|
||||
query: pattern.to_string(),
|
||||
}
|
||||
} else if let Some(query) = input.get("query").and_then(|q| q.as_str()) {
|
||||
ActionType::Search {
|
||||
query: query.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Search operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"web_fetch" | "webfetch" => {
|
||||
if let Some(url) = input.get("url").and_then(|u| u.as_str()) {
|
||||
ActionType::WebFetch {
|
||||
url: url.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Web fetch operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"task" => {
|
||||
if let Some(description) = input.get("description").and_then(|d| d.as_str()) {
|
||||
ActionType::TaskCreate {
|
||||
description: description.to_string(),
|
||||
}
|
||||
} else if let Some(prompt) = input.get("prompt").and_then(|p| p.as_str()) {
|
||||
ActionType::TaskCreate {
|
||||
description: prompt.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Task creation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => ActionType::Other {
|
||||
description: format!("Tool: {}", tool_name),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -123,4 +404,10 @@ impl Executor for AmpFollowupExecutor {
|
||||
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
fn normalize_logs(&self, logs: &str) -> Result<NormalizedConversation, String> {
|
||||
// Reuse the same logic as the main AmpExecutor
|
||||
let main_executor = AmpExecutor;
|
||||
main_executor.normalize_logs(logs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,10 @@ use tokio::process::Command;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
executor::{Executor, ExecutorError},
|
||||
executor::{
|
||||
ActionType, Executor, ExecutorError, NormalizedConversation, NormalizedEntry,
|
||||
NormalizedEntryType,
|
||||
},
|
||||
models::task::Task,
|
||||
utils::shell::get_shell_command,
|
||||
};
|
||||
@@ -68,6 +71,277 @@ impl Executor for ClaudeExecutor {
|
||||
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
fn normalize_logs(&self, logs: &str) -> Result<NormalizedConversation, String> {
|
||||
use serde_json::Value;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
let mut session_id = None;
|
||||
|
||||
for line in logs.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to parse as JSON
|
||||
let json: Value = serde_json::from_str(trimmed)
|
||||
.map_err(|e| format!("Failed to parse JSON: {}", e))?;
|
||||
|
||||
// Extract session ID
|
||||
if session_id.is_none() {
|
||||
if let Some(sess_id) = json.get("session_id").and_then(|v| v.as_str()) {
|
||||
session_id = Some(sess_id.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// Process different message types
|
||||
if let Some(msg_type) = json.get("type").and_then(|t| t.as_str()) {
|
||||
match msg_type {
|
||||
"assistant" => {
|
||||
if let Some(message) = json.get("message") {
|
||||
if let Some(content) = message.get("content").and_then(|c| c.as_array())
|
||||
{
|
||||
for content_item in content {
|
||||
if let Some(content_type) =
|
||||
content_item.get("type").and_then(|t| t.as_str())
|
||||
{
|
||||
match content_type {
|
||||
"text" => {
|
||||
if let Some(text) = content_item
|
||||
.get("text")
|
||||
.and_then(|t| t.as_str())
|
||||
{
|
||||
entries.push(NormalizedEntry {
|
||||
timestamp: None,
|
||||
entry_type:
|
||||
NormalizedEntryType::AssistantMessage,
|
||||
content: text.to_string(),
|
||||
metadata: Some(content_item.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
"tool_use" => {
|
||||
if let Some(tool_name) = content_item
|
||||
.get("name")
|
||||
.and_then(|n| n.as_str())
|
||||
{
|
||||
let input = content_item
|
||||
.get("input")
|
||||
.unwrap_or(&Value::Null);
|
||||
let action_type =
|
||||
self.extract_action_type(tool_name, input);
|
||||
let content = self.generate_concise_content(
|
||||
tool_name,
|
||||
input,
|
||||
&action_type,
|
||||
);
|
||||
|
||||
entries.push(NormalizedEntry {
|
||||
timestamp: None,
|
||||
entry_type: NormalizedEntryType::ToolUse {
|
||||
tool_name: tool_name.to_string(),
|
||||
action_type,
|
||||
},
|
||||
content,
|
||||
metadata: Some(content_item.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"user" => {
|
||||
if let Some(message) = json.get("message") {
|
||||
if let Some(content) = message.get("content").and_then(|c| c.as_array())
|
||||
{
|
||||
for content_item in content {
|
||||
if let Some(content_type) =
|
||||
content_item.get("type").and_then(|t| t.as_str())
|
||||
{
|
||||
if content_type == "text" {
|
||||
if let Some(text) =
|
||||
content_item.get("text").and_then(|t| t.as_str())
|
||||
{
|
||||
entries.push(NormalizedEntry {
|
||||
timestamp: None,
|
||||
entry_type: NormalizedEntryType::UserMessage,
|
||||
content: text.to_string(),
|
||||
metadata: Some(content_item.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"system" => {
|
||||
if let Some(subtype) = json.get("subtype").and_then(|s| s.as_str()) {
|
||||
if subtype == "init" {
|
||||
entries.push(NormalizedEntry {
|
||||
timestamp: None,
|
||||
entry_type: NormalizedEntryType::SystemMessage,
|
||||
content: format!(
|
||||
"System initialized with model: {}",
|
||||
json.get("model")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("unknown")
|
||||
),
|
||||
metadata: Some(json.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(NormalizedConversation {
|
||||
entries,
|
||||
session_id,
|
||||
executor_type: "claude".to_string(),
|
||||
prompt: None,
|
||||
summary: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ClaudeExecutor {
|
||||
fn generate_concise_content(
|
||||
&self,
|
||||
tool_name: &str,
|
||||
input: &serde_json::Value,
|
||||
action_type: &ActionType,
|
||||
) -> String {
|
||||
match action_type {
|
||||
ActionType::FileRead { path } => path.clone(),
|
||||
ActionType::FileWrite { path } => path.clone(),
|
||||
ActionType::CommandRun { command } => command.clone(),
|
||||
ActionType::Search { query } => query.clone(),
|
||||
ActionType::WebFetch { url } => url.clone(),
|
||||
ActionType::TaskCreate { description } => description.clone(),
|
||||
ActionType::Other { description: _ } => {
|
||||
// For other tools, try to extract key information or fall back to tool name
|
||||
match tool_name.to_lowercase().as_str() {
|
||||
"todoread" | "todowrite" => "Managing TODO list".to_string(),
|
||||
"ls" => {
|
||||
if let Some(path) = input.get("path").and_then(|p| p.as_str()) {
|
||||
format!("List directory: {}", path)
|
||||
} else {
|
||||
"List directory".to_string()
|
||||
}
|
||||
}
|
||||
"codebase_search_agent" => {
|
||||
if let Some(query) = input.get("query").and_then(|q| q.as_str()) {
|
||||
format!("Search: {}", query)
|
||||
} else {
|
||||
"Codebase search".to_string()
|
||||
}
|
||||
}
|
||||
_ => tool_name.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_action_type(&self, tool_name: &str, input: &serde_json::Value) -> ActionType {
|
||||
match tool_name.to_lowercase().as_str() {
|
||||
"read" => {
|
||||
if let Some(file_path) = input.get("file_path").and_then(|p| p.as_str()) {
|
||||
ActionType::FileRead {
|
||||
path: file_path.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "File read operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"edit" | "write" | "multiedit" => {
|
||||
if let Some(file_path) = input.get("file_path").and_then(|p| p.as_str()) {
|
||||
ActionType::FileWrite {
|
||||
path: file_path.to_string(),
|
||||
}
|
||||
} else if let Some(path) = input.get("path").and_then(|p| p.as_str()) {
|
||||
ActionType::FileWrite {
|
||||
path: path.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "File write operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"bash" => {
|
||||
if let Some(command) = input.get("command").and_then(|c| c.as_str()) {
|
||||
ActionType::CommandRun {
|
||||
command: command.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Command execution".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"grep" => {
|
||||
if let Some(pattern) = input.get("pattern").and_then(|p| p.as_str()) {
|
||||
ActionType::Search {
|
||||
query: pattern.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Search operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"glob" => {
|
||||
if let Some(file_pattern) = input.get("filePattern").and_then(|p| p.as_str()) {
|
||||
ActionType::Search {
|
||||
query: file_pattern.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "File pattern search".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"webfetch" => {
|
||||
if let Some(url) = input.get("url").and_then(|u| u.as_str()) {
|
||||
ActionType::WebFetch {
|
||||
url: url.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Web fetch operation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
"task" => {
|
||||
if let Some(description) = input.get("description").and_then(|d| d.as_str()) {
|
||||
ActionType::TaskCreate {
|
||||
description: description.to_string(),
|
||||
}
|
||||
} else if let Some(prompt) = input.get("prompt").and_then(|p| p.as_str()) {
|
||||
ActionType::TaskCreate {
|
||||
description: prompt.to_string(),
|
||||
}
|
||||
} else {
|
||||
ActionType::Other {
|
||||
description: "Task creation".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => ActionType::Other {
|
||||
description: format!("Tool: {}", tool_name),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -109,4 +383,10 @@ impl Executor for ClaudeFollowupExecutor {
|
||||
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
fn normalize_logs(&self, logs: &str) -> Result<NormalizedConversation, String> {
|
||||
// Reuse the same logic as the main ClaudeExecutor
|
||||
let main_executor = ClaudeExecutor;
|
||||
main_executor.normalize_logs(logs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ pub mod routes;
|
||||
pub mod services;
|
||||
pub mod utils;
|
||||
|
||||
#[cfg(test)]
|
||||
mod executor_tests;
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "../frontend/dist"]
|
||||
pub struct Assets;
|
||||
|
||||
@@ -148,6 +148,29 @@ pub struct BranchStatus {
|
||||
pub base_branch_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub enum ExecutionState {
|
||||
NotStarted,
|
||||
SetupRunning,
|
||||
SetupComplete,
|
||||
SetupFailed,
|
||||
CodingAgentRunning,
|
||||
CodingAgentComplete,
|
||||
CodingAgentFailed,
|
||||
Complete,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub struct TaskAttemptState {
|
||||
pub execution_state: ExecutionState,
|
||||
pub has_changes: bool,
|
||||
pub has_setup_script: bool,
|
||||
pub setup_process_id: Option<String>,
|
||||
pub coding_agent_process_id: Option<String>,
|
||||
}
|
||||
|
||||
impl TaskAttempt {
|
||||
pub async fn find_by_id(pool: &SqlitePool, id: Uuid) -> Result<Option<Self>, sqlx::Error> {
|
||||
sqlx::query_as!(
|
||||
@@ -1241,11 +1264,156 @@ impl TaskAttempt {
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
|
||||
// Now also get unstaged changes (working directory changes)
|
||||
let current_tree = worktree_repo.head()?.peel_to_tree()?;
|
||||
|
||||
// Create diff from HEAD to working directory for unstaged changes
|
||||
let mut unstaged_diff_opts = git2::DiffOptions::new();
|
||||
unstaged_diff_opts.context_lines(10);
|
||||
unstaged_diff_opts.interhunk_lines(0);
|
||||
unstaged_diff_opts.include_untracked(true); // Include untracked files
|
||||
|
||||
let unstaged_diff = worktree_repo.diff_tree_to_workdir_with_index(
|
||||
Some(¤t_tree),
|
||||
Some(&mut unstaged_diff_opts),
|
||||
)?;
|
||||
|
||||
// Process unstaged changes
|
||||
unstaged_diff.foreach(
|
||||
&mut |delta, _progress| {
|
||||
if let Some(path_str) = delta.new_file().path().and_then(|p| p.to_str()) {
|
||||
if let Err(e) = Self::process_unstaged_file(
|
||||
&mut files,
|
||||
&worktree_repo,
|
||||
base_oid,
|
||||
&attempt.worktree_path,
|
||||
path_str,
|
||||
&delta,
|
||||
) {
|
||||
eprintln!("Error processing unstaged file {}: {:?}", path_str, e);
|
||||
}
|
||||
}
|
||||
true
|
||||
},
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(WorktreeDiff { files })
|
||||
}
|
||||
|
||||
fn process_unstaged_file(
|
||||
files: &mut Vec<FileDiff>,
|
||||
worktree_repo: &Repository,
|
||||
base_oid: git2::Oid,
|
||||
worktree_path: &str,
|
||||
path_str: &str,
|
||||
delta: &git2::DiffDelta,
|
||||
) -> Result<(), TaskAttemptError> {
|
||||
let old_file = delta.old_file();
|
||||
let new_file = delta.new_file();
|
||||
|
||||
// Check if we already have a diff for this file from committed changes
|
||||
if let Some(existing_file) = files.iter_mut().find(|f| f.path == path_str) {
|
||||
// File already has committed changes, need to create a combined diff
|
||||
// from the base branch to the current working directory (including unstaged changes)
|
||||
|
||||
// Get the base content (from the fork point)
|
||||
let base_content = if let Ok(base_commit) = worktree_repo.find_commit(base_oid) {
|
||||
if let Ok(base_tree) = base_commit.tree() {
|
||||
match base_tree.get_path(std::path::Path::new(path_str)) {
|
||||
Ok(entry) => {
|
||||
if let Ok(blob) = worktree_repo.find_blob(entry.id()) {
|
||||
String::from_utf8_lossy(blob.content()).to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// Get the working directory content
|
||||
let working_content = if delta.status() != git2::Delta::Deleted {
|
||||
let file_path = std::path::Path::new(worktree_path).join(path_str);
|
||||
std::fs::read_to_string(&file_path).unwrap_or_default()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// Create a combined diff from base to working directory
|
||||
if base_content != working_content {
|
||||
// Use git's patch generation with the content directly
|
||||
let mut diff_opts = git2::DiffOptions::new();
|
||||
diff_opts.context_lines(10);
|
||||
diff_opts.interhunk_lines(0);
|
||||
|
||||
if let Ok(patch) = git2::Patch::from_buffers(
|
||||
base_content.as_bytes(),
|
||||
Some(std::path::Path::new(path_str)),
|
||||
working_content.as_bytes(),
|
||||
Some(std::path::Path::new(path_str)),
|
||||
Some(&mut diff_opts),
|
||||
) {
|
||||
let mut combined_chunks = Vec::new();
|
||||
|
||||
// Process the patch hunks
|
||||
for hunk_idx in 0..patch.num_hunks() {
|
||||
if let Ok((_hunk, hunk_lines)) = patch.hunk(hunk_idx) {
|
||||
// Process each line in the hunk
|
||||
for line_idx in 0..hunk_lines {
|
||||
if let Ok(line) = patch.line_in_hunk(hunk_idx, line_idx) {
|
||||
let content =
|
||||
String::from_utf8_lossy(line.content()).to_string();
|
||||
|
||||
let chunk_type = match line.origin() {
|
||||
' ' => DiffChunkType::Equal,
|
||||
'+' => DiffChunkType::Insert,
|
||||
'-' => DiffChunkType::Delete,
|
||||
_ => continue, // Skip other line types
|
||||
};
|
||||
|
||||
combined_chunks.push(DiffChunk {
|
||||
chunk_type,
|
||||
content,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !combined_chunks.is_empty() {
|
||||
existing_file.chunks = combined_chunks;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// File only has unstaged changes (new file or uncommitted changes only)
|
||||
match Self::generate_git_diff_chunks(worktree_repo, &old_file, &new_file, path_str) {
|
||||
Ok(diff_chunks) if !diff_chunks.is_empty() => {
|
||||
files.push(FileDiff {
|
||||
path: path_str.to_string(),
|
||||
chunks: diff_chunks,
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error generating unstaged diff for {}: {:?}", path_str, e);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generate diff chunks using Git's native diff algorithm
|
||||
pub fn generate_git_diff_chunks(
|
||||
repo: &Repository,
|
||||
@@ -1785,4 +1953,128 @@ impl TaskAttempt {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the current execution state for a task attempt
|
||||
pub async fn get_execution_state(
|
||||
pool: &SqlitePool,
|
||||
attempt_id: Uuid,
|
||||
task_id: Uuid,
|
||||
project_id: Uuid,
|
||||
) -> Result<TaskAttemptState, TaskAttemptError> {
|
||||
// Get the task attempt with validation
|
||||
let _attempt = sqlx::query_as!(
|
||||
TaskAttempt,
|
||||
r#"SELECT ta.id as "id!: Uuid", ta.task_id as "task_id!: Uuid", ta.worktree_path, ta.branch, ta.merge_commit, ta.executor, ta.pr_url, ta.pr_number, ta.pr_status, ta.pr_merged_at as "pr_merged_at: DateTime<Utc>", ta.created_at as "created_at!: DateTime<Utc>", ta.updated_at as "updated_at!: DateTime<Utc>"
|
||||
FROM task_attempts ta
|
||||
JOIN tasks t ON ta.task_id = t.id
|
||||
WHERE ta.id = $1 AND t.id = $2 AND t.project_id = $3"#,
|
||||
attempt_id,
|
||||
task_id,
|
||||
project_id
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.ok_or(TaskAttemptError::TaskNotFound)?;
|
||||
|
||||
// Get the project to check if it has a setup script
|
||||
let project = Project::find_by_id(pool, project_id)
|
||||
.await?
|
||||
.ok_or(TaskAttemptError::ProjectNotFound)?;
|
||||
|
||||
let has_setup_script = project
|
||||
.setup_script
|
||||
.as_ref()
|
||||
.map(|script| !script.trim().is_empty())
|
||||
.unwrap_or(false);
|
||||
|
||||
// Get all execution processes for this attempt, ordered by created_at
|
||||
let processes =
|
||||
crate::models::execution_process::ExecutionProcess::find_by_task_attempt_id(
|
||||
pool, attempt_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Find setup and coding agent processes
|
||||
let setup_process = processes.iter().find(|p| {
|
||||
matches!(
|
||||
p.process_type,
|
||||
crate::models::execution_process::ExecutionProcessType::SetupScript
|
||||
)
|
||||
});
|
||||
|
||||
let coding_agent_process = processes.iter().find(|p| {
|
||||
matches!(
|
||||
p.process_type,
|
||||
crate::models::execution_process::ExecutionProcessType::CodingAgent
|
||||
)
|
||||
});
|
||||
|
||||
// Determine execution state based on processes
|
||||
let execution_state = if let Some(setup) = setup_process {
|
||||
match setup.status {
|
||||
crate::models::execution_process::ExecutionProcessStatus::Running => {
|
||||
ExecutionState::SetupRunning
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Completed => {
|
||||
if let Some(agent) = coding_agent_process {
|
||||
match agent.status {
|
||||
crate::models::execution_process::ExecutionProcessStatus::Running => {
|
||||
ExecutionState::CodingAgentRunning
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Completed => {
|
||||
ExecutionState::CodingAgentComplete
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Failed => {
|
||||
ExecutionState::CodingAgentFailed
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Killed => {
|
||||
ExecutionState::CodingAgentFailed
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ExecutionState::SetupComplete
|
||||
}
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Failed => {
|
||||
ExecutionState::SetupFailed
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Killed => {
|
||||
ExecutionState::SetupFailed
|
||||
}
|
||||
}
|
||||
} else if let Some(agent) = coding_agent_process {
|
||||
// No setup script, only coding agent
|
||||
match agent.status {
|
||||
crate::models::execution_process::ExecutionProcessStatus::Running => {
|
||||
ExecutionState::CodingAgentRunning
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Completed => {
|
||||
ExecutionState::CodingAgentComplete
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Failed => {
|
||||
ExecutionState::CodingAgentFailed
|
||||
}
|
||||
crate::models::execution_process::ExecutionProcessStatus::Killed => {
|
||||
ExecutionState::CodingAgentFailed
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No processes started yet
|
||||
ExecutionState::NotStarted
|
||||
};
|
||||
|
||||
// Check if there are any changes (quick diff check)
|
||||
let has_changes = match Self::get_diff(pool, attempt_id, task_id, project_id).await {
|
||||
Ok(diff) => !diff.files.is_empty(),
|
||||
Err(_) => false, // If diff fails, assume no changes
|
||||
};
|
||||
|
||||
Ok(TaskAttemptState {
|
||||
execution_state,
|
||||
has_changes,
|
||||
has_setup_script,
|
||||
setup_process_id: setup_process.map(|p| p.id.to_string()),
|
||||
coding_agent_process_id: coding_agent_process.map(|p| p.id.to_string()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,18 +12,22 @@ use sqlx::SqlitePool;
|
||||
use tokio::sync::RwLock;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::{
|
||||
config::Config,
|
||||
execution_process::{ExecutionProcess, ExecutionProcessSummary},
|
||||
task::Task,
|
||||
task_attempt::{
|
||||
BranchStatus, CreateFollowUpAttempt, CreatePrParams, CreateTaskAttempt, TaskAttempt,
|
||||
TaskAttemptStatus, WorktreeDiff,
|
||||
use crate::{
|
||||
executor::{ExecutorConfig, NormalizedConversation},
|
||||
models::{
|
||||
config::Config,
|
||||
execution_process::{ExecutionProcess, ExecutionProcessStatus, ExecutionProcessSummary},
|
||||
executor_session::ExecutorSession,
|
||||
task::Task,
|
||||
task_attempt::{
|
||||
BranchStatus, CreateFollowUpAttempt, CreatePrParams, CreateTaskAttempt, TaskAttempt,
|
||||
TaskAttemptState, TaskAttemptStatus, WorktreeDiff,
|
||||
},
|
||||
task_attempt_activity::{
|
||||
CreateTaskAttemptActivity, TaskAttemptActivity, TaskAttemptActivityWithPrompt,
|
||||
},
|
||||
ApiResponse,
|
||||
},
|
||||
task_attempt_activity::{
|
||||
CreateTaskAttemptActivity, TaskAttemptActivity, TaskAttemptActivityWithPrompt,
|
||||
},
|
||||
ApiResponse,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
@@ -948,6 +952,175 @@ pub async fn start_dev_server(
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_task_attempt_execution_state(
|
||||
Path((project_id, task_id, attempt_id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
Extension(pool): Extension<SqlitePool>,
|
||||
) -> Result<ResponseJson<ApiResponse<TaskAttemptState>>, StatusCode> {
|
||||
// Verify task attempt exists and belongs to the correct task
|
||||
match TaskAttempt::exists_for_task(&pool, attempt_id, task_id, project_id).await {
|
||||
Ok(false) => return Err(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to check task attempt existence: {}", e);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
Ok(true) => {}
|
||||
}
|
||||
|
||||
// Get the execution state
|
||||
match TaskAttempt::get_execution_state(&pool, attempt_id, task_id, project_id).await {
|
||||
Ok(state) => Ok(ResponseJson(ApiResponse {
|
||||
success: true,
|
||||
data: Some(state),
|
||||
message: None,
|
||||
})),
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Failed to get execution state for task attempt {}: {}",
|
||||
attempt_id,
|
||||
e
|
||||
);
|
||||
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_execution_process_normalized_logs(
|
||||
Path((project_id, process_id)): Path<(Uuid, Uuid)>,
|
||||
Extension(pool): Extension<SqlitePool>,
|
||||
) -> Result<ResponseJson<ApiResponse<NormalizedConversation>>, StatusCode> {
|
||||
// Get the execution process and verify it belongs to the correct project
|
||||
let process = match ExecutionProcess::find_by_id(&pool, process_id).await {
|
||||
Ok(Some(process)) => process,
|
||||
Ok(None) => return Err(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to fetch execution process {}: {}", process_id, e);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
// Verify the process belongs to a task attempt in the correct project
|
||||
let attempt = match TaskAttempt::find_by_id(&pool, process.task_attempt_id).await {
|
||||
Ok(Some(attempt)) => attempt,
|
||||
Ok(None) => return Err(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to fetch task attempt: {}", e);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
let _task = match Task::find_by_id(&pool, attempt.task_id).await {
|
||||
Ok(Some(task)) if task.project_id == project_id => task,
|
||||
Ok(Some(_)) => return Err(StatusCode::NOT_FOUND), // Wrong project
|
||||
Ok(None) => return Err(StatusCode::NOT_FOUND),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to fetch task: {}", e);
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
};
|
||||
|
||||
// Get logs from the execution process
|
||||
let logs = match process.stdout {
|
||||
Some(stdout) => stdout,
|
||||
None => {
|
||||
// If the process is still running, return empty logs instead of an error
|
||||
if process.status == ExecutionProcessStatus::Running {
|
||||
// Get executor session data for this execution process
|
||||
let executor_session =
|
||||
match ExecutorSession::find_by_execution_process_id(&pool, process_id).await {
|
||||
Ok(session) => session,
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Failed to fetch executor session for process {}: {}",
|
||||
process_id,
|
||||
e
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
return Ok(ResponseJson(ApiResponse {
|
||||
success: true,
|
||||
data: Some(NormalizedConversation {
|
||||
entries: vec![],
|
||||
session_id: None,
|
||||
executor_type: process
|
||||
.executor_type
|
||||
.clone()
|
||||
.unwrap_or("unknown".to_string()),
|
||||
prompt: executor_session.as_ref().and_then(|s| s.prompt.clone()),
|
||||
summary: executor_session.as_ref().and_then(|s| s.summary.clone()),
|
||||
}),
|
||||
message: None,
|
||||
}));
|
||||
}
|
||||
|
||||
return Ok(ResponseJson(ApiResponse {
|
||||
success: false,
|
||||
data: None,
|
||||
message: Some("No logs available for this execution process".to_string()),
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
// Determine executor type and create appropriate executor for normalization
|
||||
let executor_type = process.executor_type.as_deref().unwrap_or("unknown");
|
||||
let executor_config = match executor_type {
|
||||
"amp" => ExecutorConfig::Amp,
|
||||
"claude" => ExecutorConfig::Claude,
|
||||
"echo" => ExecutorConfig::Echo,
|
||||
"gemini" => ExecutorConfig::Gemini,
|
||||
"opencode" => ExecutorConfig::Opencode,
|
||||
_ => {
|
||||
return Ok(ResponseJson(ApiResponse {
|
||||
success: false,
|
||||
data: None,
|
||||
message: Some(format!("Unsupported executor type: {}", executor_type)),
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
let executor = executor_config.create_executor();
|
||||
|
||||
// Get executor session data for this execution process
|
||||
let executor_session =
|
||||
match ExecutorSession::find_by_execution_process_id(&pool, process_id).await {
|
||||
Ok(session) => session,
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Failed to fetch executor session for process {}: {}",
|
||||
process_id,
|
||||
e
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// Normalize the logs
|
||||
match executor.normalize_logs(&logs) {
|
||||
Ok(mut normalized) => {
|
||||
// Add prompt and summary from executor session
|
||||
if let Some(session) = executor_session {
|
||||
normalized.prompt = session.prompt;
|
||||
normalized.summary = session.summary;
|
||||
}
|
||||
|
||||
Ok(ResponseJson(ApiResponse {
|
||||
success: true,
|
||||
data: Some(normalized),
|
||||
message: None,
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to normalize logs for process {}: {}", process_id, e);
|
||||
Ok(ResponseJson(ApiResponse {
|
||||
success: false,
|
||||
data: None,
|
||||
message: Some(format!("Failed to normalize logs: {}", e)),
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn task_attempts_router() -> Router {
|
||||
use axum::routing::post;
|
||||
|
||||
@@ -1005,6 +1178,10 @@ pub fn task_attempts_router() -> Router {
|
||||
"/projects/:project_id/execution-processes/:process_id",
|
||||
get(get_execution_process),
|
||||
)
|
||||
.route(
|
||||
"/projects/:project_id/execution-processes/:process_id/normalized-logs",
|
||||
get(get_execution_process_normalized_logs),
|
||||
)
|
||||
.route(
|
||||
"/projects/:project_id/tasks/:task_id/attempts/:attempt_id/follow-up",
|
||||
post(create_followup_attempt),
|
||||
@@ -1013,4 +1190,8 @@ pub fn task_attempts_router() -> Router {
|
||||
"/projects/:project_id/tasks/:task_id/attempts/:attempt_id/start-dev-server",
|
||||
post(start_dev_server),
|
||||
)
|
||||
.route(
|
||||
"/projects/:project_id/tasks/:task_id/attempts/:attempt_id",
|
||||
get(get_task_attempt_execution_state),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { BrowserRouter, Routes, Route } from 'react-router-dom';
|
||||
import { Navbar } from '@/components/layout/navbar';
|
||||
import { Projects } from '@/pages/projects';
|
||||
import { ProjectTasks } from '@/pages/project-tasks';
|
||||
import { TaskAttemptComparePage } from '@/pages/task-attempt-compare';
|
||||
|
||||
import { Settings } from '@/pages/Settings';
|
||||
import { McpServers } from '@/pages/McpServers';
|
||||
import { DisclaimerDialog } from '@/components/DisclaimerDialog';
|
||||
@@ -127,10 +127,7 @@ function AppContent() {
|
||||
path="/projects/:projectId/tasks/:taskId"
|
||||
element={<ProjectTasks />}
|
||||
/>
|
||||
<Route
|
||||
path="/projects/:projectId/tasks/:taskId/attempts/:attemptId/compare"
|
||||
element={<TaskAttemptComparePage />}
|
||||
/>
|
||||
|
||||
<Route path="/settings" element={<Settings />} />
|
||||
<Route path="/mcp-servers" element={<McpServers />} />
|
||||
</Routes>
|
||||
|
||||
@@ -1,799 +0,0 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
import {
|
||||
Brain,
|
||||
Wrench as Tool,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Clock,
|
||||
Zap,
|
||||
AlertTriangle,
|
||||
FileText,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface JSONLLine {
|
||||
type: string;
|
||||
threadID?: string;
|
||||
// Amp format
|
||||
messages?: [
|
||||
number,
|
||||
{
|
||||
role: 'user' | 'assistant';
|
||||
content: Array<{
|
||||
type: 'text' | 'thinking' | 'tool_use' | 'tool_result';
|
||||
text?: string;
|
||||
thinking?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
input?: any;
|
||||
toolUseID?: string;
|
||||
run?: {
|
||||
status: string;
|
||||
result?: string;
|
||||
toAllow?: string[];
|
||||
};
|
||||
}>;
|
||||
meta?: {
|
||||
sentAt: number;
|
||||
};
|
||||
state?: {
|
||||
type: string;
|
||||
stopReason?: string;
|
||||
};
|
||||
},
|
||||
][];
|
||||
toolResults?: Array<{
|
||||
type: 'tool_use' | 'tool_result';
|
||||
id?: string;
|
||||
name?: string;
|
||||
input?: any;
|
||||
toolUseID?: string;
|
||||
run?: {
|
||||
status: string;
|
||||
result?: string;
|
||||
toAllow?: string[];
|
||||
};
|
||||
}>;
|
||||
tokenUsage?: {
|
||||
used: number;
|
||||
maxAvailable: number;
|
||||
};
|
||||
state?: string;
|
||||
tool?: string;
|
||||
command?: string;
|
||||
// Claude format
|
||||
message?: {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content:
|
||||
| Array<{
|
||||
type: 'text' | 'tool_use' | 'tool_result';
|
||||
text?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
input?: any;
|
||||
tool_use_id?: string;
|
||||
content?: any;
|
||||
is_error?: boolean;
|
||||
}>
|
||||
| string;
|
||||
};
|
||||
messageKey?: number;
|
||||
isStreaming?: boolean;
|
||||
// Tool rejection message (string format)
|
||||
rejectionMessage?: string;
|
||||
usage?: {
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
cache_creation_input_tokens?: number;
|
||||
cache_read_input_tokens?: number;
|
||||
};
|
||||
result?: any;
|
||||
duration_ms?: number;
|
||||
total_cost_usd?: number;
|
||||
error?: string; // For parse errors
|
||||
}
|
||||
|
||||
interface ConversationViewerProps {
|
||||
jsonlOutput: string;
|
||||
}
|
||||
|
||||
// Validation functions
|
||||
const isValidMessage = (data: any): boolean => {
|
||||
return (
|
||||
typeof data.role === 'string' &&
|
||||
Array.isArray(data.content) &&
|
||||
data.content.every(
|
||||
(item: any) =>
|
||||
typeof item.type === 'string' &&
|
||||
(item.type !== 'text' || typeof item.text === 'string') &&
|
||||
(item.type !== 'thinking' || typeof item.thinking === 'string') &&
|
||||
(item.type !== 'tool_use' || typeof item.name === 'string') &&
|
||||
(item.type !== 'tool_result' ||
|
||||
!item.run ||
|
||||
typeof item.run.status === 'string')
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const isValidClaudeMessage = (data: any): boolean => {
|
||||
return (
|
||||
typeof data.role === 'string' &&
|
||||
(typeof data.content === 'string' ||
|
||||
(Array.isArray(data.content) &&
|
||||
data.content.every(
|
||||
(item: any) =>
|
||||
typeof item.type === 'string' &&
|
||||
(item.type !== 'text' || typeof item.text === 'string') &&
|
||||
(item.type !== 'tool_use' || typeof item.name === 'string') &&
|
||||
(item.type !== 'tool_result' || typeof item.content !== 'undefined')
|
||||
)))
|
||||
);
|
||||
};
|
||||
|
||||
const isValidTokenUsage = (data: any): boolean => {
|
||||
return (
|
||||
data &&
|
||||
typeof data.used === 'number' &&
|
||||
typeof data.maxAvailable === 'number'
|
||||
);
|
||||
};
|
||||
|
||||
const isValidClaudeUsage = (data: any): boolean => {
|
||||
return (
|
||||
data &&
|
||||
typeof data.input_tokens === 'number' &&
|
||||
typeof data.output_tokens === 'number'
|
||||
);
|
||||
};
|
||||
|
||||
const isValidToolRejection = (data: any): boolean => {
|
||||
return (
|
||||
typeof data.tool === 'string' &&
|
||||
typeof data.command === 'string' &&
|
||||
(typeof data.message === 'string' ||
|
||||
typeof data.rejectionMessage === 'string')
|
||||
);
|
||||
};
|
||||
|
||||
const isValidMessagesLine = (line: any): boolean => {
|
||||
return (
|
||||
Array.isArray(line.messages) &&
|
||||
line.messages.every(
|
||||
(msg: any) =>
|
||||
Array.isArray(msg) &&
|
||||
msg.length >= 2 &&
|
||||
typeof msg[0] === 'number' &&
|
||||
isValidMessage(msg[1])
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
export function ConversationViewer({ jsonlOutput }: ConversationViewerProps) {
|
||||
const [expandedMessages, setExpandedMessages] = useState<Set<string>>(
|
||||
new Set()
|
||||
);
|
||||
const [showTokenUsage, setShowTokenUsage] = useState(false);
|
||||
|
||||
const parsedLines = useMemo(() => {
|
||||
try {
|
||||
return jsonlOutput
|
||||
.split('\n')
|
||||
.filter((line) => line.trim())
|
||||
.map((line, index) => {
|
||||
try {
|
||||
const parsed = JSON.parse(line);
|
||||
return {
|
||||
...parsed,
|
||||
_lineIndex: index,
|
||||
_rawLine: line,
|
||||
} as JSONLLine & { _lineIndex: number; _rawLine: string };
|
||||
} catch {
|
||||
return {
|
||||
type: 'parse-error',
|
||||
_lineIndex: index,
|
||||
_rawLine: line,
|
||||
error: 'Failed to parse JSON',
|
||||
} as JSONLLine & {
|
||||
_lineIndex: number;
|
||||
_rawLine: string;
|
||||
error: string;
|
||||
};
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}, [jsonlOutput]);
|
||||
|
||||
const conversation = useMemo(() => {
|
||||
const streamingMessageMap = new Map<number, any>();
|
||||
const items: Array<{
|
||||
type: 'message' | 'tool-rejection' | 'parse-error' | 'unknown';
|
||||
role?: 'user' | 'assistant';
|
||||
content?: Array<{
|
||||
type: string;
|
||||
text?: string;
|
||||
thinking?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
input?: any;
|
||||
toolUseID?: string;
|
||||
run?: any;
|
||||
}>;
|
||||
timestamp?: number;
|
||||
messageIndex?: number;
|
||||
lineIndex?: number;
|
||||
tool?: string;
|
||||
command?: string;
|
||||
message?: string;
|
||||
error?: string;
|
||||
rawLine?: string;
|
||||
}> = [];
|
||||
|
||||
const tokenUsages: Array<{
|
||||
used: number;
|
||||
maxAvailable: number;
|
||||
lineIndex: number;
|
||||
}> = [];
|
||||
const states: Array<{ state: string; lineIndex: number }> = [];
|
||||
|
||||
for (const line of parsedLines) {
|
||||
try {
|
||||
if (line.type === 'parse-error') {
|
||||
items.push({
|
||||
type: 'parse-error',
|
||||
error: line.error,
|
||||
rawLine: line._rawLine,
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
} else if (
|
||||
line.type === 'messages' &&
|
||||
isValidMessagesLine(line) &&
|
||||
line.messages
|
||||
) {
|
||||
// Amp format
|
||||
for (const [messageIndex, message] of line.messages) {
|
||||
const messageItem = {
|
||||
type: 'message' as const,
|
||||
role: message.role,
|
||||
content: message.content,
|
||||
timestamp: message.meta?.sentAt,
|
||||
messageIndex,
|
||||
lineIndex: line._lineIndex,
|
||||
};
|
||||
|
||||
// Handle Gemini streaming via top-level messageKey and isStreaming
|
||||
if (line.isStreaming && line.messageKey !== undefined) {
|
||||
const existingMessage = streamingMessageMap.get(line.messageKey);
|
||||
if (existingMessage) {
|
||||
// Append new content to existing message
|
||||
if (
|
||||
existingMessage.content &&
|
||||
existingMessage.content[0] &&
|
||||
messageItem.content &&
|
||||
messageItem.content[0]
|
||||
) {
|
||||
existingMessage.content[0].text =
|
||||
(existingMessage.content[0].text || '') +
|
||||
(messageItem.content[0].text || '');
|
||||
existingMessage.timestamp = messageItem.timestamp; // Update timestamp
|
||||
}
|
||||
} else {
|
||||
// First segment for this message
|
||||
streamingMessageMap.set(line.messageKey, messageItem);
|
||||
}
|
||||
} else {
|
||||
items.push(messageItem);
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
(line.type === 'user' ||
|
||||
line.type === 'assistant' ||
|
||||
line.type === 'system') &&
|
||||
line.message &&
|
||||
isValidClaudeMessage(line.message)
|
||||
) {
|
||||
// Claude format
|
||||
const content =
|
||||
typeof line.message.content === 'string'
|
||||
? [{ type: 'text', text: line.message.content }]
|
||||
: line.message.content;
|
||||
|
||||
items.push({
|
||||
type: 'message',
|
||||
role:
|
||||
line.message.role === 'system' ? 'assistant' : line.message.role,
|
||||
content: content,
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
} else if (
|
||||
line.type === 'result' &&
|
||||
line.usage &&
|
||||
isValidClaudeUsage(line.usage)
|
||||
) {
|
||||
// Claude usage info
|
||||
tokenUsages.push({
|
||||
used: line.usage.input_tokens + line.usage.output_tokens,
|
||||
maxAvailable:
|
||||
line.usage.input_tokens + line.usage.output_tokens + 100000, // Approximate
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
} else if (
|
||||
line.type === 'token-usage' &&
|
||||
line.tokenUsage &&
|
||||
isValidTokenUsage(line.tokenUsage)
|
||||
) {
|
||||
// Amp format
|
||||
tokenUsages.push({
|
||||
used: line.tokenUsage.used,
|
||||
maxAvailable: line.tokenUsage.maxAvailable,
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
} else if (line.type === 'state' && typeof line.state === 'string') {
|
||||
states.push({
|
||||
state: line.state,
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
} else if (
|
||||
line.type === 'tool-rejected' &&
|
||||
isValidToolRejection(line)
|
||||
) {
|
||||
items.push({
|
||||
type: 'tool-rejection',
|
||||
tool: line.tool,
|
||||
command: line.command,
|
||||
message:
|
||||
typeof line.message === 'string'
|
||||
? line.message
|
||||
: line.rejectionMessage || 'Tool rejected',
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
} else {
|
||||
// Unknown line type or invalid structure - add as unknown for fallback rendering
|
||||
items.push({
|
||||
type: 'unknown',
|
||||
rawLine: line._rawLine,
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// If anything goes wrong processing a line, treat it as unknown
|
||||
items.push({
|
||||
type: 'unknown',
|
||||
rawLine: line._rawLine,
|
||||
lineIndex: line._lineIndex,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const streamingMessages = Array.from(streamingMessageMap.values());
|
||||
const finalItems = [...items, ...streamingMessages];
|
||||
|
||||
// Sort by messageIndex for messages, then by lineIndex for everything else
|
||||
finalItems.sort((a, b) => {
|
||||
if (a.type === 'message' && b.type === 'message') {
|
||||
return (a.messageIndex || 0) - (b.messageIndex || 0);
|
||||
}
|
||||
return (a.lineIndex || 0) - (b.lineIndex || 0);
|
||||
});
|
||||
|
||||
return {
|
||||
items: finalItems,
|
||||
tokenUsages,
|
||||
states,
|
||||
};
|
||||
}, [parsedLines]);
|
||||
|
||||
const toggleMessage = (messageId: string) => {
|
||||
const newExpanded = new Set(expandedMessages);
|
||||
if (newExpanded.has(messageId)) {
|
||||
newExpanded.delete(messageId);
|
||||
} else {
|
||||
newExpanded.add(messageId);
|
||||
}
|
||||
setExpandedMessages(newExpanded);
|
||||
};
|
||||
|
||||
const formatToolInput = (input: any): string => {
|
||||
try {
|
||||
if (input === null || input === undefined) {
|
||||
return String(input);
|
||||
}
|
||||
if (typeof input === 'object') {
|
||||
// Try to stringify, but handle circular references and complex objects
|
||||
return JSON.stringify(input);
|
||||
}
|
||||
return String(input);
|
||||
} catch (error) {
|
||||
// If anything goes wrong, return a safe fallback
|
||||
return `[Unable to display input: ${String(input).substring(0, 100)}...]`;
|
||||
}
|
||||
};
|
||||
|
||||
const safeRenderString = (value: any): string => {
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
if (value === null || value === undefined) {
|
||||
return String(value);
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
try {
|
||||
// Use the same safe JSON.stringify logic as formatToolInput
|
||||
return '(RAW)' + JSON.stringify(value);
|
||||
} catch (error) {
|
||||
return `[Object - serialization failed: ${String(value).substring(
|
||||
0,
|
||||
50
|
||||
)}...]`;
|
||||
}
|
||||
}
|
||||
return String(value);
|
||||
};
|
||||
|
||||
const getToolStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'done':
|
||||
return 'bg-green-500';
|
||||
case 'rejected-by-user':
|
||||
case 'blocked-on-user':
|
||||
return 'bg-yellow-500';
|
||||
case 'error':
|
||||
return 'bg-red-500';
|
||||
default:
|
||||
return 'bg-blue-500';
|
||||
}
|
||||
};
|
||||
|
||||
if (parsedLines.length === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No valid JSONL data found
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const latestTokenUsage =
|
||||
conversation.tokenUsages[conversation.tokenUsages.length - 1];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header with token usage */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Brain className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">LLM Conversation</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{latestTokenUsage && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
<Zap className="h-3 w-3 mr-1" />
|
||||
{latestTokenUsage.used.toLocaleString()} /{' '}
|
||||
{latestTokenUsage.maxAvailable.toLocaleString()} tokens
|
||||
</Badge>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowTokenUsage(!showTokenUsage)}
|
||||
>
|
||||
{showTokenUsage ? (
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Token usage details */}
|
||||
{showTokenUsage && conversation.tokenUsages.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm">Token Usage Timeline</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-3">
|
||||
<div className="space-y-1">
|
||||
{conversation.tokenUsages.map((usage, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between text-xs"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
Step {index + 1}
|
||||
</span>
|
||||
<span>
|
||||
{usage.used.toLocaleString()} /{' '}
|
||||
{usage.maxAvailable.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Conversation items (messages and tool rejections) */}
|
||||
<div className="space-y-3">
|
||||
{conversation.items.map((item, index) => {
|
||||
if (item.type === 'parse-error') {
|
||||
return (
|
||||
<Card
|
||||
key={`error-${index}`}
|
||||
className="bg-yellow-100/50 dark:bg-yellow-900/20 border"
|
||||
>
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<AlertTriangle className="h-4 w-4 text-yellow-600 dark:text-yellow-400" />
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Parse Error
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">
|
||||
Raw JSONL:
|
||||
</p>
|
||||
<pre className="text-xs bg-background p-2 rounded border overflow-x-auto whitespace-pre-wrap">
|
||||
{safeRenderString(item.rawLine)}
|
||||
</pre>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (item.type === 'unknown') {
|
||||
let prettyJson = item.rawLine;
|
||||
try {
|
||||
prettyJson = JSON.stringify(
|
||||
JSON.parse(item.rawLine || '{}'),
|
||||
null,
|
||||
2
|
||||
);
|
||||
} catch {
|
||||
// Keep as is if can't prettify
|
||||
}
|
||||
|
||||
return (
|
||||
<Card key={`unknown-${index}`} className="bg-muted/30 border">
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Unknown
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">JSONL:</p>
|
||||
<pre className="text-xs bg-background p-2 rounded border overflow-x-auto whitespace-pre-wrap">
|
||||
{safeRenderString(prettyJson)}
|
||||
</pre>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (item.type === 'tool-rejection') {
|
||||
return (
|
||||
<Card
|
||||
key={`rejection-${index}`}
|
||||
className="bg-red-100/50 dark:bg-red-900/20 border"
|
||||
>
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<AlertTriangle className="h-4 w-4 text-red-600 dark:text-red-400" />
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Tool Rejected
|
||||
</Badge>
|
||||
<span className="text-sm font-medium">
|
||||
{safeRenderString(item.tool)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">
|
||||
Command:
|
||||
</p>
|
||||
<pre className="text-xs bg-background p-2 rounded border overflow-x-auto">
|
||||
{safeRenderString(item.command)}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1">
|
||||
Message:
|
||||
</p>
|
||||
<p className="text-xs bg-background p-2 rounded border">
|
||||
{safeRenderString(item.message)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (item.type === 'message') {
|
||||
const messageId = `message-${index}`;
|
||||
const isExpanded = expandedMessages.has(messageId);
|
||||
const hasThinking = item.content?.some(
|
||||
(c: any) => c.type === 'thinking'
|
||||
);
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={messageId}
|
||||
className={`${
|
||||
item.role === 'user'
|
||||
? 'bg-blue-100/50 dark:bg-blue-900/20 border ml-12'
|
||||
: 'bg-muted/50 border mr-12'
|
||||
}`}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-sm font-medium capitalize">
|
||||
{item.role}
|
||||
</span>
|
||||
{item.timestamp && (
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(item.timestamp).toLocaleTimeString()}
|
||||
</div>
|
||||
)}
|
||||
{hasThinking && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => toggleMessage(messageId)}
|
||||
className="h-6 px-2 text-xs"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronUp className="h-3 w-3 mr-1" />
|
||||
Hide thinking
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronDown className="h-3 w-3 mr-1" />
|
||||
Show thinking
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{item.content?.map((content: any, contentIndex: number) => {
|
||||
if (content.type === 'text') {
|
||||
return (
|
||||
<div
|
||||
key={contentIndex}
|
||||
className="prose prose-sm max-w-none"
|
||||
>
|
||||
<p className="text-sm whitespace-pre-wrap">
|
||||
{safeRenderString(content.text)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (content.type === 'thinking' && isExpanded) {
|
||||
return (
|
||||
<div key={contentIndex} className="mt-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
💭 Thinking
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground italic whitespace-pre-wrap">
|
||||
{safeRenderString(content.thinking)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (content.type === 'tool_use') {
|
||||
return (
|
||||
<div key={contentIndex} className="mt-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Tool className="h-4 w-4 text-green-600 dark:text-green-400" />
|
||||
<span className="text-sm font-medium">
|
||||
{safeRenderString(content.name)}
|
||||
</span>
|
||||
</div>
|
||||
{content.input && (
|
||||
<pre className="text-xs bg-muted/50 p-2 rounded overflow-x-auto max-h-32">
|
||||
{formatToolInput(content.input)}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (content.type === 'tool_result') {
|
||||
return (
|
||||
<div key={contentIndex} className="mt-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<div className="w-4 h-4 flex items-center justify-center">
|
||||
{content.run?.status ? (
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full ${getToolStatusColor(
|
||||
content.run.status
|
||||
)}`}
|
||||
/>
|
||||
) : content.is_error ? (
|
||||
<div className="w-2 h-2 rounded-full bg-red-500" />
|
||||
) : (
|
||||
<div className="w-2 h-2 rounded-full bg-green-500" />
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Result
|
||||
</span>
|
||||
{content.run?.status && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
({safeRenderString(content.run.status)})
|
||||
</span>
|
||||
)}
|
||||
{content.is_error && (
|
||||
<span className="text-xs text-red-500">
|
||||
(Error)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* Amp format result */}
|
||||
{content.run?.result && (
|
||||
<pre className="text-xs bg-muted/50 p-2 rounded overflow-x-auto max-h-32">
|
||||
{safeRenderString(content.run.result)}
|
||||
</pre>
|
||||
)}
|
||||
{/* Claude format result */}
|
||||
{content.content && !content.run && (
|
||||
<pre className="text-xs bg-muted/50 p-2 rounded overflow-x-auto max-h-32">
|
||||
{safeRenderString(content.content)}
|
||||
</pre>
|
||||
)}
|
||||
{content.run?.toAllow && (
|
||||
<div className="mt-2">
|
||||
<p className="text-xs text-muted-foreground mb-1">
|
||||
Commands to allow:
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{content.run.toAllow.map(
|
||||
(cmd: string, i: number) => (
|
||||
<code
|
||||
key={i}
|
||||
className="text-xs bg-muted px-1 rounded"
|
||||
>
|
||||
{safeRenderString(cmd)}
|
||||
</code>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
})}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
import { useState, useMemo, useEffect } from 'react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { FileText, MessageSquare } from 'lucide-react';
|
||||
import { ConversationViewer } from './ConversationViewer';
|
||||
import type { ExecutionProcess, ExecutionProcessStatus } from 'shared/types';
|
||||
|
||||
interface ExecutionOutputViewerProps {
|
||||
executionProcess: ExecutionProcess;
|
||||
executor?: string;
|
||||
}
|
||||
|
||||
const getExecutionProcessStatusDisplay = (
|
||||
status: ExecutionProcessStatus
|
||||
): { label: string; color: string } => {
|
||||
switch (status) {
|
||||
case 'running':
|
||||
return { label: 'Running', color: 'bg-blue-500' };
|
||||
case 'completed':
|
||||
return { label: 'Completed', color: 'bg-green-500' };
|
||||
case 'failed':
|
||||
return { label: 'Failed', color: 'bg-red-500' };
|
||||
case 'killed':
|
||||
return { label: 'Stopped', color: 'bg-gray-500' };
|
||||
default:
|
||||
return { label: 'Unknown', color: 'bg-gray-400' };
|
||||
}
|
||||
};
|
||||
|
||||
export function ExecutionOutputViewer({
|
||||
executionProcess,
|
||||
executor,
|
||||
}: ExecutionOutputViewerProps) {
|
||||
const [viewMode, setViewMode] = useState<'conversation' | 'raw'>('raw');
|
||||
|
||||
const isAmpExecutor = executor === 'amp';
|
||||
const isClaudeExecutor = executor === 'claude';
|
||||
const isGeminiExecutor = executor === 'gemini';
|
||||
const hasStdout = !!executionProcess.stdout;
|
||||
const hasStderr = !!executionProcess.stderr;
|
||||
|
||||
// Check if stdout looks like JSONL (for Amp, Claude, or Gemini executor)
|
||||
const { isValidJsonl, jsonlFormat } = useMemo(() => {
|
||||
if (
|
||||
(!isAmpExecutor && !isClaudeExecutor && !isGeminiExecutor) ||
|
||||
!executionProcess.stdout
|
||||
) {
|
||||
return { isValidJsonl: false, jsonlFormat: null };
|
||||
}
|
||||
|
||||
try {
|
||||
const lines = executionProcess.stdout
|
||||
.split('\n')
|
||||
.filter((line) => line.trim());
|
||||
if (lines.length === 0) return { isValidJsonl: false, jsonlFormat: null };
|
||||
|
||||
// Try to parse at least the first few lines as JSON
|
||||
const testLines = lines.slice(0, Math.min(3, lines.length));
|
||||
const allValid = testLines.every((line) => {
|
||||
try {
|
||||
JSON.parse(line);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
if (!allValid) return { isValidJsonl: false, jsonlFormat: null };
|
||||
|
||||
// Detect format by checking for Amp vs Claude structure
|
||||
let hasAmpFormat = false;
|
||||
let hasClaudeFormat = false;
|
||||
|
||||
for (const line of testLines) {
|
||||
try {
|
||||
const parsed = JSON.parse(line);
|
||||
if (parsed.type === 'messages' || parsed.type === 'token-usage') {
|
||||
hasAmpFormat = true;
|
||||
}
|
||||
if (
|
||||
parsed.type === 'user' ||
|
||||
parsed.type === 'assistant' ||
|
||||
parsed.type === 'system' ||
|
||||
parsed.type === 'result'
|
||||
) {
|
||||
hasClaudeFormat = true;
|
||||
}
|
||||
} catch {
|
||||
// Skip invalid lines
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isValidJsonl: true,
|
||||
jsonlFormat: hasAmpFormat
|
||||
? 'amp'
|
||||
: hasClaudeFormat
|
||||
? 'claude'
|
||||
: 'unknown',
|
||||
};
|
||||
} catch {
|
||||
return { isValidJsonl: false, jsonlFormat: null };
|
||||
}
|
||||
}, [
|
||||
isAmpExecutor,
|
||||
isClaudeExecutor,
|
||||
isGeminiExecutor,
|
||||
executionProcess.stdout,
|
||||
]);
|
||||
|
||||
// Set initial view mode based on JSONL detection
|
||||
useEffect(() => {
|
||||
if (isValidJsonl) {
|
||||
setViewMode('conversation');
|
||||
}
|
||||
}, [isValidJsonl]);
|
||||
|
||||
if (!hasStdout && !hasStderr) {
|
||||
return (
|
||||
<Card className="bg-muted border-none">
|
||||
<CardContent className="p-3">
|
||||
<div className="text-xs text-muted-foreground italic text-center">
|
||||
Waiting for output...
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const statusDisplay = getExecutionProcessStatusDisplay(
|
||||
executionProcess.status
|
||||
);
|
||||
|
||||
return (
|
||||
<Card className="">
|
||||
<CardContent className="p-3">
|
||||
<div className="space-y-3">
|
||||
{/* Execution process header with status */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="text-xs capitalize">
|
||||
{executionProcess.process_type
|
||||
.replace(/([A-Z])/g, ' $1')
|
||||
.toLowerCase()}
|
||||
</Badge>
|
||||
<div className="flex items-center gap-1">
|
||||
<div
|
||||
className={`h-2 w-2 rounded-full ${statusDisplay.color}`}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{statusDisplay.label}
|
||||
</span>
|
||||
</div>
|
||||
{executor && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{executor}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* View mode toggle for executors with valid JSONL */}
|
||||
{isValidJsonl && hasStdout && (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{jsonlFormat && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{jsonlFormat} format
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant={viewMode === 'conversation' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setViewMode('conversation')}
|
||||
className="h-7 px-2 text-xs"
|
||||
>
|
||||
<MessageSquare className="h-3 w-3 mr-1" />
|
||||
Conversation
|
||||
</Button>
|
||||
<Button
|
||||
variant={viewMode === 'raw' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setViewMode('raw')}
|
||||
className="h-7 px-2 text-xs"
|
||||
>
|
||||
<FileText className="h-3 w-3 mr-1" />
|
||||
Raw
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Output content */}
|
||||
{hasStdout && (
|
||||
<div>
|
||||
{isValidJsonl && viewMode === 'conversation' ? (
|
||||
<ConversationViewer
|
||||
jsonlOutput={executionProcess.stdout || ''}
|
||||
/>
|
||||
) : (
|
||||
<div>
|
||||
<pre className="text-xs overflow-x-auto whitespace-pre-wrap p-2">
|
||||
{executionProcess.stdout}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasStderr && (
|
||||
<div>
|
||||
<pre className="text-xs overflow-x-auto whitespace-pre-wrap p-2 text-red-600">
|
||||
{executionProcess.stderr}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
221
frontend/src/components/tasks/NormalizedConversationViewer.tsx
Normal file
221
frontend/src/components/tasks/NormalizedConversationViewer.tsx
Normal file
@@ -0,0 +1,221 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
User,
|
||||
Bot,
|
||||
Eye,
|
||||
Edit,
|
||||
Terminal,
|
||||
Search,
|
||||
Globe,
|
||||
Plus,
|
||||
Settings,
|
||||
Brain,
|
||||
Hammer,
|
||||
} from 'lucide-react';
|
||||
import { makeRequest } from '@/lib/api';
|
||||
import type {
|
||||
NormalizedConversation,
|
||||
NormalizedEntryType,
|
||||
ExecutionProcess,
|
||||
ApiResponse,
|
||||
} from 'shared/types';
|
||||
|
||||
interface NormalizedConversationViewerProps {
|
||||
executionProcess: ExecutionProcess;
|
||||
projectId: string;
|
||||
onConversationUpdate?: () => void;
|
||||
}
|
||||
|
||||
const getEntryIcon = (entryType: NormalizedEntryType) => {
|
||||
if (entryType.type === 'user_message') {
|
||||
return <User className="h-4 w-4 text-blue-600" />;
|
||||
}
|
||||
if (entryType.type === 'assistant_message') {
|
||||
return <Bot className="h-4 w-4 text-green-600" />;
|
||||
}
|
||||
if (entryType.type === 'system_message') {
|
||||
return <Settings className="h-4 w-4 text-gray-600" />;
|
||||
}
|
||||
if (entryType.type === 'thinking') {
|
||||
return <Brain className="h-4 w-4 text-purple-600" />;
|
||||
}
|
||||
if (entryType.type === 'tool_use') {
|
||||
const { action_type } = entryType;
|
||||
if (action_type.action === 'file_read') {
|
||||
return <Eye className="h-4 w-4 text-orange-600" />;
|
||||
}
|
||||
if (action_type.action === 'file_write') {
|
||||
return <Edit className="h-4 w-4 text-red-600" />;
|
||||
}
|
||||
if (action_type.action === 'command_run') {
|
||||
return <Terminal className="h-4 w-4 text-yellow-600" />;
|
||||
}
|
||||
if (action_type.action === 'search') {
|
||||
return <Search className="h-4 w-4 text-indigo-600" />;
|
||||
}
|
||||
if (action_type.action === 'web_fetch') {
|
||||
return <Globe className="h-4 w-4 text-cyan-600" />;
|
||||
}
|
||||
if (action_type.action === 'task_create') {
|
||||
return <Plus className="h-4 w-4 text-teal-600" />;
|
||||
}
|
||||
return <Settings className="h-4 w-4 text-gray-600" />;
|
||||
}
|
||||
return <Settings className="h-4 w-4 text-gray-400" />;
|
||||
};
|
||||
|
||||
const getContentClassName = (entryType: NormalizedEntryType) => {
|
||||
const baseClasses = 'text-sm whitespace-pre-wrap break-words';
|
||||
|
||||
if (
|
||||
entryType.type === 'tool_use' &&
|
||||
entryType.action_type.action === 'command_run'
|
||||
) {
|
||||
return `${baseClasses} font-mono`;
|
||||
}
|
||||
|
||||
return baseClasses;
|
||||
};
|
||||
|
||||
export function NormalizedConversationViewer({
|
||||
executionProcess,
|
||||
projectId,
|
||||
onConversationUpdate,
|
||||
}: NormalizedConversationViewerProps) {
|
||||
const [conversation, setConversation] =
|
||||
useState<NormalizedConversation | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchNormalizedLogs = useCallback(
|
||||
async (isPolling = false) => {
|
||||
try {
|
||||
if (!isPolling) {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/execution-processes/${executionProcess.id}/normalized-logs`
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<NormalizedConversation> =
|
||||
await response.json();
|
||||
if (result.success && result.data) {
|
||||
setConversation((prev) => {
|
||||
// Only update if content actually changed
|
||||
if (
|
||||
!prev ||
|
||||
JSON.stringify(prev) !== JSON.stringify(result.data)
|
||||
) {
|
||||
// Notify parent component of conversation update
|
||||
if (onConversationUpdate) {
|
||||
// Use setTimeout to ensure state update happens first
|
||||
setTimeout(onConversationUpdate, 0);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
} else if (!isPolling) {
|
||||
setError(result.message || 'Failed to fetch normalized logs');
|
||||
}
|
||||
} else if (!isPolling) {
|
||||
const errorText = await response.text();
|
||||
setError(`Failed to fetch logs: ${errorText || response.statusText}`);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isPolling) {
|
||||
setError(
|
||||
`Error fetching logs: ${err instanceof Error ? err.message : 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!isPolling) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[executionProcess.id, projectId, onConversationUpdate]
|
||||
);
|
||||
|
||||
// Initial fetch
|
||||
useEffect(() => {
|
||||
fetchNormalizedLogs();
|
||||
}, [fetchNormalizedLogs]);
|
||||
|
||||
// Auto-refresh every 2 seconds when process is running
|
||||
useEffect(() => {
|
||||
if (executionProcess.status === 'running') {
|
||||
const interval = setInterval(() => {
|
||||
fetchNormalizedLogs(true);
|
||||
}, 2000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
}, [executionProcess.status, fetchNormalizedLogs]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="text-xs text-muted-foreground italic text-center">
|
||||
Loading conversation...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <div className="text-xs text-red-600 text-center">{error}</div>;
|
||||
}
|
||||
|
||||
if (!conversation || conversation.entries.length === 0) {
|
||||
// If the execution process is still running, show loading instead of "no data"
|
||||
if (executionProcess.status === 'running') {
|
||||
return (
|
||||
<div className="text-xs text-muted-foreground italic text-center">
|
||||
Waiting for logs...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-xs text-muted-foreground italic text-center">
|
||||
No conversation data available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Display prompt if available */}
|
||||
{conversation.prompt && (
|
||||
<div className="flex items-start gap-3 mb-6">
|
||||
<div className="flex-shrink-0 mt-1">
|
||||
<Hammer className="h-4 w-4 text-blue-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm whitespace-pre-wrap text-foreground">
|
||||
{conversation.prompt}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Display conversation entries */}
|
||||
<div className="space-y-2">
|
||||
{conversation.entries.map((entry, index) => (
|
||||
<div key={index} className="flex items-start gap-3">
|
||||
<div className="flex-shrink-0 mt-1">
|
||||
{getEntryIcon(entry.entry_type)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className={getContentClassName(entry.entry_type)}>
|
||||
{entry.content}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Clock, ChevronDown, ChevronUp, Code } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Chip } from '@/components/ui/chip';
|
||||
import { ExecutionOutputViewer } from './ExecutionOutputViewer';
|
||||
import { NormalizedConversationViewer } from './NormalizedConversationViewer';
|
||||
import type {
|
||||
TaskAttempt,
|
||||
TaskAttemptActivityWithPrompt,
|
||||
@@ -15,6 +15,7 @@ interface TaskActivityHistoryProps {
|
||||
selectedAttempt: TaskAttempt | null;
|
||||
activities: TaskAttemptActivityWithPrompt[];
|
||||
runningProcessDetails: Record<string, ExecutionProcess>;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
const getAttemptStatusDisplay = (
|
||||
@@ -63,6 +64,7 @@ export function TaskActivityHistory({
|
||||
selectedAttempt,
|
||||
activities,
|
||||
runningProcessDetails,
|
||||
projectId,
|
||||
}: TaskActivityHistoryProps) {
|
||||
const [expandedOutputs, setExpandedOutputs] = useState<Set<string>>(
|
||||
new Set()
|
||||
@@ -163,11 +165,11 @@ export function TaskActivityHistory({
|
||||
: 'max-h-64 overflow-hidden flex flex-col justify-end'
|
||||
}`}
|
||||
>
|
||||
<ExecutionOutputViewer
|
||||
<NormalizedConversationViewer
|
||||
executionProcess={
|
||||
runningProcessDetails[activity.execution_process_id]
|
||||
}
|
||||
executor={selectedAttempt?.executor || undefined}
|
||||
projectId={projectId}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useCallback, useState } from 'react';
|
||||
import { TaskDetailsHeader } from './TaskDetailsHeader';
|
||||
import { TaskDetailsToolbar } from './TaskDetailsToolbar';
|
||||
import { TaskActivityHistory } from './TaskActivityHistory';
|
||||
import { NormalizedConversationViewer } from './NormalizedConversationViewer';
|
||||
import { TaskFollowUpSection } from './TaskFollowUpSection';
|
||||
import { EditorSelectionDialog } from './EditorSelectionDialog';
|
||||
import { useTaskDetails } from '@/hooks/useTaskDetails';
|
||||
@@ -9,7 +9,25 @@ import {
|
||||
getTaskPanelClasses,
|
||||
getBackdropClasses,
|
||||
} from '@/lib/responsive-config';
|
||||
import type { TaskWithAttemptStatus, EditorType, Project } from 'shared/types';
|
||||
import { makeRequest } from '@/lib/api';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { FileText, ChevronDown, ChevronUp, Trash2 } from 'lucide-react';
|
||||
import type {
|
||||
TaskWithAttemptStatus,
|
||||
EditorType,
|
||||
Project,
|
||||
WorktreeDiff,
|
||||
DiffChunkType,
|
||||
DiffChunk,
|
||||
} from 'shared/types';
|
||||
|
||||
interface TaskDetailsPanelProps {
|
||||
task: TaskWithAttemptStatus | null;
|
||||
@@ -19,7 +37,28 @@ interface TaskDetailsPanelProps {
|
||||
onClose: () => void;
|
||||
onEditTask?: (task: TaskWithAttemptStatus) => void;
|
||||
onDeleteTask?: (taskId: string) => void;
|
||||
isDialogOpen?: boolean; // New prop to indicate if any dialog is open
|
||||
isDialogOpen?: boolean;
|
||||
}
|
||||
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data: T | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
interface ProcessedLine {
|
||||
content: string;
|
||||
chunkType: DiffChunkType;
|
||||
oldLineNumber?: number;
|
||||
newLineNumber?: number;
|
||||
}
|
||||
|
||||
interface ProcessedSection {
|
||||
type: 'context' | 'change' | 'expanded';
|
||||
lines: ProcessedLine[];
|
||||
expandKey?: string;
|
||||
expandedAbove?: boolean;
|
||||
expandedBelow?: boolean;
|
||||
}
|
||||
|
||||
export function TaskDetailsPanel({
|
||||
@@ -33,8 +72,20 @@ export function TaskDetailsPanel({
|
||||
isDialogOpen = false,
|
||||
}: TaskDetailsPanelProps) {
|
||||
const [showEditorDialog, setShowEditorDialog] = useState(false);
|
||||
const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
|
||||
const [shouldAutoScrollLogs, setShouldAutoScrollLogs] = useState(true);
|
||||
const [conversationUpdateTrigger, setConversationUpdateTrigger] = useState(0);
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
const setupScrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Diff-related state
|
||||
const [diff, setDiff] = useState<WorktreeDiff | null>(null);
|
||||
const [diffLoading, setDiffLoading] = useState(true);
|
||||
const [diffError, setDiffError] = useState<string | null>(null);
|
||||
const [expandedSections, setExpandedSections] = useState<Set<string>>(
|
||||
new Set()
|
||||
);
|
||||
const [deletingFiles, setDeletingFiles] = useState<Set<string>>(new Set());
|
||||
const [fileToDelete, setFileToDelete] = useState<string | null>(null);
|
||||
|
||||
// Use the custom hook for all task details logic
|
||||
const {
|
||||
@@ -51,11 +102,11 @@ export function TaskDetailsPanel({
|
||||
devServerDetails,
|
||||
branches,
|
||||
selectedBranch,
|
||||
|
||||
runningDevServer,
|
||||
isAttemptRunning,
|
||||
canSendFollowUp,
|
||||
processedDevServerLogs,
|
||||
executionState,
|
||||
setFollowUpMessage,
|
||||
setFollowUpError,
|
||||
setIsHoveringDevServer,
|
||||
@@ -68,6 +119,66 @@ export function TaskDetailsPanel({
|
||||
handleSendFollowUp,
|
||||
} = useTaskDetails(task, projectId, isOpen);
|
||||
|
||||
// Fetch diff when attempt changes
|
||||
const fetchDiff = useCallback(async () => {
|
||||
if (!projectId || !task?.id || !selectedAttempt?.id) {
|
||||
setDiff(null);
|
||||
setDiffLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setDiffLoading(true);
|
||||
setDiffError(null);
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${task.id}/attempts/${selectedAttempt.id}/diff`
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<WorktreeDiff> = await response.json();
|
||||
if (result.success && result.data) {
|
||||
setDiff(result.data);
|
||||
} else {
|
||||
setDiffError('Failed to load diff');
|
||||
}
|
||||
} else {
|
||||
setDiffError('Failed to load diff');
|
||||
}
|
||||
} catch (err) {
|
||||
setDiffError('Failed to load diff');
|
||||
} finally {
|
||||
setDiffLoading(false);
|
||||
}
|
||||
}, [projectId, task?.id, selectedAttempt?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
fetchDiff();
|
||||
}
|
||||
}, [isOpen, fetchDiff]);
|
||||
|
||||
// Refresh diff when coding agent is running and making changes
|
||||
useEffect(() => {
|
||||
if (!executionState || !isOpen || !selectedAttempt) return;
|
||||
|
||||
const isCodingAgentRunning =
|
||||
executionState.execution_state === 'CodingAgentRunning';
|
||||
|
||||
if (isCodingAgentRunning) {
|
||||
// Immediately refresh diff when coding agent starts running
|
||||
fetchDiff();
|
||||
|
||||
// Then refresh diff every 2 seconds while coding agent is active
|
||||
const interval = setInterval(() => {
|
||||
fetchDiff();
|
||||
}, 2000);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}
|
||||
}, [executionState, isOpen, selectedAttempt, fetchDiff]);
|
||||
|
||||
// Handle ESC key locally to prevent global navigation
|
||||
useEffect(() => {
|
||||
if (!isOpen || isDialogOpen) return;
|
||||
@@ -84,28 +195,45 @@ export function TaskDetailsPanel({
|
||||
return () => document.removeEventListener('keydown', handleKeyDown, true);
|
||||
}, [isOpen, onClose, isDialogOpen]);
|
||||
|
||||
// Auto-scroll to bottom when activities or execution processes change
|
||||
// Callback to trigger auto-scroll when conversation updates
|
||||
const handleConversationUpdate = useCallback(() => {
|
||||
setConversationUpdateTrigger((prev) => prev + 1);
|
||||
}, []);
|
||||
|
||||
// Auto-scroll to bottom when activities, execution processes, or conversation changes (for logs section)
|
||||
useEffect(() => {
|
||||
if (shouldAutoScroll && scrollContainerRef.current) {
|
||||
if (shouldAutoScrollLogs && scrollContainerRef.current) {
|
||||
scrollContainerRef.current.scrollTop =
|
||||
scrollContainerRef.current.scrollHeight;
|
||||
}
|
||||
}, [attemptData.activities, attemptData.processes, shouldAutoScroll]);
|
||||
}, [
|
||||
attemptData.activities,
|
||||
attemptData.processes,
|
||||
conversationUpdateTrigger,
|
||||
shouldAutoScrollLogs,
|
||||
]);
|
||||
|
||||
// Handle scroll events to detect manual scrolling
|
||||
const handleScroll = useCallback(() => {
|
||||
// Auto-scroll setup script logs to bottom
|
||||
useEffect(() => {
|
||||
if (setupScrollRef.current) {
|
||||
setupScrollRef.current.scrollTop = setupScrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [attemptData.runningProcessDetails]);
|
||||
|
||||
// Handle scroll events to detect manual scrolling (for logs section)
|
||||
const handleLogsScroll = useCallback(() => {
|
||||
if (scrollContainerRef.current) {
|
||||
const { scrollTop, scrollHeight, clientHeight } =
|
||||
scrollContainerRef.current;
|
||||
const isAtBottom = scrollTop + clientHeight >= scrollHeight - 5;
|
||||
|
||||
if (isAtBottom && !shouldAutoScroll) {
|
||||
setShouldAutoScroll(true);
|
||||
} else if (!isAtBottom && shouldAutoScroll) {
|
||||
setShouldAutoScroll(false);
|
||||
if (isAtBottom && !shouldAutoScrollLogs) {
|
||||
setShouldAutoScrollLogs(true);
|
||||
} else if (!isAtBottom && shouldAutoScrollLogs) {
|
||||
setShouldAutoScrollLogs(false);
|
||||
}
|
||||
}
|
||||
}, [shouldAutoScroll]);
|
||||
}, [shouldAutoScrollLogs]);
|
||||
|
||||
const handleOpenInEditor = async (editorType?: EditorType) => {
|
||||
try {
|
||||
@@ -117,6 +245,672 @@ export function TaskDetailsPanel({
|
||||
}
|
||||
};
|
||||
|
||||
// Diff processing functions
|
||||
const getChunkClassName = (chunkType: DiffChunkType) => {
|
||||
const baseClass = 'font-mono text-sm whitespace-pre flex w-full';
|
||||
|
||||
switch (chunkType) {
|
||||
case 'Insert':
|
||||
return `${baseClass} bg-green-50 dark:bg-green-900/20 text-green-900 dark:text-green-100`;
|
||||
case 'Delete':
|
||||
return `${baseClass} bg-red-50 dark:bg-red-900/20 text-red-900 dark:text-red-100`;
|
||||
case 'Equal':
|
||||
default:
|
||||
return `${baseClass} text-muted-foreground`;
|
||||
}
|
||||
};
|
||||
|
||||
const getLineNumberClassName = (chunkType: DiffChunkType) => {
|
||||
const baseClass =
|
||||
'flex-shrink-0 w-12 px-1.5 text-xs border-r select-none min-h-[1.25rem] flex items-center';
|
||||
|
||||
switch (chunkType) {
|
||||
case 'Insert':
|
||||
return `${baseClass} text-green-800 dark:text-green-200 bg-green-100 dark:bg-green-900/40 border-green-300 dark:border-green-600`;
|
||||
case 'Delete':
|
||||
return `${baseClass} text-red-800 dark:text-red-200 bg-red-100 dark:bg-red-900/40 border-red-300 dark:border-red-600`;
|
||||
case 'Equal':
|
||||
default:
|
||||
return `${baseClass} text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-700`;
|
||||
}
|
||||
};
|
||||
|
||||
const getChunkPrefix = (chunkType: DiffChunkType) => {
|
||||
switch (chunkType) {
|
||||
case 'Insert':
|
||||
return '+';
|
||||
case 'Delete':
|
||||
return '-';
|
||||
case 'Equal':
|
||||
default:
|
||||
return ' ';
|
||||
}
|
||||
};
|
||||
|
||||
const processFileChunks = (chunks: DiffChunk[], fileIndex: number) => {
|
||||
const CONTEXT_LINES = 3;
|
||||
const lines: ProcessedLine[] = [];
|
||||
let oldLineNumber = 1;
|
||||
let newLineNumber = 1;
|
||||
|
||||
// Convert chunks to lines with line numbers
|
||||
chunks.forEach((chunk) => {
|
||||
const chunkLines = chunk.content.split('\n');
|
||||
chunkLines.forEach((line, index) => {
|
||||
if (index < chunkLines.length - 1 || line !== '') {
|
||||
const processedLine: ProcessedLine = {
|
||||
content: line,
|
||||
chunkType: chunk.chunk_type,
|
||||
};
|
||||
|
||||
switch (chunk.chunk_type) {
|
||||
case 'Equal':
|
||||
processedLine.oldLineNumber = oldLineNumber++;
|
||||
processedLine.newLineNumber = newLineNumber++;
|
||||
break;
|
||||
case 'Delete':
|
||||
processedLine.oldLineNumber = oldLineNumber++;
|
||||
break;
|
||||
case 'Insert':
|
||||
processedLine.newLineNumber = newLineNumber++;
|
||||
break;
|
||||
}
|
||||
|
||||
lines.push(processedLine);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const sections: ProcessedSection[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
if (line.chunkType === 'Equal') {
|
||||
let nextChangeIndex = i + 1;
|
||||
while (
|
||||
nextChangeIndex < lines.length &&
|
||||
lines[nextChangeIndex].chunkType === 'Equal'
|
||||
) {
|
||||
nextChangeIndex++;
|
||||
}
|
||||
|
||||
const contextLength = nextChangeIndex - i;
|
||||
const hasNextChange = nextChangeIndex < lines.length;
|
||||
const hasPrevChange =
|
||||
sections.length > 0 &&
|
||||
sections[sections.length - 1].type === 'change';
|
||||
|
||||
if (
|
||||
contextLength <= CONTEXT_LINES * 2 ||
|
||||
(!hasPrevChange && !hasNextChange)
|
||||
) {
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(i, nextChangeIndex),
|
||||
});
|
||||
} else {
|
||||
if (hasPrevChange) {
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(i, i + CONTEXT_LINES),
|
||||
});
|
||||
i += CONTEXT_LINES;
|
||||
}
|
||||
|
||||
if (hasNextChange) {
|
||||
const expandStart = hasPrevChange ? i : i + CONTEXT_LINES;
|
||||
const expandEnd = nextChangeIndex - CONTEXT_LINES;
|
||||
|
||||
if (expandEnd > expandStart) {
|
||||
const expandKey = `${fileIndex}-${expandStart}-${expandEnd}`;
|
||||
const isExpanded = expandedSections.has(expandKey);
|
||||
|
||||
if (isExpanded) {
|
||||
sections.push({
|
||||
type: 'expanded',
|
||||
lines: lines.slice(expandStart, expandEnd),
|
||||
expandKey,
|
||||
});
|
||||
} else {
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: [],
|
||||
expandKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(
|
||||
nextChangeIndex - CONTEXT_LINES,
|
||||
nextChangeIndex
|
||||
),
|
||||
});
|
||||
} else if (!hasPrevChange) {
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(i, i + CONTEXT_LINES),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
i = nextChangeIndex;
|
||||
} else {
|
||||
const changeStart = i;
|
||||
while (i < lines.length && lines[i].chunkType !== 'Equal') {
|
||||
i++;
|
||||
}
|
||||
|
||||
sections.push({
|
||||
type: 'change',
|
||||
lines: lines.slice(changeStart, i),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return sections;
|
||||
};
|
||||
|
||||
const toggleExpandSection = (expandKey: string) => {
|
||||
setExpandedSections((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(expandKey)) {
|
||||
newSet.delete(expandKey);
|
||||
} else {
|
||||
newSet.add(expandKey);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteFileClick = (filePath: string) => {
|
||||
setFileToDelete(filePath);
|
||||
};
|
||||
|
||||
const handleConfirmDelete = async () => {
|
||||
if (!fileToDelete || !projectId || !task?.id || !selectedAttempt?.id)
|
||||
return;
|
||||
|
||||
try {
|
||||
setDeletingFiles((prev) => new Set(prev).add(fileToDelete));
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${task.id}/attempts/${selectedAttempt.id}/delete-file?file_path=${encodeURIComponent(
|
||||
fileToDelete
|
||||
)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<null> = await response.json();
|
||||
if (result.success) {
|
||||
fetchDiff();
|
||||
} else {
|
||||
setDiffError(result.message || 'Failed to delete file');
|
||||
}
|
||||
} else {
|
||||
setDiffError('Failed to delete file');
|
||||
}
|
||||
} catch (err) {
|
||||
setDiffError('Failed to delete file');
|
||||
} finally {
|
||||
setDeletingFiles((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(fileToDelete);
|
||||
return newSet;
|
||||
});
|
||||
setFileToDelete(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelDelete = () => {
|
||||
setFileToDelete(null);
|
||||
};
|
||||
|
||||
// Determine what content to show based on execution state
|
||||
const renderMainContent = (): JSX.Element => {
|
||||
if (!executionState) {
|
||||
// Still loading execution state, show loading
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-foreground mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground ml-4">Loading...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isSetupRunning = executionState.execution_state === 'SetupRunning';
|
||||
const isSetupFailed = executionState.execution_state === 'SetupFailed';
|
||||
const isCodingAgentRunning =
|
||||
executionState.execution_state === 'CodingAgentRunning';
|
||||
const isCodingAgentComplete =
|
||||
executionState.execution_state === 'CodingAgentComplete';
|
||||
const hasChanges = executionState.has_changes;
|
||||
|
||||
// When setup script is running, show setup execution stdio
|
||||
if (isSetupRunning) {
|
||||
// Find the setup script process in runningProcessDetails first, then fallback to processes
|
||||
const setupProcess = executionState.setup_process_id
|
||||
? attemptData.runningProcessDetails[executionState.setup_process_id]
|
||||
: Object.values(attemptData.runningProcessDetails).find(
|
||||
(process) => process.process_type === 'setupscript'
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex-1 min-h-0 p-6 overflow-y-auto"
|
||||
ref={setupScrollRef}
|
||||
>
|
||||
<div className="mb-4">
|
||||
<p className="text-lg font-semibold mb-2">Setup Script Running</p>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Preparing the environment for the coding agent...
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{setupProcess && (
|
||||
<div className="font-mono text-sm whitespace-pre-wrap text-muted-foreground">
|
||||
{(() => {
|
||||
const stdout = setupProcess.stdout || '';
|
||||
const stderr = setupProcess.stderr || '';
|
||||
const combined = [stdout, stderr].filter(Boolean).join('\n');
|
||||
return combined || 'Waiting for setup script output...';
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// When setup failed, show error message
|
||||
if (isSetupFailed) {
|
||||
return (
|
||||
<div className="flex-1 min-h-0 p-6 overflow-y-auto">
|
||||
<div className="text-center py-8 text-destructive">
|
||||
<p className="text-lg font-semibold mb-2">Setup Script Failed</p>
|
||||
<p className="text-muted-foreground">
|
||||
The setup script encountered an error. Check the logs for details.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// When coding agent is running or complete but no changes yet, show just agent conversation (full height)
|
||||
if ((isCodingAgentRunning || isCodingAgentComplete) && !hasChanges) {
|
||||
return (
|
||||
<div className="flex-1 min-h-0 border-t bg-muted/30">
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
onScroll={handleLogsScroll}
|
||||
className="h-full overflow-y-auto p-6"
|
||||
>
|
||||
{loading ? (
|
||||
<div className="text-center py-8">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-foreground mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
</div>
|
||||
) : (
|
||||
(() => {
|
||||
// Find main coding agent process (command: "executor")
|
||||
let mainCodingAgentProcess = Object.values(
|
||||
attemptData.runningProcessDetails
|
||||
).find(
|
||||
(process) =>
|
||||
process.process_type === 'codingagent' &&
|
||||
process.command === 'executor'
|
||||
);
|
||||
|
||||
if (!mainCodingAgentProcess) {
|
||||
const mainCodingAgentSummary = attemptData.processes.find(
|
||||
(process) =>
|
||||
process.process_type === 'codingagent' &&
|
||||
process.command === 'executor'
|
||||
);
|
||||
|
||||
if (mainCodingAgentSummary) {
|
||||
mainCodingAgentProcess = Object.values(
|
||||
attemptData.runningProcessDetails
|
||||
).find(
|
||||
(process) => process.id === mainCodingAgentSummary.id
|
||||
);
|
||||
|
||||
if (!mainCodingAgentProcess) {
|
||||
mainCodingAgentProcess = {
|
||||
...mainCodingAgentSummary,
|
||||
stdout: null,
|
||||
stderr: null,
|
||||
} as any;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find follow up executor processes (command: "followup_executor")
|
||||
const followUpProcesses = attemptData.processes
|
||||
.filter(
|
||||
(process) =>
|
||||
process.process_type === 'codingagent' &&
|
||||
process.command === 'followup_executor'
|
||||
)
|
||||
.map((summary) => {
|
||||
const detailedProcess = Object.values(
|
||||
attemptData.runningProcessDetails
|
||||
).find((process) => process.id === summary.id);
|
||||
return (
|
||||
detailedProcess ||
|
||||
({
|
||||
...summary,
|
||||
stdout: null,
|
||||
stderr: null,
|
||||
} as any)
|
||||
);
|
||||
});
|
||||
|
||||
if (mainCodingAgentProcess || followUpProcesses.length > 0) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{mainCodingAgentProcess && (
|
||||
<div>
|
||||
<NormalizedConversationViewer
|
||||
executionProcess={mainCodingAgentProcess}
|
||||
projectId={projectId}
|
||||
onConversationUpdate={handleConversationUpdate}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{followUpProcesses.map((followUpProcess) => (
|
||||
<div key={followUpProcess.id}>
|
||||
<div className="border-t border-border mb-8"></div>
|
||||
<NormalizedConversationViewer
|
||||
executionProcess={followUpProcess}
|
||||
projectId={projectId}
|
||||
onConversationUpdate={handleConversationUpdate}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
|
||||
<p className="text-lg font-semibold mb-2">
|
||||
Coding Agent Starting
|
||||
</p>
|
||||
<p>Initializing conversation...</p>
|
||||
</div>
|
||||
);
|
||||
})()
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// When changes appear, show them (2/3) and conversation (1/3) in split view
|
||||
if (hasChanges) {
|
||||
return (
|
||||
<>
|
||||
{/* Top 2/3 - Code Changes */}
|
||||
<div className="flex-1 min-h-0 p-4 overflow-y-auto">
|
||||
{diffLoading ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-foreground mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground ml-4">Loading changes...</p>
|
||||
</div>
|
||||
) : diffError ? (
|
||||
<div className="text-center py-8 text-destructive">
|
||||
<p>{diffError}</p>
|
||||
</div>
|
||||
) : !diff || diff.files.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||
<p>No changes detected</p>
|
||||
<p className="text-sm">
|
||||
The worktree is identical to the base commit
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{diff.files.map((file, fileIndex) => (
|
||||
<div
|
||||
key={fileIndex}
|
||||
className="border rounded-lg overflow-hidden"
|
||||
>
|
||||
<div className="bg-muted px-3 py-1.5 border-b flex items-center justify-between">
|
||||
<p className="text-sm font-medium text-muted-foreground font-mono">
|
||||
{file.path}
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDeleteFileClick(file.path)}
|
||||
disabled={deletingFiles.has(file.path)}
|
||||
className="text-red-600 hover:text-red-800 hover:bg-red-50 h-8 px-3 gap-1"
|
||||
title={`Delete ${file.path}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
{deletingFiles.has(file.path)
|
||||
? 'Deleting...'
|
||||
: 'Delete File'}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<div className="inline-block min-w-full">
|
||||
{processFileChunks(file.chunks, fileIndex).map(
|
||||
(section, sectionIndex) => {
|
||||
if (
|
||||
section.type === 'context' &&
|
||||
section.lines.length === 0 &&
|
||||
section.expandKey
|
||||
) {
|
||||
const lineCount =
|
||||
parseInt(section.expandKey.split('-')[2]) -
|
||||
parseInt(section.expandKey.split('-')[1]);
|
||||
return (
|
||||
<div
|
||||
key={`expand-${section.expandKey}`}
|
||||
className="w-full"
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
toggleExpandSection(section.expandKey!)
|
||||
}
|
||||
className="w-full h-6 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-950/50 border-t border-b border-gray-200 dark:border-gray-700 rounded-none justify-start"
|
||||
>
|
||||
<ChevronDown className="h-3 w-3 mr-1" />
|
||||
Show {lineCount} more lines
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={`section-${sectionIndex}`}>
|
||||
{section.type === 'expanded' &&
|
||||
section.expandKey && (
|
||||
<div className="w-full">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
toggleExpandSection(
|
||||
section.expandKey!
|
||||
)
|
||||
}
|
||||
className="w-full h-6 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-950/50 border-t border-b border-gray-200 dark:border-gray-700 rounded-none justify-start"
|
||||
>
|
||||
<ChevronUp className="h-3 w-3 mr-1" />
|
||||
Hide expanded lines
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{section.lines.map((line, lineIndex) => (
|
||||
<div
|
||||
key={`${sectionIndex}-${lineIndex}`}
|
||||
className={getChunkClassName(
|
||||
line.chunkType
|
||||
)}
|
||||
style={{ minWidth: 'max-content' }}
|
||||
>
|
||||
<div
|
||||
className={getLineNumberClassName(
|
||||
line.chunkType
|
||||
)}
|
||||
>
|
||||
<span className="inline-block w-5 text-right">
|
||||
{line.oldLineNumber || ''}
|
||||
</span>
|
||||
<span className="inline-block w-5 text-right ml-1">
|
||||
{line.newLineNumber || ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1 px-2 min-h-[1.25rem] flex items-center">
|
||||
<span className="inline-block w-4">
|
||||
{getChunkPrefix(line.chunkType)}
|
||||
</span>
|
||||
<span>{line.content}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bottom 1/3 - Agent Logs */}
|
||||
<div className="h-1/3 min-h-0 border-t bg-muted/30">
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
onScroll={handleLogsScroll}
|
||||
className="h-full overflow-y-auto p-4"
|
||||
>
|
||||
{loading ? (
|
||||
<div className="text-center py-8">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-foreground mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
</div>
|
||||
) : (
|
||||
(() => {
|
||||
// Find main coding agent process (command: "executor")
|
||||
let mainCodingAgentProcess = Object.values(
|
||||
attemptData.runningProcessDetails
|
||||
).find(
|
||||
(process) =>
|
||||
process.process_type === 'codingagent' &&
|
||||
process.command === 'executor'
|
||||
);
|
||||
|
||||
if (!mainCodingAgentProcess) {
|
||||
const mainCodingAgentSummary = attemptData.processes.find(
|
||||
(process) =>
|
||||
process.process_type === 'codingagent' &&
|
||||
process.command === 'executor'
|
||||
);
|
||||
|
||||
if (mainCodingAgentSummary) {
|
||||
mainCodingAgentProcess = Object.values(
|
||||
attemptData.runningProcessDetails
|
||||
).find(
|
||||
(process) => process.id === mainCodingAgentSummary.id
|
||||
);
|
||||
|
||||
if (!mainCodingAgentProcess) {
|
||||
mainCodingAgentProcess = {
|
||||
...mainCodingAgentSummary,
|
||||
stdout: null,
|
||||
stderr: null,
|
||||
} as any;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find follow up executor processes (command: "followup_executor")
|
||||
const followUpProcesses = attemptData.processes
|
||||
.filter(
|
||||
(process) =>
|
||||
process.process_type === 'codingagent' &&
|
||||
process.command === 'followup_executor'
|
||||
)
|
||||
.map((summary) => {
|
||||
const detailedProcess = Object.values(
|
||||
attemptData.runningProcessDetails
|
||||
).find((process) => process.id === summary.id);
|
||||
return (
|
||||
detailedProcess ||
|
||||
({
|
||||
...summary,
|
||||
stdout: null,
|
||||
stderr: null,
|
||||
} as any)
|
||||
);
|
||||
});
|
||||
|
||||
if (mainCodingAgentProcess || followUpProcesses.length > 0) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{mainCodingAgentProcess && (
|
||||
<div>
|
||||
<NormalizedConversationViewer
|
||||
executionProcess={mainCodingAgentProcess}
|
||||
projectId={projectId}
|
||||
onConversationUpdate={handleConversationUpdate}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{followUpProcesses.map((followUpProcess) => (
|
||||
<div key={followUpProcess.id}>
|
||||
<div className="border-t border-border mb-8"></div>
|
||||
<NormalizedConversationViewer
|
||||
executionProcess={followUpProcess}
|
||||
projectId={projectId}
|
||||
onConversationUpdate={handleConversationUpdate}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<p>No coding agent conversation to display</p>
|
||||
</div>
|
||||
);
|
||||
})()
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Default case - execution hasn't started or no specific state
|
||||
return (
|
||||
<div className="flex-1 min-h-0 p-6 overflow-y-auto">
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<p>Task execution not started yet</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (!task) return null;
|
||||
|
||||
return (
|
||||
@@ -162,24 +956,9 @@ export function TaskDetailsPanel({
|
||||
onSetIsHoveringDevServer={setIsHoveringDevServer}
|
||||
/>
|
||||
|
||||
{/* Content */}
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
onScroll={handleScroll}
|
||||
className="flex-1 overflow-y-auto p-6 space-y-6"
|
||||
>
|
||||
{loading ? (
|
||||
<div className="text-center py-8">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-foreground mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
</div>
|
||||
) : (
|
||||
<TaskActivityHistory
|
||||
selectedAttempt={selectedAttempt}
|
||||
activities={attemptData.activities}
|
||||
runningProcessDetails={attemptData.runningProcessDetails}
|
||||
/>
|
||||
)}
|
||||
{/* Main Content - Dynamic based on execution state */}
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{renderMainContent()}
|
||||
</div>
|
||||
|
||||
{/* Footer - Follow-up section */}
|
||||
@@ -204,6 +983,48 @@ export function TaskDetailsPanel({
|
||||
onClose={() => setShowEditorDialog(false)}
|
||||
onSelectEditor={handleOpenInEditor}
|
||||
/>
|
||||
|
||||
{/* Delete File Confirmation Dialog */}
|
||||
<Dialog
|
||||
open={!!fileToDelete}
|
||||
onOpenChange={() => handleCancelDelete()}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete File</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete the file{' '}
|
||||
<span className="font-mono font-medium">
|
||||
"{fileToDelete}"
|
||||
</span>
|
||||
?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<div className="bg-red-50 border border-red-200 rounded-md p-3">
|
||||
<p className="text-sm text-red-800">
|
||||
<strong>Warning:</strong> This action will permanently
|
||||
remove the entire file from the worktree. This cannot be
|
||||
undone.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancelDelete}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleConfirmDelete}
|
||||
disabled={deletingFiles.has(fileToDelete || '')}
|
||||
>
|
||||
{deletingFiles.has(fileToDelete || '')
|
||||
? 'Deleting...'
|
||||
: 'Delete File'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -10,6 +10,7 @@ import type {
|
||||
ExecutionProcessSummary,
|
||||
EditorType,
|
||||
GitBranch,
|
||||
TaskAttemptState,
|
||||
} from 'shared/types';
|
||||
|
||||
export function useTaskDetails(
|
||||
@@ -45,6 +46,9 @@ export function useTaskDetails(
|
||||
const [isHoveringDevServer, setIsHoveringDevServer] = useState(false);
|
||||
const [branches, setBranches] = useState<GitBranch[]>([]);
|
||||
const [selectedBranch, setSelectedBranch] = useState<string | null>(null);
|
||||
const [executionState, setExecutionState] = useState<TaskAttemptState | null>(
|
||||
null
|
||||
);
|
||||
|
||||
// Find running dev server in current project
|
||||
const runningDevServer = useMemo(() => {
|
||||
@@ -153,6 +157,8 @@ export function useTaskDetails(
|
||||
);
|
||||
|
||||
const runningProcessDetails: Record<string, ExecutionProcess> = {};
|
||||
|
||||
// Fetch details for running activities
|
||||
for (const activity of runningActivities) {
|
||||
try {
|
||||
const detailResponse = await makeRequest(
|
||||
@@ -174,6 +180,30 @@ export function useTaskDetails(
|
||||
}
|
||||
}
|
||||
|
||||
// Also fetch setup script process details if it exists in the processes
|
||||
const setupProcess = processesResult.data.find(
|
||||
(process) => process.process_type === 'setupscript'
|
||||
);
|
||||
if (setupProcess && !runningProcessDetails[setupProcess.id]) {
|
||||
try {
|
||||
const detailResponse = await makeRequest(
|
||||
`/api/projects/${projectId}/execution-processes/${setupProcess.id}`
|
||||
);
|
||||
if (detailResponse.ok) {
|
||||
const detailResult: ApiResponse<ExecutionProcess> =
|
||||
await detailResponse.json();
|
||||
if (detailResult.success && detailResult.data) {
|
||||
runningProcessDetails[setupProcess.id] = detailResult.data;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`Failed to fetch setup process details ${setupProcess.id}:`,
|
||||
err
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
setAttemptData({
|
||||
activities: activitiesResult.data,
|
||||
processes: processesResult.data,
|
||||
@@ -188,6 +218,28 @@ export function useTaskDetails(
|
||||
[task, projectId]
|
||||
);
|
||||
|
||||
const fetchExecutionState = useCallback(
|
||||
async (attemptId: string) => {
|
||||
if (!task) return;
|
||||
|
||||
try {
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${task.id}/attempts/${attemptId}`
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<TaskAttemptState> = await response.json();
|
||||
if (result.success && result.data) {
|
||||
setExecutionState(result.data);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch execution state:', err);
|
||||
}
|
||||
},
|
||||
[task, projectId]
|
||||
);
|
||||
|
||||
const fetchTaskAttempts = useCallback(async () => {
|
||||
if (!task) return;
|
||||
|
||||
@@ -210,6 +262,7 @@ export function useTaskDetails(
|
||||
);
|
||||
setSelectedAttempt(latestAttempt);
|
||||
fetchAttemptData(latestAttempt.id);
|
||||
fetchExecutionState(latestAttempt.id);
|
||||
} else {
|
||||
setSelectedAttempt(null);
|
||||
setAttemptData({
|
||||
@@ -225,7 +278,7 @@ export function useTaskDetails(
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [task, projectId, fetchAttemptData]);
|
||||
}, [task, projectId, fetchAttemptData, fetchExecutionState]);
|
||||
|
||||
// Fetch dev server details when hovering
|
||||
const fetchDevServerDetails = useCallback(async () => {
|
||||
@@ -280,6 +333,14 @@ export function useTaskDetails(
|
||||
}
|
||||
}, [task, isOpen, fetchTaskAttempts, fetchProjectBranches]);
|
||||
|
||||
// Load attempt data when selectedAttempt changes
|
||||
useEffect(() => {
|
||||
if (selectedAttempt && task) {
|
||||
fetchAttemptData(selectedAttempt.id);
|
||||
fetchExecutionState(selectedAttempt.id);
|
||||
}
|
||||
}, [selectedAttempt, task, fetchAttemptData, fetchExecutionState]);
|
||||
|
||||
// Polling for updates when attempt is running
|
||||
useEffect(() => {
|
||||
if (!isAttemptRunning || !task) return;
|
||||
@@ -287,11 +348,18 @@ export function useTaskDetails(
|
||||
const interval = setInterval(() => {
|
||||
if (selectedAttempt) {
|
||||
fetchAttemptData(selectedAttempt.id);
|
||||
fetchExecutionState(selectedAttempt.id);
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [isAttemptRunning, task, selectedAttempt, fetchAttemptData]);
|
||||
}, [
|
||||
isAttemptRunning,
|
||||
task,
|
||||
selectedAttempt,
|
||||
fetchAttemptData,
|
||||
fetchExecutionState,
|
||||
]);
|
||||
|
||||
// Poll dev server details while hovering
|
||||
useEffect(() => {
|
||||
@@ -310,6 +378,7 @@ export function useTaskDetails(
|
||||
if (attempt) {
|
||||
setSelectedAttempt(attempt);
|
||||
fetchAttemptData(attempt.id);
|
||||
fetchExecutionState(attempt.id);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -510,6 +579,7 @@ export function useTaskDetails(
|
||||
isHoveringDevServer,
|
||||
branches,
|
||||
selectedBranch,
|
||||
executionState,
|
||||
|
||||
// Computed
|
||||
runningDevServer,
|
||||
|
||||
@@ -40,13 +40,6 @@ export const createKeyboardShortcuts = (
|
||||
|
||||
// Navigate back based on current path
|
||||
if (
|
||||
currentPath.includes('/attempts/') &&
|
||||
currentPath.includes('/compare')
|
||||
) {
|
||||
// From compare page, go back to task details
|
||||
const taskPath = currentPath.split('/attempts/')[0];
|
||||
context.navigate(taskPath);
|
||||
} else if (
|
||||
currentPath.includes('/tasks/') &&
|
||||
!currentPath.endsWith('/tasks')
|
||||
) {
|
||||
|
||||
@@ -1,975 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
ArrowLeft,
|
||||
FileText,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
RefreshCw,
|
||||
GitBranch,
|
||||
Trash2,
|
||||
Eye,
|
||||
EyeOff,
|
||||
GitPullRequest,
|
||||
} from 'lucide-react';
|
||||
import { makeRequest } from '@/lib/api';
|
||||
import type {
|
||||
WorktreeDiff,
|
||||
DiffChunkType,
|
||||
DiffChunk,
|
||||
BranchStatus,
|
||||
} from 'shared/types';
|
||||
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data: T | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export function TaskAttemptComparePage() {
|
||||
const { projectId, taskId, attemptId } = useParams<{
|
||||
projectId: string;
|
||||
taskId: string;
|
||||
attemptId: string;
|
||||
}>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [diff, setDiff] = useState<WorktreeDiff | null>(null);
|
||||
const [branchStatus, setBranchStatus] = useState<BranchStatus | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [branchStatusLoading, setBranchStatusLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [merging, setMerging] = useState(false);
|
||||
const [rebasing, setRebasing] = useState(false);
|
||||
const [rebaseSuccess, setRebaseSuccess] = useState(false);
|
||||
const [expandedSections, setExpandedSections] = useState<Set<string>>(
|
||||
new Set()
|
||||
);
|
||||
const [showAllUnchanged, setShowAllUnchanged] = useState(false);
|
||||
const [deletingFiles, setDeletingFiles] = useState<Set<string>>(new Set());
|
||||
const [fileToDelete, setFileToDelete] = useState<string | null>(null);
|
||||
const [showUncommittedWarning, setShowUncommittedWarning] = useState(false);
|
||||
const [creatingPR, setCreatingPR] = useState(false);
|
||||
const [showCreatePRDialog, setShowCreatePRDialog] = useState(false);
|
||||
const [prTitle, setPrTitle] = useState('');
|
||||
const [prBody, setPrBody] = useState('');
|
||||
const [prBaseBranch, setPrBaseBranch] = useState('main');
|
||||
const [taskDetails, setTaskDetails] = useState<{
|
||||
title: string;
|
||||
description: string | null;
|
||||
} | null>(null);
|
||||
|
||||
// Define callbacks first
|
||||
const fetchTaskDetails = useCallback(async () => {
|
||||
if (!projectId || !taskId) return;
|
||||
|
||||
try {
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${taskId}`
|
||||
);
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<any> = await response.json();
|
||||
if (result.success && result.data) {
|
||||
setTaskDetails({
|
||||
title: result.data.title,
|
||||
description: result.data.description,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Silently fail - not critical for the main functionality
|
||||
}
|
||||
}, [projectId, taskId]);
|
||||
|
||||
const fetchDiff = useCallback(async () => {
|
||||
if (!projectId || !taskId || !attemptId) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${taskId}/attempts/${attemptId}/diff`
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<WorktreeDiff> = await response.json();
|
||||
if (result.success && result.data) {
|
||||
setDiff(result.data);
|
||||
} else {
|
||||
setError('Failed to load diff');
|
||||
}
|
||||
} else {
|
||||
setError('Failed to load diff');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to load diff');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [projectId, taskId, attemptId]);
|
||||
|
||||
const fetchBranchStatus = useCallback(async () => {
|
||||
if (!projectId || !taskId || !attemptId) return;
|
||||
|
||||
try {
|
||||
setBranchStatusLoading(true);
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${taskId}/attempts/${attemptId}/branch-status`
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<BranchStatus> = await response.json();
|
||||
if (result.success && result.data) {
|
||||
setBranchStatus(result.data);
|
||||
} else {
|
||||
setError('Failed to load branch status');
|
||||
}
|
||||
} else {
|
||||
setError('Failed to load branch status');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to load branch status');
|
||||
} finally {
|
||||
setBranchStatusLoading(false);
|
||||
}
|
||||
}, [projectId, taskId, attemptId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (projectId && taskId && attemptId) {
|
||||
fetchTaskDetails();
|
||||
fetchDiff();
|
||||
fetchBranchStatus();
|
||||
}
|
||||
}, [
|
||||
projectId,
|
||||
taskId,
|
||||
attemptId,
|
||||
fetchTaskDetails,
|
||||
fetchDiff,
|
||||
fetchBranchStatus,
|
||||
]);
|
||||
|
||||
const handleBackClick = () => {
|
||||
navigate(`/projects/${projectId}/tasks/${taskId}`);
|
||||
};
|
||||
|
||||
const handleMergeClick = async () => {
|
||||
if (!projectId || !taskId || !attemptId) return;
|
||||
|
||||
// Check for uncommitted changes and show warning dialog
|
||||
if (branchStatus?.has_uncommitted_changes) {
|
||||
setShowUncommittedWarning(true);
|
||||
return;
|
||||
}
|
||||
|
||||
await performMerge();
|
||||
};
|
||||
|
||||
const performMerge = async () => {
|
||||
if (!projectId || !taskId || !attemptId) return;
|
||||
|
||||
try {
|
||||
setMerging(true);
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${taskId}/attempts/${attemptId}/merge`,
|
||||
{
|
||||
method: 'POST',
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<string> = await response.json();
|
||||
if (result.success) {
|
||||
// Refetch both diff and branch status to show updated state
|
||||
fetchDiff();
|
||||
fetchBranchStatus();
|
||||
} else {
|
||||
setError('Failed to merge changes');
|
||||
}
|
||||
} else {
|
||||
setError('Failed to merge changes');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to merge changes');
|
||||
} finally {
|
||||
setMerging(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirmMergeWithUncommitted = async () => {
|
||||
setShowUncommittedWarning(false);
|
||||
await performMerge();
|
||||
};
|
||||
|
||||
const handleCancelMergeWithUncommitted = () => {
|
||||
setShowUncommittedWarning(false);
|
||||
};
|
||||
|
||||
const handleRebaseClick = async () => {
|
||||
if (!projectId || !taskId || !attemptId) return;
|
||||
|
||||
try {
|
||||
setRebasing(true);
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${taskId}/attempts/${attemptId}/rebase`,
|
||||
{
|
||||
method: 'POST',
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<string> = await response.json();
|
||||
if (result.success) {
|
||||
setRebaseSuccess(true);
|
||||
// Refresh both diff and branch status after rebase
|
||||
fetchDiff();
|
||||
fetchBranchStatus();
|
||||
} else {
|
||||
setError(result.message || 'Failed to rebase branch');
|
||||
}
|
||||
} else {
|
||||
setError('Failed to rebase branch');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to rebase branch');
|
||||
} finally {
|
||||
setRebasing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreatePRClick = async () => {
|
||||
if (!projectId || !taskId || !attemptId) return;
|
||||
|
||||
// Auto-fill with task details if available
|
||||
if (taskDetails) {
|
||||
setPrTitle(`${taskDetails.title} (vibe-kanban)`);
|
||||
setPrBody(taskDetails.description || '');
|
||||
} else {
|
||||
// Fallback if task details aren't available
|
||||
setPrTitle('Task completion (vibe-kanban)');
|
||||
setPrBody('');
|
||||
}
|
||||
|
||||
setShowCreatePRDialog(true);
|
||||
};
|
||||
|
||||
const handleConfirmCreatePR = async () => {
|
||||
if (!projectId || !taskId || !attemptId) return;
|
||||
|
||||
try {
|
||||
setCreatingPR(true);
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${taskId}/attempts/${attemptId}/create-pr`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: prTitle,
|
||||
body: prBody || null,
|
||||
base_branch: prBaseBranch || null,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<string> = await response.json();
|
||||
if (result.success && result.data) {
|
||||
// Open the PR URL in a new tab
|
||||
window.open(result.data, '_blank');
|
||||
setShowCreatePRDialog(false);
|
||||
// Reset form
|
||||
setPrTitle('');
|
||||
setPrBody('');
|
||||
setPrBaseBranch('main');
|
||||
} else {
|
||||
setError(result.message || 'Failed to create GitHub PR');
|
||||
}
|
||||
} else {
|
||||
setError('Failed to create GitHub PR');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to create GitHub PR');
|
||||
} finally {
|
||||
setCreatingPR(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelCreatePR = () => {
|
||||
setShowCreatePRDialog(false);
|
||||
// Reset form to empty state - will be auto-filled again when reopened
|
||||
setPrTitle('');
|
||||
setPrBody('');
|
||||
setPrBaseBranch('main');
|
||||
};
|
||||
|
||||
const getChunkClassName = (chunkType: DiffChunkType) => {
|
||||
const baseClass = 'font-mono text-sm whitespace-pre py-1 flex';
|
||||
|
||||
switch (chunkType) {
|
||||
case 'Insert':
|
||||
return `${baseClass} bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200 border-l-2 border-green-400 dark:border-green-500`;
|
||||
case 'Delete':
|
||||
return `${baseClass} bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 border-l-2 border-red-400 dark:border-red-500`;
|
||||
case 'Equal':
|
||||
default:
|
||||
return `${baseClass} text-muted-foreground`;
|
||||
}
|
||||
};
|
||||
|
||||
const getChunkPrefix = (chunkType: DiffChunkType) => {
|
||||
switch (chunkType) {
|
||||
case 'Insert':
|
||||
return '+';
|
||||
case 'Delete':
|
||||
return '-';
|
||||
case 'Equal':
|
||||
default:
|
||||
return ' ';
|
||||
}
|
||||
};
|
||||
|
||||
interface ProcessedLine {
|
||||
content: string;
|
||||
chunkType: DiffChunkType;
|
||||
oldLineNumber?: number;
|
||||
newLineNumber?: number;
|
||||
}
|
||||
|
||||
interface ProcessedSection {
|
||||
type: 'context' | 'change' | 'expanded';
|
||||
lines: ProcessedLine[];
|
||||
expandKey?: string;
|
||||
expandedAbove?: boolean;
|
||||
expandedBelow?: boolean;
|
||||
}
|
||||
|
||||
const processFileChunks = (chunks: DiffChunk[], fileIndex: number) => {
|
||||
const CONTEXT_LINES = 3;
|
||||
const lines: ProcessedLine[] = [];
|
||||
let oldLineNumber = 1;
|
||||
let newLineNumber = 1;
|
||||
|
||||
// Convert chunks to lines with line numbers
|
||||
chunks.forEach((chunk) => {
|
||||
const chunkLines = chunk.content.split('\n');
|
||||
chunkLines.forEach((line, index) => {
|
||||
if (index < chunkLines.length - 1 || line !== '') {
|
||||
// Skip empty last line from split
|
||||
const processedLine: ProcessedLine = {
|
||||
content: line,
|
||||
chunkType: chunk.chunk_type,
|
||||
};
|
||||
|
||||
// Set line numbers based on chunk type
|
||||
switch (chunk.chunk_type) {
|
||||
case 'Equal':
|
||||
processedLine.oldLineNumber = oldLineNumber++;
|
||||
processedLine.newLineNumber = newLineNumber++;
|
||||
break;
|
||||
case 'Delete':
|
||||
processedLine.oldLineNumber = oldLineNumber++;
|
||||
// No new line number for deletions
|
||||
break;
|
||||
case 'Insert':
|
||||
processedLine.newLineNumber = newLineNumber++;
|
||||
// No old line number for insertions
|
||||
break;
|
||||
}
|
||||
|
||||
lines.push(processedLine);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const sections: ProcessedSection[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
if (line.chunkType === 'Equal') {
|
||||
// Look for the next change or end of file
|
||||
let nextChangeIndex = i + 1;
|
||||
while (
|
||||
nextChangeIndex < lines.length &&
|
||||
lines[nextChangeIndex].chunkType === 'Equal'
|
||||
) {
|
||||
nextChangeIndex++;
|
||||
}
|
||||
|
||||
const contextLength = nextChangeIndex - i;
|
||||
const hasNextChange = nextChangeIndex < lines.length;
|
||||
const hasPrevChange =
|
||||
sections.length > 0 &&
|
||||
sections[sections.length - 1].type === 'change';
|
||||
|
||||
if (
|
||||
contextLength <= CONTEXT_LINES * 2 ||
|
||||
(!hasPrevChange && !hasNextChange) ||
|
||||
showAllUnchanged
|
||||
) {
|
||||
// Show all context if it's short, no changes around it, or global toggle is on
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(i, nextChangeIndex),
|
||||
});
|
||||
} else {
|
||||
// Split into context sections with expandable middle
|
||||
if (hasPrevChange) {
|
||||
// Add context after previous change
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(i, i + CONTEXT_LINES),
|
||||
});
|
||||
i += CONTEXT_LINES;
|
||||
}
|
||||
|
||||
if (hasNextChange) {
|
||||
// Add expandable section
|
||||
const expandStart = hasPrevChange ? i : i + CONTEXT_LINES;
|
||||
const expandEnd = nextChangeIndex - CONTEXT_LINES;
|
||||
|
||||
if (expandEnd > expandStart) {
|
||||
const expandKey = `${fileIndex}-${expandStart}-${expandEnd}`;
|
||||
const isExpanded =
|
||||
expandedSections.has(expandKey) || showAllUnchanged;
|
||||
|
||||
if (isExpanded) {
|
||||
sections.push({
|
||||
type: 'expanded',
|
||||
lines: lines.slice(expandStart, expandEnd),
|
||||
expandKey,
|
||||
});
|
||||
} else {
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: [],
|
||||
expandKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add context before next change
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(
|
||||
nextChangeIndex - CONTEXT_LINES,
|
||||
nextChangeIndex
|
||||
),
|
||||
});
|
||||
} else if (!hasPrevChange) {
|
||||
// No changes around, just show first few lines
|
||||
sections.push({
|
||||
type: 'context',
|
||||
lines: lines.slice(i, i + CONTEXT_LINES),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
i = nextChangeIndex;
|
||||
} else {
|
||||
// Found a change, collect all consecutive changes
|
||||
const changeStart = i;
|
||||
while (i < lines.length && lines[i].chunkType !== 'Equal') {
|
||||
i++;
|
||||
}
|
||||
|
||||
sections.push({
|
||||
type: 'change',
|
||||
lines: lines.slice(changeStart, i),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return sections;
|
||||
};
|
||||
|
||||
const toggleExpandSection = (expandKey: string) => {
|
||||
setExpandedSections((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(expandKey)) {
|
||||
newSet.delete(expandKey);
|
||||
} else {
|
||||
newSet.add(expandKey);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteFileClick = (filePath: string) => {
|
||||
setFileToDelete(filePath);
|
||||
};
|
||||
|
||||
const handleConfirmDelete = async () => {
|
||||
if (!fileToDelete || !projectId || !taskId || !attemptId) return;
|
||||
|
||||
try {
|
||||
setDeletingFiles((prev) => new Set(prev).add(fileToDelete));
|
||||
const response = await makeRequest(
|
||||
`/api/projects/${projectId}/tasks/${taskId}/attempts/${attemptId}/delete-file?file_path=${encodeURIComponent(
|
||||
fileToDelete
|
||||
)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
}
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const result: ApiResponse<null> = await response.json();
|
||||
if (result.success) {
|
||||
// Refresh the diff to show updated state
|
||||
fetchDiff();
|
||||
} else {
|
||||
setError(result.message || 'Failed to delete file');
|
||||
}
|
||||
} else {
|
||||
setError('Failed to delete file');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to delete file');
|
||||
} finally {
|
||||
setDeletingFiles((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(fileToDelete);
|
||||
return newSet;
|
||||
});
|
||||
setFileToDelete(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelDelete = () => {
|
||||
setFileToDelete(null);
|
||||
};
|
||||
|
||||
if (loading || branchStatusLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-foreground mx-auto mb-4"></div>
|
||||
<p className="text-muted-foreground">Loading diff...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-destructive mb-4">{error}</p>
|
||||
<Button onClick={handleBackClick} variant="outline">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Task
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button onClick={handleBackClick} variant="outline" size="sm">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Back to Task
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold flex items-center gap-2">
|
||||
<FileText className="h-6 w-6" />
|
||||
Compare Changes
|
||||
</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
{/* Branch Status */}
|
||||
{!branchStatusLoading && branchStatus && (
|
||||
<div className="flex items-center gap-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{branchStatus.up_to_date ? (
|
||||
<span className="text-green-600">Up to date</span>
|
||||
) : branchStatus.is_behind === true && !branchStatus.merged ? (
|
||||
<span className="text-orange-600">
|
||||
{branchStatus.commits_behind} commit
|
||||
{branchStatus.commits_behind !== 1 ? 's' : ''} behind{' '}
|
||||
{branchStatus.base_branch_name}
|
||||
</span>
|
||||
) : !branchStatus.merged ? (
|
||||
<span className="text-blue-600">
|
||||
{branchStatus.commits_ahead} commit
|
||||
{branchStatus.commits_ahead !== 1 ? 's' : ''} ahead of{' '}
|
||||
{branchStatus.base_branch_name}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{branchStatus.has_uncommitted_changes && (
|
||||
<div className="flex items-center gap-1 text-yellow-600">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span>Uncommitted changes</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Status Messages */}
|
||||
{branchStatus?.merged && (
|
||||
<div className="text-green-600 text-sm font-medium">
|
||||
✓ Changes have been merged
|
||||
</div>
|
||||
)}
|
||||
{rebaseSuccess && (
|
||||
<div className="text-green-600 text-sm">
|
||||
Branch rebased successfully!
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center gap-2">
|
||||
{branchStatus &&
|
||||
branchStatus.is_behind === true &&
|
||||
!branchStatus.merged && (
|
||||
<Button
|
||||
onClick={handleRebaseClick}
|
||||
disabled={rebasing || branchStatusLoading}
|
||||
variant="outline"
|
||||
className="border-orange-300 text-orange-700 hover:bg-orange-50"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`mr-2 h-4 w-4 ${rebasing ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
{rebasing
|
||||
? 'Rebasing...'
|
||||
: `Rebase onto ${branchStatus.base_branch_name}`}
|
||||
</Button>
|
||||
)}
|
||||
{!branchStatus?.merged && (
|
||||
<>
|
||||
<Button
|
||||
onClick={handleCreatePRClick}
|
||||
disabled={
|
||||
creatingPR ||
|
||||
!diff ||
|
||||
diff.files.length === 0 ||
|
||||
Boolean(branchStatus?.is_behind)
|
||||
}
|
||||
variant="outline"
|
||||
className="border-blue-300 text-blue-700 hover:bg-blue-50"
|
||||
>
|
||||
<GitPullRequest className="mr-2 h-4 w-4" />
|
||||
{creatingPR ? 'Creating PR...' : 'Create PR'}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleMergeClick}
|
||||
disabled={
|
||||
merging ||
|
||||
!diff ||
|
||||
diff.files.length === 0 ||
|
||||
Boolean(branchStatus?.is_behind)
|
||||
}
|
||||
className="bg-green-600 hover:bg-green-700 disabled:bg-gray-400"
|
||||
>
|
||||
{merging ? 'Merging...' : 'Merge Changes'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="text-lg">
|
||||
Diff: Base Commit vs. Current Worktree
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Shows changes made in the task attempt worktree compared to the
|
||||
base commit
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowAllUnchanged(!showAllUnchanged)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{showAllUnchanged ? (
|
||||
<>
|
||||
<EyeOff className="h-4 w-4" />
|
||||
Hide Unchanged
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Eye className="h-4 w-4" />
|
||||
Show All Unchanged
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!diff || diff.files.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
|
||||
<p>No changes detected</p>
|
||||
<p className="text-sm">
|
||||
The worktree is identical to the base commit
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{diff.files.map((file, fileIndex) => (
|
||||
<div
|
||||
key={fileIndex}
|
||||
className="border rounded-lg overflow-hidden"
|
||||
>
|
||||
<div className="bg-muted px-3 py-2 border-b flex items-center justify-between">
|
||||
<p className="text-sm font-medium text-muted-foreground font-mono">
|
||||
{file.path}
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDeleteFileClick(file.path)}
|
||||
disabled={deletingFiles.has(file.path)}
|
||||
className="text-red-600 hover:text-red-800 hover:bg-red-50 h-8 px-3 gap-1"
|
||||
title={`Delete ${file.path}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
{deletingFiles.has(file.path)
|
||||
? 'Deleting...'
|
||||
: 'Delete File'}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-[600px] overflow-y-auto">
|
||||
{processFileChunks(file.chunks, fileIndex).map(
|
||||
(section, sectionIndex) => {
|
||||
if (
|
||||
section.type === 'context' &&
|
||||
section.lines.length === 0 &&
|
||||
section.expandKey &&
|
||||
!showAllUnchanged
|
||||
) {
|
||||
// Render expand button (only when global toggle is off)
|
||||
const lineCount =
|
||||
parseInt(section.expandKey.split('-')[2]) -
|
||||
parseInt(section.expandKey.split('-')[1]);
|
||||
return (
|
||||
<div key={`expand-${section.expandKey}`}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
toggleExpandSection(section.expandKey!)
|
||||
}
|
||||
className="w-full h-8 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-950/50 border-t border-b border-gray-200 dark:border-gray-700 rounded-none"
|
||||
>
|
||||
<ChevronDown className="h-3 w-3 mr-1" />
|
||||
Show {lineCount} more lines
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Render lines (context, change, or expanded)
|
||||
return (
|
||||
<div key={`section-${sectionIndex}`}>
|
||||
{section.type === 'expanded' &&
|
||||
section.expandKey &&
|
||||
!showAllUnchanged && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
toggleExpandSection(section.expandKey!)
|
||||
}
|
||||
className="w-full h-8 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-950/50 border-t border-b border-gray-200 dark:border-gray-700 rounded-none"
|
||||
>
|
||||
<ChevronUp className="h-3 w-3 mr-1" />
|
||||
Hide expanded lines
|
||||
</Button>
|
||||
)}
|
||||
{section.lines.map((line, lineIndex) => (
|
||||
<div
|
||||
key={`${sectionIndex}-${lineIndex}`}
|
||||
className={getChunkClassName(line.chunkType)}
|
||||
>
|
||||
<div className="flex-shrink-0 w-16 px-2 text-xs text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 select-none">
|
||||
<span className="inline-block w-6 text-right">
|
||||
{line.oldLineNumber || ''}
|
||||
</span>
|
||||
<span className="inline-block w-6 text-right ml-1">
|
||||
{line.newLineNumber || ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1 px-3">
|
||||
<span className="inline-block w-4">
|
||||
{getChunkPrefix(line.chunkType)}
|
||||
</span>
|
||||
<span>{line.content}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Delete File Confirmation Dialog */}
|
||||
<Dialog open={!!fileToDelete} onOpenChange={() => handleCancelDelete()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete File</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete the file{' '}
|
||||
<span className="font-mono font-medium">"{fileToDelete}"</span>?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<div className="bg-red-50 border border-red-200 rounded-md p-3">
|
||||
<p className="text-sm text-red-800">
|
||||
<strong>Warning:</strong> This action will permanently remove
|
||||
the entire file from the worktree. This cannot be undone.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancelDelete}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleConfirmDelete}
|
||||
disabled={deletingFiles.has(fileToDelete || '')}
|
||||
>
|
||||
{deletingFiles.has(fileToDelete || '')
|
||||
? 'Deleting...'
|
||||
: 'Delete File'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Uncommitted Changes Warning Dialog */}
|
||||
<Dialog
|
||||
open={showUncommittedWarning}
|
||||
onOpenChange={() => handleCancelMergeWithUncommitted()}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Uncommitted Changes Detected</DialogTitle>
|
||||
<DialogDescription>
|
||||
There are uncommitted changes in the worktree that will be
|
||||
included in the merge.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-md p-3">
|
||||
<p className="text-sm text-yellow-800">
|
||||
<strong>Warning:</strong> The worktree contains uncommitted
|
||||
changes (modified, added, or deleted files) that have not been
|
||||
committed to git. These changes will be permanently merged into
|
||||
the {branchStatus?.base_branch_name || 'base'} branch.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCancelMergeWithUncommitted}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirmMergeWithUncommitted}
|
||||
disabled={merging}
|
||||
className="bg-yellow-600 hover:bg-yellow-700"
|
||||
>
|
||||
{merging ? 'Merging...' : 'Merge Anyway'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Create PR Dialog */}
|
||||
<Dialog
|
||||
open={showCreatePRDialog}
|
||||
onOpenChange={() => handleCancelCreatePR()}
|
||||
>
|
||||
<DialogContent className="sm:max-w-[525px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create GitHub Pull Request</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a pull request for this task attempt on GitHub.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-title">Title</Label>
|
||||
<Input
|
||||
id="pr-title"
|
||||
value={prTitle}
|
||||
onChange={(e) => setPrTitle(e.target.value)}
|
||||
placeholder="Enter PR title"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-body">Description (optional)</Label>
|
||||
<Textarea
|
||||
id="pr-body"
|
||||
value={prBody}
|
||||
onChange={(e) => setPrBody(e.target.value)}
|
||||
placeholder="Enter PR description"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-base">Base Branch</Label>
|
||||
<Input
|
||||
id="pr-base"
|
||||
value={prBaseBranch}
|
||||
onChange={(e) => setPrBaseBranch(e.target.value)}
|
||||
placeholder="main"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleCancelCreatePR}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirmCreatePR}
|
||||
disabled={creatingPR || !prTitle.trim()}
|
||||
className="bg-blue-600 hover:bg-blue-700"
|
||||
>
|
||||
{creatingPR ? 'Creating...' : 'Create PR'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -82,6 +82,10 @@ export type WorktreeDiff = { files: Array<FileDiff>, };
|
||||
|
||||
export type BranchStatus = { is_behind: boolean, commits_behind: number, commits_ahead: number, up_to_date: boolean, merged: boolean, has_uncommitted_changes: boolean, base_branch_name: string, };
|
||||
|
||||
export type ExecutionState = "NotStarted" | "SetupRunning" | "SetupComplete" | "SetupFailed" | "CodingAgentRunning" | "CodingAgentComplete" | "CodingAgentFailed" | "Complete";
|
||||
|
||||
export type TaskAttemptState = { execution_state: ExecutionState, has_changes: boolean, has_setup_script: boolean, setup_process_id: string | null, coding_agent_process_id: string | null, };
|
||||
|
||||
export type ExecutionProcess = { id: string, task_attempt_id: string, process_type: ExecutionProcessType, executor_type: string | null, status: ExecutionProcessStatus, command: string, args: string | null, working_directory: string, stdout: string | null, stderr: string | null, exit_code: bigint | null, started_at: string, completed_at: string | null, created_at: string, updated_at: string, };
|
||||
|
||||
export type ExecutionProcessSummary = { id: string, task_attempt_id: string, process_type: ExecutionProcessType, executor_type: string | null, status: ExecutionProcessStatus, command: string, args: string | null, working_directory: string, exit_code: bigint | null, started_at: string, completed_at: string | null, created_at: string, updated_at: string, };
|
||||
@@ -100,6 +104,14 @@ export type CreateExecutorSession = { task_attempt_id: string, execution_process
|
||||
|
||||
export type UpdateExecutorSession = { session_id: string | null, prompt: string | null, summary: string | null, };
|
||||
|
||||
export type NormalizedConversation = { entries: Array<NormalizedEntry>, session_id: string | null, executor_type: string, prompt: string | null, summary: string | null, };
|
||||
|
||||
export type NormalizedEntry = { timestamp: string | null, entry_type: NormalizedEntryType, content: string, };
|
||||
|
||||
export type NormalizedEntryType = { "type": "user_message" } | { "type": "assistant_message" } | { "type": "tool_use", tool_name: string, action_type: ActionType, } | { "type": "system_message" } | { "type": "thinking" };
|
||||
|
||||
export type ActionType = { "action": "file_read", path: string, } | { "action": "file_write", path: string, } | { "action": "command_run", command: string, } | { "action": "search", query: string, } | { "action": "web_fetch", url: string, } | { "action": "task_create", description: string, } | { "action": "other", description: string, };
|
||||
|
||||
// Generated constants
|
||||
export const EXECUTOR_TYPES: string[] = [
|
||||
"echo",
|
||||
|
||||
Reference in New Issue
Block a user