Skip to content

Commit

Permalink
make ui little better
Browse files Browse the repository at this point in the history
  • Loading branch information
vysakh0 committed Jul 20, 2024
1 parent 3ca7e88 commit 510c5e6
Show file tree
Hide file tree
Showing 15 changed files with 106 additions and 148 deletions.
2 changes: 1 addition & 1 deletion src/drd/cli/ask_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def handle_ask_command(ask, file, debug):
suggestion = suggest_file_alternative(file_path, project_metadata)
print_info(f"Suggestion: {suggestion}")
user_input = click.prompt(
"Do you want to proceed without this file? (y/n)", type=str)
"Do you want to proceed without this file?", type=str)
if user_input.lower() != 'y':
return

Expand Down
2 changes: 1 addition & 1 deletion src/drd/cli/monitor/error_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def monitoring_handle_error_with_dravid(error, line, monitor):
print_command_details(fix_commands)

user_input = monitor.get_user_input(
"Do you want to proceed with this fix? You will be able to stop anytime during the step. [y/N]: "
"Do you want to proceed with this fix? You will be able to stop anytime during the step. "
)

if user_input.lower() == 'y':
Expand Down
3 changes: 1 addition & 2 deletions src/drd/cli/monitor/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


def run_dev_server_with_monitoring(command: str):
print_info("Starting server monitor...")
error_handlers = {
r"(?:Cannot find module|Module not found|ImportError|No module named)": handle_module_not_found,
r"(?:SyntaxError|Expected|Unexpected token)": handle_syntax_error,
Expand All @@ -16,7 +15,7 @@ def run_dev_server_with_monitoring(command: str):
monitor = DevServerMonitor(current_dir, error_handlers, command)
try:
monitor.start()
print_info("Server monitor started. Press Ctrl+C to stop.")
print_info("👓 server monitor started. Press Ctrl+C to stop.")
while not monitor.should_stop.is_set():
pass
print_info("Server monitor has ended.")
Expand Down
5 changes: 3 additions & 2 deletions src/drd/cli/monitor/output_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import threading
import time
import select
from ...utils import print_info, print_error
from ...utils import print_info, print_error, print_prompt

MAX_RETRIES = 3

Expand Down Expand Up @@ -80,7 +80,8 @@ def _check_idle_state(self):
if (time_since_last_output > 5 and
not self.idle_prompt_shown and
not self.monitor.processing_input.is_set()):
print_info("\nNo more tasks to auto-process. What can I do next?")
print_prompt(
"\nNo more tasks to auto-process. What can I do next?")
self._show_options()
self.idle_prompt_shown = True

Expand Down
7 changes: 4 additions & 3 deletions src/drd/cli/monitor/server_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from queue import Queue
from .input_handler import InputHandler
from .output_monitor import OutputMonitor
from ...utils import print_info, print_success, print_error
from ...utils import print_info, print_success, print_error, print_header, print_prompt

MAX_RETRIES = 3

Expand All @@ -26,7 +26,8 @@ def __init__(self, project_dir: str, error_handlers: dict, command: str):
def start(self):
self.should_stop.clear()
self.restart_requested.clear()
print_info(f"Starting server with command: {self.command}")
print_header(
f"Starting Dravid AI along with your process/server: {self.command}")
try:
self.process = start_process(self.command, self.project_dir)
self.output_monitor.start()
Expand All @@ -41,7 +42,7 @@ def stop(self):
if self.process:
self.process.terminate()
self.process.wait()
print_info("Server monitor stopped.")
print_prompt("Server monitor stopped.")

def request_restart(self):
self.restart_requested.set()
Expand Down
16 changes: 4 additions & 12 deletions src/drd/cli/query/dynamic_command_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,8 @@ def execute_commands(commands, executor, metadata_manager, is_fix=False, debug=F

for i, cmd in enumerate(commands, 1):
step_description = "fix" if is_fix else "command"
print_step(i, total_steps,
f"Processing {cmd['type']} {step_description}...")

if cmd['type'] == 'explanation':
print_info(f"Explanation: {cmd['content']}")
all_outputs.append(
f"Step {i}/{total_steps}: Explanation - {cmd['content']}")
else:
Expand Down Expand Up @@ -49,7 +46,6 @@ def execute_commands(commands, executor, metadata_manager, is_fix=False, debug=F


def handle_shell_command(cmd, executor):
print_info(f"Executing shell command: {cmd['command']}")
output = executor.execute_shell_command(cmd['command'])
if isinstance(output, str) and output.startswith("Skipping"):
print_info(output)
Expand All @@ -63,8 +59,6 @@ def handle_shell_command(cmd, executor):


def handle_file_operation(cmd, executor, metadata_manager):
print_info(
f"Performing file operation: {cmd['operation']} on {cmd['filename']}")
operation_performed = executor.perform_file_operation(
cmd['operation'],
cmd['filename'],
Expand Down Expand Up @@ -133,8 +127,8 @@ def handle_error_with_dravid(error, cmd, executor, metadata_manager, depth=0, pr
previous_context, cmd, error_type, error_message, error_trace, project_context
)

print_info("Sending error information to dravid for analysis...")
print_info("LLM calls to be made: 1")
print_info(
"🏏 Sending error information to dravid for analysis(1 LLM call)...\n")

try:
fix_commands = call_dravid_api(
Expand All @@ -143,22 +137,20 @@ def handle_error_with_dravid(error, cmd, executor, metadata_manager, depth=0, pr
print_error(f"Error parsing dravid's response: {str(e)}")
return False

print_info("dravid's suggested fix:")
print_info("Applying dravid's suggested fix...")
print_info("🩺 Dravid's suggested fix:", indent=2)
print_info("🔨 Applying dravid's suggested fix...", indent=2)

fix_applied, step_completed, error_message, all_outputs = execute_commands(
fix_commands, executor, metadata_manager, is_fix=True, debug=debug
)

if fix_applied:
print_success("All fix steps successfully applied.")
print_info("Fix application details:")
click.echo(all_outputs)
return True
else:
print_error(f"Failed to apply the fix at step {step_completed}.")
print_error(f"Error message: {error_message}")
print_info("Fix application details:")
click.echo(all_outputs)

return handle_error_with_dravid(
Expand Down
56 changes: 26 additions & 30 deletions src/drd/cli/query/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
from ...utils.step_executor import Executor
from ...metadata.project_metadata import ProjectMetadataManager
from .dynamic_command_handler import handle_error_with_dravid, execute_commands
from ...utils import print_error, print_success, print_info, print_debug, print_warning, run_with_loader
from ...utils import print_error, print_success, print_info, print_debug, print_warning, print_step, print_header, run_with_loader
from ...utils.file_utils import get_file_content, fetch_project_guidelines, is_directory_empty
from .file_operations import get_files_to_modify
from ...utils.parser import parse_dravid_response


def execute_dravid_command(query, image_path, debug, instruction_prompt, warn=None):
print_info("Starting Dravid CLI tool..")
print_header("Starting Dravid AI ...")

if warn:
print_warning("Please make sure you are in a fresh directory.")
print_warning(
"If it is an existing project, please ensure you're in a git branch")
print_warning("Please ensure you review and commit(git) changes")
print("\n")

executor = Executor()
metadata_manager = ProjectMetadataManager(executor.current_dir)
Expand All @@ -23,27 +23,27 @@ def execute_dravid_command(query, image_path, debug, instruction_prompt, warn=No
project_context = metadata_manager.get_project_context()

if project_context:
print_info("Identifying related files to the query...")
print_info("LLM calls to be made: 1")
print_info("🔍 Identifying related files to the query...", indent=2)
print_info("(1 LLM call)", indent=4)
files_to_modify = run_with_loader(
lambda: get_files_to_modify(query, project_context),
"Analyzing project files"
)

print_info(
f"Found {len(files_to_modify)} potentially relevant files.")
f"Found {len(files_to_modify)} potentially relevant files.", indent=4)
if debug:
print_info("Possible files to be modified:")
print_info("Possible files to be modified:", indent=4)
for file in files_to_modify:
print(f" - {file}")
print_info(f" - {file}", indent=6)

print_info("Reading file contents...")
print_info("📂 Reading file contents...", indent=2)
file_contents = {}
for file in files_to_modify:
content = get_file_content(file)
if content:
file_contents[file] = content
print_info(f" - Read content of {file}")
print_info(f" - Read content of {file}", indent=4)

project_guidelines = fetch_project_guidelines(executor.current_dir)
file_context = "\n".join(
Expand All @@ -52,49 +52,45 @@ def execute_dravid_command(query, image_path, debug, instruction_prompt, warn=No
else:
is_empty = is_directory_empty(executor.current_dir)
print_info(
"No current project context found. Will create a new project in the current directory.")
"No current project context found. Will create a new project in the current directory.", indent=2)
full_query = f"User query: {query}"
full_query = f"Current directory is {'empty' if is_empty else 'not empty'}.\n\nUser query: {query}"

print_info("Preparing to send query to LLM...")
print_info("💡 Preparing to send query to LLM...", indent=2)
if image_path:
print_info(f"Processing image: {image_path}")
print_info("LLM calls to be made: 1")
print_info(f"Processing image: {image_path}", indent=4)
print_info("(1 LLM call)", indent=4)
commands = run_with_loader(
lambda: call_dravid_vision_api(
full_query, image_path, include_context=True, instruction_prompt=instruction_prompt),
"Analyzing image and generating response"
)
else:
print_info("Streaming response from LLM...")
print_info("LLM calls to be made: 1")
print_info("💬 Streaming response from LLM...", indent=2)
print_info("(1 LLM call)", indent=4)
xml_result = stream_dravid_api(
full_query, include_context=True, instruction_prompt=instruction_prompt, print_chunk=False)
commands = parse_dravid_response(xml_result)
# return None
if debug:
print_debug(f"Received {len(commands)} new command(s)")

if not commands:
print_error(
"Failed to parse Claude's response or no commands to execute.")
print("Actual result:", xml_result)
"Failed to parse LLM's response or no commands to execute.")
print_debug("Actual result: " + str(xml_result))
return

print_info(
f"Parsed {len(commands)} commands from Claude's response.")

# Execute commands using the new execute_commands function
success, step_completed, error_message, all_outputs = execute_commands(
commands, executor, metadata_manager, debug=debug)

if not success:
print_error(f"Failed to execute command at step {step_completed}.")
print_error(
f"Failed to execute command at step {step_completed}.")
print_error(f"Error message: {error_message}")
print_info("Attempting to fix the error...")
if handle_error_with_dravid(Exception(error_message), commands[step_completed-1], executor, metadata_manager, debug=debug):
print_info(
"Fix applied successfully. Continuing with the remaining commands.")
# Re-execute the remaining commands
"Fix applied successfully. Continuing with the remaining commands.", indent=2)
remaining_commands = commands[step_completed:]
success, _, error_message, additional_outputs = execute_commands(
remaining_commands, executor, metadata_manager, debug=debug)
Expand All @@ -103,10 +99,10 @@ def execute_dravid_command(query, image_path, debug, instruction_prompt, warn=No
print_error(
"Unable to fix the error. Skipping this command and continuing with the next.")

print_info("Execution details:")
print_info("Execution details:", indent=2)
click.echo(all_outputs)

print_success("Dravid CLI tool execution completed.")
print_success("Dravid CLI Tool execution completed.")
except Exception as e:
print_error(f"An unexpected error occurred: {str(e)}")
if debug:
Expand Down
6 changes: 5 additions & 1 deletion src/drd/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
print_step,
print_debug,
print_warning,
print_header,
print_prompt
)
from .loader import Loader, run_with_loader
__all__ = [
Expand All @@ -15,5 +17,7 @@
'print_debug',
'print_warning',
'Loader',
'run_with_loader'
'run_with_loader',
'print_header',
'print_prompt'
]
4 changes: 2 additions & 2 deletions src/drd/utils/pretty_print_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def pretty_print_xml_stream(chunk, state):
if operation_match and filename_match:
operation = operation_match.group(1).strip()
filename = filename_match.group(1).strip()
click.echo(click.style("\nFile Operation:",
click.echo(click.style("\n📂 File Operation:",
fg="yellow", bold=True), nl=False)
click.echo(f" {operation} {filename}")

Expand All @@ -63,7 +63,7 @@ def pretty_print_xml_stream(chunk, state):
if cdata_end != -1:
cdata_content = step_content[cdata_start+9:cdata_end]
click.echo(click.style(
"\nFile Content:", fg="cyan", bold=True))
"\n📄 File Content:", fg="cyan", bold=True))
click.echo(cdata_content)
elif step_type == 'shell':
command_match = re.search(
Expand Down
13 changes: 5 additions & 8 deletions src/drd/utils/step_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def perform_file_operation(self, operation, filename, content=None, force=False)
confirmation_box = create_confirmation_box(
filename, f"File operation is being carried out outside of the project directory. {operation.lower()} this file")
print(confirmation_box)
if not click.confirm(f"{Fore.YELLOW}Confirm {operation.lower()} [y/N]:{Style.RESET_ALL}", default=False):
if not click.confirm(f"{Fore.YELLOW}Confirm {operation.lower()} :{Style.RESET_ALL}", default=False):
print_info(f"File {operation.lower()} cancelled by user.")
return "Skipping this step"

Expand All @@ -73,7 +73,7 @@ def perform_file_operation(self, operation, filename, content=None, force=False)
preview = preview_file_changes(
operation, filename, new_content=content)
print(preview)
if click.confirm(f"{Fore.YELLOW}Confirm creation [y/N]:{Style.RESET_ALL}", default=False):
if click.confirm(f"{Fore.YELLOW}Confirm creation {Style.RESET_ALL}", default=False):
with open(full_path, 'w') as f:
f.write(content)
print_success(f"File created successfully: {filename}")
Expand Down Expand Up @@ -102,7 +102,7 @@ def perform_file_operation(self, operation, filename, content=None, force=False)
filename, f"{operation.lower()} this file")
print(confirmation_box)

if click.confirm(f"{Fore.YELLOW}Confirm update [y/N]:{Style.RESET_ALL}", default=False):
if click.confirm(f"{Fore.YELLOW}Confirm update {Style.RESET_ALL}", default=False):
with open(full_path, 'w') as f:
f.write(updated_content)
print_success(f"File updated successfully: {filename}")
Expand All @@ -126,7 +126,7 @@ def perform_file_operation(self, operation, filename, content=None, force=False)
confirmation_box = create_confirmation_box(
filename, f"{operation.lower()} this file")
print(confirmation_box)
if click.confirm(f"{Fore.YELLOW}Confirm deletion [y/N]:{Style.RESET_ALL}", default=False):
if click.confirm(f"{Fore.YELLOW}Confirm deletion {Style.RESET_ALL}", default=False):
try:
os.remove(full_path)
print_success(f"File deleted successfully: {filename}")
Expand Down Expand Up @@ -171,13 +171,10 @@ def execute_shell_command(self, command, timeout=300): # 5 minutes timeout
command, "execute this command")
print(confirmation_box)

if not click.confirm(f"{Fore.YELLOW}Confirm execution [y/N]:{Style.RESET_ALL}", default=False):
if not click.confirm(f"{Fore.YELLOW}Confirm execution {Style.RESET_ALL}", default=False):
print_info("Command execution cancelled by user.")
return 'Skipping this step...'

click.echo(
f"{Fore.YELLOW}Executing shell command: {command}{Style.RESET_ALL}")

if command.strip().startswith(('cd', 'chdir')):
return self._handle_cd_command(command)
elif command.strip().startswith(('source', '.')):
Expand Down
Loading

0 comments on commit 510c5e6

Please sign in to comment.