kgraph-mcp-agent-platform / docs /progress /mvp3_dynamic_ui_strategy.md
BasalGanglia's picture
πŸ† Multi-Track Hackathon Submission
1f2d50a verified

A newer version of the Gradio SDK is available: 6.1.0

Upgrade

MVP 3 Dynamic UI Strategy: Interactive Prompt Filling Components

Task ID: 43
Status: In Progress
Date: 2025-06-08
Author: Claude 4.0 Development Agent


🎯 Strategic Decision Summary

CHOSEN STRATEGY: Pre-defined Maximum Input Fields (Option 1)

After comprehensive analysis, the pre-defined maximum input approach is optimal for MVP 3 Sprint 1 implementation.


πŸ“Š Current State Analysis

Existing UI Architecture

  • Clean MVP 2 Implementation: Professional Gradio interface with custom CSS
  • Single Output Model: handle_find_tools() returns dict to gr.JSON component
  • Static Display: Input variables shown as read-only information in JSON format
  • Proven Performance: Sub-400ms response times with 102 tests passing

Input Variable Requirements Analysis

Based on data/initial_prompts.json analysis:

Prompt Variables Complexity Example
Basic Text Summary 1 Simple input_text
Structured Document 3 Medium document_type, focus_areas, content
Customer Feedback 2 Medium product_service, feedback_text
Social Monitoring 3 Medium platform, topic, social_content
Accessibility Caption 3 Medium context, key_elements, target_audience
Creative Content 4 Complex tone, content_type, purpose, highlight_aspects
Security Audit 4 Complex language, application_type, security_concerns, code_snippet
Code Quality Review 4 Complex language, team_type, coding_standards, code_block

Key Insights:

  • Range: 1-4 input variables per prompt
  • Distribution: 37.5% (3 prompts) have 3+ variables, 25% have 4 variables
  • Recommendation: MAX_PROMPT_INPUTS = 5 provides comfortable buffer

πŸ—οΈ Strategy Options Evaluation

Option 1: Pre-defined Maximum Input Fields βœ… CHOSEN

Implementation:

  • Create 5 gr.Textbox components in UI layout (initially visible=False)
  • Show/hide and update labels dynamically based on selected prompt
  • Use gr.update() for reactive state management

Pros:

  • βœ… Gradio State Simplicity: Minimal complexity for reactive updates
  • βœ… Development Speed: Fast implementation for hackathon timeline
  • βœ… Predictable Behavior: Fixed components reduce debugging complexity
  • βœ… User Experience: Smooth, consistent transitions
  • βœ… Performance: No component creation/destruction overhead
  • βœ… Maintenance: Easy to understand and modify

Cons:

  • ⚠️ Fixed Limit: Cannot handle prompts with >5 variables (acceptable limitation)
  • ⚠️ Minor Overhead: Unused components exist in DOM (negligible impact)

Option 2: Dynamic Group Rendering

Implementation:

  • Use gr.Group with conditional component creation
  • More complex state management with Gradio's reactive model

Pros:

  • βœ… Flexibility: Can handle any number of variables
  • βœ… Efficiency: Only creates needed components

Cons:

  • ❌ Complexity: More difficult state management
  • ❌ Development Time: Longer implementation for complex reactive patterns
  • ❌ Risk: Higher chance of Gradio state inconsistencies
  • ❌ Debugging: More complex to troubleshoot

Option 3: HTML/JS Injection

Implementation:

  • Custom HTML/JavaScript for dynamic input generation
  • Breaks out of Gradio's Python-first model

Cons:

  • ❌ Gradio Integration: Poor integration with Gradio's reactive system
  • ❌ Maintenance: Mixed technology stack complexity
  • ❌ User Experience: Potential inconsistencies with Gradio styling

🎨 UI Flow & User Interaction Design

User Journey Flow:

1. User enters query β†’ "analyze customer sentiment"
2. Click "Generate Action Plan" button
3. System displays tool+prompt combination in JSON
4. **NEW:** Input fields appear below JSON results
5. **NEW:** Execute button becomes visible
6. User fills input fields β†’ "mobile app", "crashes frequently"
7. **FUTURE:** User clicks Execute β†’ simulated results shown

Visual Hierarchy:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Query Input & Generate Action Plan Button   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ JSON Results (existing MVP 2 functionality) β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ ✨ NEW: Interactive Input Fields Section    β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ πŸ“ Fill Prompt Variables                β”‚ β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚
β”‚ β”‚ β”‚ Product/Service β”‚ β”‚ Feedback Text   β”‚ β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚
β”‚ β”‚ [πŸš€ Execute Plan (Simulated)]          β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ ✨ FUTURE: Execution Results Area          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Interaction States:

  1. Initial State: All input fields hidden, execute button hidden
  2. Plan Generated: Relevant input fields visible with proper labels
  3. Fields Populated: Execute button enabled (future sprint)
  4. Executing: Loading state with spinner (future sprint)
  5. Results Shown: Execution output displayed (future sprint)

πŸ”§ Technical Implementation Approach

Configuration Constants:

# Configuration for MVP 3
MAX_PROMPT_INPUTS = 5  # Covers 100% of current prompts with buffer
PROMPT_INPUT_PREFIX = "prompt_input_"  # Element ID prefix for testing

New UI Components:

# Inside create_gradio_interface() after results_output_json
with gr.Column(visible=False) as prompt_inputs_group:
    gr.Markdown("### πŸ“ Fill Prompt Variables")
    gr.Markdown("*Complete the required information for your selected action plan*")
    
    # Pre-defined input fields
    prompt_input_fields = []
    for i in range(MAX_PROMPT_INPUTS):
        field = gr.Textbox(
            label=f"Input {i+1}",  # Will be updated dynamically
            visible=False,
            interactive=True,
            lines=2,  # Allow for longer inputs like code snippets
            elem_id=f"{PROMPT_INPUT_PREFIX}{i}",
            placeholder="Enter value..."
        )
        prompt_input_fields.append(field)
    
    # Execute button (for MVP 3 Sprint 2)
    execute_button = gr.Button(
        "πŸš€ Execute Plan (Simulated)",
        visible=False,
        variant="primary",
        elem_id="execute_plan_button"
    )

# Execution results area (for MVP 3 Sprint 2)
execution_output_display = gr.Markdown(
    "", 
    elem_id="execution_results",
    label="🎯 Execution Results"
)

Enhanced State Management:

def handle_find_tools(query: str) -> tuple:
    """Enhanced return signature for MVP 3 dynamic inputs."""
    # ... existing logic for JSON results ...
    
    # Initialize dynamic input updates
    textbox_updates = []
    prompt_inputs_group_update = gr.Column.update(visible=False)
    execute_button_update = gr.Button.update(visible=False)
    execution_output_update = gr.Markdown.update(value="")
    
    # Check if we have planned steps with input variables
    if planned_steps and planned_steps[0].prompt.input_variables:
        current_plan = planned_steps[0]  # Focus on first/top plan
        input_vars = current_plan.prompt.input_variables
        
        # Show input group if variables exist
        prompt_inputs_group_update = gr.Column.update(visible=True)
        execute_button_update = gr.Button.update(visible=True)
        
        # Configure each textbox
        for i in range(MAX_PROMPT_INPUTS):
            if i < len(input_vars):
                var_name = input_vars[i]
                textbox_updates.append(gr.Textbox.update(
                    label=f"πŸ“ {_format_variable_label(var_name)}",
                    visible=True,
                    placeholder=f"Enter {_get_variable_description(var_name)}",
                    value="",  # Clear previous values
                    interactive=True
                ))
            else:
                textbox_updates.append(gr.Textbox.update(
                    visible=False,
                    value=""
                ))
    else:
        # No variables or no plans - hide all input fields
        for _ in range(MAX_PROMPT_INPUTS):
            textbox_updates.append(gr.Textbox.update(
                visible=False,
                value=""
            ))
    
    return (
        results_json,                    # Existing JSON output
        prompt_inputs_group_update,      # Group visibility
        *textbox_updates,                # Individual textbox updates (5 items)
        execute_button_update,           # Execute button visibility
        execution_output_update          # Clear execution results
    )

def _format_variable_label(var_name: str) -> str:
    """Format variable name for better UX."""
    return var_name.replace('_', ' ').title()

Event Wiring Update:

# Updated find_button.click() event
find_button.click(
    fn=handle_find_tools,
    inputs=[query_input],
    outputs=[
        results_output_json,           # Existing output
        prompt_inputs_group,           # Group visibility
        *prompt_input_fields,          # All 5 textbox fields
        execute_button,                # Execute button
        execution_output_display       # Results display
    ],
    api_name="find_tools"
)

πŸ§ͺ Quality Assurance Strategy

Testing Approach:

  1. Component Testing: Individual gr.update() validation
  2. State Testing: Verify correct show/hide behavior
  3. Integration Testing: Full user workflow validation
  4. Performance Testing: Ensure <400ms response maintained
  5. Regression Testing: All existing MVP 2 functionality preserved

Edge Cases to Handle:

  • No Input Variables: Prompt with empty input_variables list
  • Single Variable: Simple prompts with one input
  • Maximum Variables: 4-5 variable prompts (stress test)
  • Rapid Query Changes: Quick succession of different prompts
  • Empty Query Results: No plans found scenario

Error States:

  • Component Failures: Graceful degradation if Gradio updates fail
  • State Inconsistencies: Fallback to hidden state
  • Performance Issues: Monitoring for response time degradation

πŸ”— Integration Points with Existing Code

Files to Modify:

  1. app.py: Primary implementation file

    • create_gradio_interface() function
    • handle_find_tools() function
    • Add new helper functions for variable formatting
  2. CSS Enhancements: Extend existing custom CSS

    .prompt-inputs-section {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 16px;
        margin: 16px 0;
        border: 1px solid #e9ecef;
    }
    
    .input-field {
        margin: 8px 0;
    }
    
    .execute-button {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        margin-top: 16px;
    }
    

Backward Compatibility:

  • βœ… All existing MVP 2 functionality preserved
  • βœ… JSON output format unchanged
  • βœ… API endpoints remain identical
  • βœ… Performance characteristics maintained

Dependencies:

  • βœ… No new external dependencies required
  • βœ… Uses existing Gradio capabilities
  • βœ… Compatible with current project structure

πŸ“ˆ Performance Considerations

Response Time Targets:

  • Existing: <400ms for tool suggestion
  • MVP 3: <450ms including dynamic UI updates (10% buffer)
  • Memory: Minimal increase from 5 additional Gradio components

Optimization Strategies:

  1. Minimal DOM Changes: Only update necessary components
  2. Efficient State Updates: Use targeted gr.update() calls
  3. Caching: Reuse formatted variable descriptions
  4. Progressive Enhancement: Add features without breaking core functionality

🎯 Success Metrics

Technical Metrics:

  • Dynamic input fields operational for 1-5 variables
  • No performance degradation (maintain <450ms target)
  • Zero Gradio console errors
  • All existing tests continue passing

User Experience Metrics:

  • Intuitive input field labeling and placeholders
  • Smooth visual transitions between states
  • Clear feedback for all interaction states
  • Mobile-responsive behavior maintained

Quality Metrics:

  • Code quality gates passing (lint, type, test)
  • Comprehensive test coverage for new functionality
  • Documentation updated appropriately
  • Ready for MVP 3 Sprint 2 implementation

πŸ”„ Future Sprint Dependencies

MVP 3 Sprint 2 Requirements:

This strategy creates the foundation for Sprint 2:

  1. Input Collection: Gather user values from dynamic fields
  2. Input Validation: Ensure required fields are completed
  3. Execute Button Logic: Wire execution functionality
  4. Result Display: Show simulated execution output

Interface Contract:

# Future function signature for Sprint 2
def handle_execute_plan(
    query: str,
    input_1: str, input_2: str, input_3: str, 
    input_4: str, input_5: str
) -> str:
    """Execute the planned step with user inputs."""
    # Implementation in Sprint 2
    pass

πŸ“ Implementation Plan Summary

Phase 1: UI Layout (30 minutes)

  • Add 5 predefined gr.Textbox components
  • Create container group with visibility control
  • Add execute button infrastructure
  • Update CSS styling

Phase 2: State Management (45 minutes)

  • Modify handle_find_tools() return signature
  • Implement dynamic label and placeholder generation
  • Create input field update logic
  • Handle edge cases and error states

Phase 3: Event Wiring (15 minutes)

  • Update find_button.click() outputs mapping
  • Test Gradio reactive updates
  • Verify state synchronization

Phase 4: Testing & Validation (30 minutes)

  • Component-level testing
  • Integration testing with various prompts
  • Performance validation
  • User experience verification

βœ… Decision Rationale

Why Pre-defined Maximum Input Fields is Optimal:

  1. Hackathon Timeline: Fast, reliable implementation
  2. Gradio Expertise: Leverages team's proven Gradio experience
  3. Risk Management: Low complexity reduces implementation risk
  4. Performance: Maintains excellent response times
  5. User Experience: Smooth, predictable interactions
  6. Maintenance: Easy to understand and extend
  7. Coverage: Handles 100% of current prompts with growth buffer

Strategic Confidence: 95% - This approach aligns perfectly with project goals, timeline, and technical constraints.


Status: Strategy Complete βœ…
Next Action: Begin Task 44 - Implementation Phase
Expected Implementation Time: 90-120 minutes
Risk Level: LOW - Building on proven foundation with validated approach