Class: Clacky::UI2::UIController
- Inherits:
-
Object
- Object
- Clacky::UI2::UIController
- Includes:
- Clacky::UIInterface
- Defined in:
- lib/clacky/ui2/ui_controller.rb
Overview
UIController is the MVC controller layer that coordinates UI state and user interactions
Instance Attribute Summary collapse
-
#config ⇒ Object
Returns the value of attribute config.
-
#inline_input ⇒ Object
readonly
Returns the value of attribute inline_input.
-
#input_area ⇒ Object
readonly
Returns the value of attribute input_area.
-
#layout ⇒ Object
readonly
Returns the value of attribute layout.
-
#renderer ⇒ Object
readonly
Returns the value of attribute renderer.
-
#running ⇒ Object
readonly
Returns the value of attribute running.
Instance Method Summary collapse
-
#append_output(content) ⇒ Object
Append output to the output area.
-
#clear_input ⇒ Object
Clear the input area.
-
#clear_progress ⇒ Object
Clear progress indicator.
-
#clear_progress_line ⇒ Object
Clear the progress line (remove last line).
-
#clear_progress_nonblocking ⇒ Object
Non-blocking variant of clear_progress, used by handle_submit so the user message appears on screen immediately without waiting for the progress thread to fully exit.
-
#display_session_history(user_messages) ⇒ Object
Display recent user messages when loading session.
-
#display_welcome_banner ⇒ Object
Display welcome banner with logo and agent info.
-
#filter_thinking_tags(content) ⇒ String
Filter out thinking tags from content Some models (e.g., MiniMax M2.1) wrap their reasoning in <think>…</think> tags.
-
#format_tool_call(name, args) ⇒ String
Format tool call for display.
-
#get_tool_instance(tool_name) ⇒ Object?
Get tool instance by name.
-
#handle_inline_input_key(key) ⇒ Object
Handle key input for InlineInput.
-
#handle_key(key) ⇒ Object
Handle keyboard input - delegate to InputArea or InlineInput.
-
#initialize(config = {}) ⇒ UIController
constructor
A new instance of UIController.
-
#initialize_and_show_banner(recent_user_messages: nil) ⇒ Object
Initialize screen and show banner (separate from input loop).
-
#input_loop ⇒ Object
Main input loop.
-
#log(message, level: :info) ⇒ Object
Log message to output area (use instead of puts).
-
#on_input(&block) ⇒ Object
Set callback for user input.
-
#on_interrupt(&block) ⇒ Object
Set callback for interrupt (Ctrl+C).
-
#on_mode_toggle(&block) ⇒ Object
Set callback for mode toggle (Shift+Tab).
-
#on_time_machine(&block) ⇒ Object
Set callback for time machine (ESC key).
-
#progress_active? ⇒ Boolean
Returns true if a progress indicator is currently active.
-
#request_confirmation(message, default: true) ⇒ Boolean, ...
Request confirmation from user (blocking).
-
#set_agent(agent, agent_profile = nil) ⇒ Object
Set agent for command suggestions.
-
#set_idle_status ⇒ Object
Set workspace status to idle (called when agent stops working).
-
#set_input_tips(message, type: :info) ⇒ Object
Set input tips message.
-
#set_skill_loader(skill_loader, agent_profile = nil) ⇒ Object
Set skill loader for command suggestions in the input area.
-
#set_working_status ⇒ Object
Set workspace status to working (called when agent starts working).
-
#show_assistant_message(content, files:) ⇒ Object
Show assistant message.
-
#show_command_output ⇒ Object
Show fullscreen command output view.
-
#show_complete(iterations:, cost:, duration: nil, cache_stats: nil, awaiting_user_feedback: false) ⇒ Object
Show completion status (only for tasks with more than 5 iterations).
-
#show_config_modal(current_config, test_callback: nil) ⇒ Hash?
Show configuration modal dialog with multi-model support.
-
#show_diff(old_content, new_content, max_lines: 50) ⇒ Object
Show diff between old and new content.
-
#show_error(message) ⇒ Object
Show error message.
-
#show_file_edit_preview(path) ⇒ Object
Show file operation preview (Edit tool).
-
#show_file_error(error_message) ⇒ Object
Show file operation error.
-
#show_file_write_preview(path, is_new_file:) ⇒ Object
Show file operation preview (Write tool).
-
#show_help ⇒ Object
Show help text.
-
#show_idle_status(phase:, message:) ⇒ Object
Show idle compression status (two-phase: start → end).
-
#show_info(message, prefix_newline: true) ⇒ Object
Show info message.
-
#show_progress(message = nil, prefix_newline: true, output_buffer: nil) ⇒ Object
Show progress indicator with dynamic elapsed time.
-
#show_shell_preview(command) ⇒ Object
Show shell command preview.
-
#show_success(message) ⇒ Object
Show success message.
-
#show_time_machine_menu(history) ⇒ Integer?
Show time machine menu for task undo/redo.
-
#show_token_usage(token_data) ⇒ Object
Display token usage statistics.
-
#show_tool_args(formatted_args) ⇒ Object
Show tool call arguments.
-
#show_tool_call(name, args) ⇒ Object
Show tool call.
-
#show_tool_error(error) ⇒ Object
Show tool error.
-
#show_tool_result(result) ⇒ Object
Show tool result.
-
#show_tool_stdout(lines) ⇒ Object
Receive a chunk of shell stdout from the on_output callback.
-
#show_warning(message) ⇒ Object
Show warning message.
-
#start ⇒ Object
Start the UI controller.
-
#start_input_loop ⇒ Object
Start input loop (separate from initialization).
-
#stop ⇒ Object
Stop the UI controller.
-
#stop_fullscreen_refresh_thread ⇒ Object
Stop the fullscreen refresh thread gracefully via flag + join.
-
#stop_progress_thread ⇒ Object
Stop the progress update thread gracefully.
-
#toggle_mode ⇒ Object
Toggle permission mode between confirm_safes and auto_approve.
-
#update_progress_line(content) ⇒ Object
Update the last line in output area (for progress indicator).
-
#update_sessionbar(tasks: nil, cost: nil, status: nil) ⇒ Object
Update session bar with current stats.
-
#update_todos(todos) ⇒ Object
Update todos display.
Constructor Details
#initialize(config = {}) ⇒ UIController
Returns a new instance of UIController.
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/clacky/ui2/ui_controller.rb', line 21 def initialize(config = {}) @renderer = ViewRenderer.new # Set theme if specified ThemeManager.set_theme(config[:theme]) if config[:theme] # Store configuration @config = { working_dir: config[:working_dir], mode: config[:mode], model: config[:model], theme: config[:theme] } # Initialize layout components @input_area = Components::InputArea.new @todo_area = Components::TodoArea.new @welcome_banner = Components::WelcomeBanner.new @inline_input = nil # Created when needed @layout = LayoutManager.new( input_area: @input_area, todo_area: @todo_area ) @running = false @input_callback = nil @interrupt_callback = nil @time_machine_callback = nil @tasks_count = 0 @total_cost = 0.0 @progress_thread = nil @progress_start_time = nil @progress_message = nil @last_diff_lines = nil end |
Instance Attribute Details
#config ⇒ Object
Returns the value of attribute config.
19 20 21 |
# File 'lib/clacky/ui2/ui_controller.rb', line 19 def config @config end |
#inline_input ⇒ Object (readonly)
Returns the value of attribute inline_input.
18 19 20 |
# File 'lib/clacky/ui2/ui_controller.rb', line 18 def inline_input @inline_input end |
#input_area ⇒ Object (readonly)
Returns the value of attribute input_area.
18 19 20 |
# File 'lib/clacky/ui2/ui_controller.rb', line 18 def input_area @input_area end |
#layout ⇒ Object (readonly)
Returns the value of attribute layout.
18 19 20 |
# File 'lib/clacky/ui2/ui_controller.rb', line 18 def layout @layout end |
#renderer ⇒ Object (readonly)
Returns the value of attribute renderer.
18 19 20 |
# File 'lib/clacky/ui2/ui_controller.rb', line 18 def renderer @renderer end |
#running ⇒ Object (readonly)
Returns the value of attribute running.
18 19 20 |
# File 'lib/clacky/ui2/ui_controller.rb', line 18 def running @running end |
Instance Method Details
#append_output(content) ⇒ Object
Append output to the output area
189 190 191 |
# File 'lib/clacky/ui2/ui_controller.rb', line 189 def append_output(content) @layout.append_output(content) end |
#clear_input ⇒ Object
Clear the input area
145 146 147 |
# File 'lib/clacky/ui2/ui_controller.rb', line 145 def clear_input @input_area.clear end |
#clear_progress ⇒ Object
Clear progress indicator
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 |
# File 'lib/clacky/ui2/ui_controller.rb', line 522 def clear_progress # Guard: if no progress is active, do nothing. # This makes clear_progress idempotent — safe to call multiple times # (e.g. once from handle_submit and again from handle_agent_exception). return unless progress_active? # Calculate elapsed time before stopping elapsed_time = @progress_start_time ? (Time.now - @progress_start_time).to_i : 0 # Stop the progress thread (blocks until thread exits or timeout) stop_progress_thread # stdout buffer no longer needed after command finishes @stdout_lines = nil # Update the final progress line to gray (stopped state) if @progress_message && elapsed_time > 0 final_output = @renderer.render_progress("#{@progress_message}… (#{elapsed_time}s)") update_progress_line(final_output) else clear_progress_line end end |
#clear_progress_line ⇒ Object
Clear the progress line (remove last line)
227 228 229 |
# File 'lib/clacky/ui2/ui_controller.rb', line 227 def clear_progress_line @layout.remove_last_line end |
#clear_progress_nonblocking ⇒ Object
Non-blocking variant of clear_progress, used by handle_submit so the user message appears on screen immediately without waiting for the progress thread to fully exit.
Strategy:
1. Snapshot elapsed time and message before touching any state.
2. Signal the progress thread to stop (sets flag + nulls start time)
so it will exit on its own next wake-up — no join here.
3. Immediately render the final (gray) progress line or remove it.
4. The thread finishes in the background; clear_progress called later
via the interrupt path is idempotent and will be a no-op.
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 |
# File 'lib/clacky/ui2/ui_controller.rb', line 557 def clear_progress_nonblocking return unless progress_active? elapsed_time = @progress_start_time ? (Time.now - @progress_start_time).to_i : 0 = @progress_message # Signal thread to stop without joining — it will exit on next loop tick @progress_start_time = nil @progress_output_buffer = nil @stdout_lines = nil @progress_thread_stop = true # Detach: let the thread die on its own; we do NOT join here @progress_thread = nil # Immediately update the visual progress line (no waiting) if && elapsed_time > 0 final_output = @renderer.render_progress("#{}… (#{elapsed_time}s)") update_progress_line(final_output) else clear_progress_line end end |
#display_session_history(user_messages) ⇒ Object
Display recent user messages when loading session
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 |
# File 'lib/clacky/ui2/ui_controller.rb', line 911 def display_session_history() theme = ThemeManager.current_theme # Show logo banner only append_output(@welcome_banner.render_logo(width: @layout.screen.width)) # Show simple header append_output(theme.format_text("Recent conversation:", :info)) # Display each user message with numbering .each_with_index do |msg, index| # Truncate long messages display_msg = if msg.length > 140 "#{msg[0..137]}..." else msg end # Show with number and indentation append_output(" #{index + 1}. #{display_msg}") end # Bottom spacing and continuation prompt append_output("") append_output(theme.format_text("Session restored. Feel free to continue with your next task.", :success)) end |
#display_welcome_banner ⇒ Object
Display welcome banner with logo and agent info
886 887 888 889 890 891 892 893 894 895 896 |
# File 'lib/clacky/ui2/ui_controller.rb', line 886 def content = @welcome_banner.render_full( working_dir: @config[:working_dir], mode: @config[:mode], width: @layout.screen.width ) append_output(content) # Check if API key is configured (show warning AFTER banner) check_api_key_configuration end |
#filter_thinking_tags(content) ⇒ String
Filter out thinking tags from content Some models (e.g., MiniMax M2.1) wrap their reasoning in <think>…</think> tags
379 380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'lib/clacky/ui2/ui_controller.rb', line 379 def (content) return content if content.nil? # Remove <think>...</think> blocks (multiline, case-insensitive) # Also handles variations like <thinking>...</thinking> filtered = content.gsub(%r{<think(?:ing)?>[\s\S]*?</think(?:ing)?>}mi, '') # Clean up multiple empty lines left behind (max 2 consecutive newlines) filtered.gsub!(/\n{3,}/, "\n\n") # Remove leading and trailing whitespace filtered.strip end |
#format_tool_call(name, args) ⇒ String
Format tool call for display
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 |
# File 'lib/clacky/ui2/ui_controller.rb', line 848 def format_tool_call(name, args) args_hash = args.is_a?(String) ? JSON.parse(args, symbolize_names: true) : args # Try to get tool instance for custom formatting tool = get_tool_instance(name) if tool begin return tool.format_call(args_hash) rescue StandardError # Fallback end end # Simple fallback "#{name}(...)" rescue JSON::ParserError "#{name}(...)" end |
#get_tool_instance(tool_name) ⇒ Object?
Get tool instance by name
870 871 872 873 874 875 876 877 878 879 880 881 882 883 |
# File 'lib/clacky/ui2/ui_controller.rb', line 870 def get_tool_instance(tool_name) # Convert tool_name to class name (e.g., "file_reader" -> "FileReader") class_name = tool_name.split('_').map(&:capitalize).join # Try to find the class in Clacky::Tools namespace if Clacky::Tools.const_defined?(class_name) tool_class = Clacky::Tools.const_get(class_name) tool_class.new else nil end rescue NameError nil end |
#handle_inline_input_key(key) ⇒ Object
Handle key input for InlineInput
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 |
# File 'lib/clacky/ui2/ui_controller.rb', line 1038 def handle_inline_input_key(key) # Get old line count BEFORE modification old_line_count = @inline_input.line_count result = @inline_input.handle_key(key) case result[:action] when :update # Update the output area with current input (considering wrapped lines) @layout.update_last_line(@inline_input.render, old_line_count) # Position cursor for inline input @layout.position_inline_input_cursor(@inline_input) when :submit, :cancel # InlineInput is done, will be cleaned up by request_confirmation after collect returns # Don't render anything here - let request_confirmation handle cleanup return when :toggle_expand # If there's command output available, show it; otherwise show diff if @stdout_lines && !@stdout_lines.empty? show_command_output else redisplay_diff end when :toggle_mode # Update mode and session bar info, but don't render yet current_mode = @config[:mode] new_mode = case current_mode.to_s when /confirm_safes/ "auto_approve" when /auto_approve/ "confirm_safes" else "auto_approve" end @config[:mode] = new_mode @mode_toggle_callback&.call(new_mode) # Update session bar data (will be rendered by request_confirmation's render_all) @input_area.( working_dir: @config[:working_dir], mode: @config[:mode], model: @config[:model], tasks: @tasks_count, cost: @total_cost ) end end |
#handle_key(key) ⇒ Object
Handle keyboard input - delegate to InputArea or InlineInput
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 |
# File 'lib/clacky/ui2/ui_controller.rb', line 965 def handle_key(key) # If in fullscreen mode, only handle Ctrl+O to exit if @layout.fullscreen_mode? if key == :ctrl_o # Signal the real-time refresh thread to stop gracefully, then join it. # Avoid Thread#kill which can interrupt the thread mid-render and # leave @render_mutex permanently locked. stop_fullscreen_refresh_thread @layout.exit_fullscreen # Restore main screen content after returning from alternate buffer @layout.rerender_all end return end # If InlineInput is active, delegate to it if @inline_input&.active? handle_inline_input_key(key) return end result = @input_area.handle_key(key) # Handle height change first if result[:height_changed] @layout.recalculate_layout end # Handle actions case result[:action] when :submit handle_submit(result[:data]) when :exit stop exit(0) when :interrupt # Stop progress indicator stop_progress_thread # Check if input area has content input_was_empty = @input_area.empty? # Notify CLI to handle interrupt (stop agent or exit) @interrupt_callback&.call(input_was_empty: input_was_empty) when :clear_output # Pass to callback with data for display @input_callback&.call("/clear", [], display: result[:data][:display]) when :scroll_up @layout.scroll_output_up when :scroll_down @layout.scroll_output_down when :help # Pass to callback with data for display @input_callback&.call("/help", [], display: result[:data][:display]) when :toggle_mode toggle_mode when :toggle_expand # If there's command output available, show it; otherwise show diff if @stdout_lines && !@stdout_lines.empty? show_command_output else redisplay_diff end when :time_machine # Trigger time machine callback @time_machine_callback&.call end # Always re-render input area after key handling @layout.render_input end |
#initialize_and_show_banner(recent_user_messages: nil) ⇒ Object
Initialize screen and show banner (separate from input loop)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/clacky/ui2/ui_controller.rb', line 65 def (recent_user_messages: nil) @running = true # Set session bar data before initializing screen @input_area.( working_dir: @config[:working_dir], mode: @config[:mode], model: @config[:model], tasks: @tasks_count, cost: @total_cost ) @layout.initialize_screen # Display welcome banner or session history if && !.empty? display_session_history() else end end |
#input_loop ⇒ Object
Main input loop
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 |
# File 'lib/clacky/ui2/ui_controller.rb', line 939 def input_loop @layout.screen.enable_raw_mode while @running # Process any pending resize events @layout.process_pending_resize key = @layout.screen.read_key(timeout: 0.1) next unless key handle_key(key) end rescue Clacky::AgentInterrupted # Signal.trap("INT") raised AgentInterrupted on the main thread. # Route through the normal Ctrl+C path so on_interrupt callback fires # (interrupt task thread if running, or exit if idle) instead of quitting blindly. handle_key(:ctrl_c) rescue => e stop raise e ensure @layout.screen.disable_raw_mode end |
#log(message, level: :info) ⇒ Object
Log message to output area (use instead of puts)
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
# File 'lib/clacky/ui2/ui_controller.rb', line 196 def log(, level: :info) theme = ThemeManager.current_theme output = case level when :debug # Gray dimmed text for debug messages theme.format_text(" [DEBUG] #{}", :thinking) when :info # Info symbol with normal text "#{theme.format_symbol(:info)} #{}" when :warning # Warning rendering @renderer.render_warning() when :error # Error rendering @renderer.render_error() else # Default to info "#{theme.format_symbol(:info)} #{}" end append_output(output) end |
#on_input(&block) ⇒ Object
Set callback for user input
158 159 160 |
# File 'lib/clacky/ui2/ui_controller.rb', line 158 def on_input(&block) @input_callback = block end |
#on_interrupt(&block) ⇒ Object
Set callback for interrupt (Ctrl+C)
164 165 166 |
# File 'lib/clacky/ui2/ui_controller.rb', line 164 def on_interrupt(&block) @interrupt_callback = block end |
#on_mode_toggle(&block) ⇒ Object
Set callback for mode toggle (Shift+Tab)
170 171 172 |
# File 'lib/clacky/ui2/ui_controller.rb', line 170 def on_mode_toggle(&block) @mode_toggle_callback = block end |
#on_time_machine(&block) ⇒ Object
Set callback for time machine (ESC key)
176 177 178 |
# File 'lib/clacky/ui2/ui_controller.rb', line 176 def on_time_machine(&block) @time_machine_callback = block end |
#progress_active? ⇒ Boolean
Returns true if a progress indicator is currently active. Used to guard calls to clear_progress so we don’t accidentally remove a non-progress line from the output buffer.
517 518 519 |
# File 'lib/clacky/ui2/ui_controller.rb', line 517 def progress_active? @progress_start_time != nil end |
#request_confirmation(message, default: true) ⇒ Boolean, ...
Request confirmation from user (blocking)
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 |
# File 'lib/clacky/ui2/ui_controller.rb', line 694 def request_confirmation(, default: true) # Show question in output with theme styling theme = ThemeManager.current_theme question_symbol = theme.format_symbol(:info) append_output("#{question_symbol} #{}") # Pause InputArea @input_area.pause @layout.recalculate_layout # Create InlineInput with styled prompt inline_input = Components::InlineInput.new( prompt: "Press Enter/y to approve(Shift+Tab for all), 'n' to reject, or type feedback: ", default: nil ) @inline_input = inline_input # Add inline input line to output (use layout to track position) @layout.append_output(inline_input.render) @layout.position_inline_input_cursor(inline_input) # Collect input (blocks until user presses Enter) result_text = inline_input.collect # Clean up - remove the inline input lines (handle wrapped lines) line_count = inline_input.line_count @layout.remove_last_line(line_count) # Append the final response to output if result_text.nil? append_output(theme.format_text(" [Cancelled]", :error)) else display_text = result_text.empty? ? (default ? "y" : "n") : result_text append_output(theme.format_text(" #{display_text}", :success)) end # Deactivate and clean up @inline_input = nil @input_area.resume @layout.recalculate_layout @layout.render_all # Parse result return nil if result_text.nil? # Cancelled response = result_text.strip.downcase case response when "y", "yes" then true when "n", "no" then false when "" then default else result_text # Return feedback text end end |
#set_agent(agent, agent_profile = nil) ⇒ Object
Set agent for command suggestions
183 184 185 |
# File 'lib/clacky/ui2/ui_controller.rb', line 183 def set_agent(agent, agent_profile = nil) @input_area.set_agent(agent, agent_profile) end |
#set_idle_status ⇒ Object
Set workspace status to idle (called when agent stops working)
646 647 648 649 650 651 |
# File 'lib/clacky/ui2/ui_controller.rb', line 646 def set_idle_status (status: 'idle') # Clear user tip when agent stops working @input_area.clear_user_tip @layout.render_input end |
#set_input_tips(message, type: :info) ⇒ Object
Set input tips message
152 153 154 |
# File 'lib/clacky/ui2/ui_controller.rb', line 152 def set_input_tips(, type: :info) @input_area.set_tips(, type: type) end |
#set_skill_loader(skill_loader, agent_profile = nil) ⇒ Object
Set skill loader for command suggestions in the input area
96 97 98 |
# File 'lib/clacky/ui2/ui_controller.rb', line 96 def set_skill_loader(skill_loader, agent_profile = nil) @input_area.set_skill_loader(skill_loader, agent_profile) end |
#set_working_status ⇒ Object
Set workspace status to working (called when agent starts working)
654 655 656 657 658 659 |
# File 'lib/clacky/ui2/ui_controller.rb', line 654 def set_working_status (status: 'working') # Show a random user tip with 40% probability when agent starts working @input_area.show_user_tip(probability: 0.4) @layout.render_input end |
#show_assistant_message(content, files:) ⇒ Object
Show assistant message
366 367 368 369 370 371 372 373 |
# File 'lib/clacky/ui2/ui_controller.rb', line 366 def (content, files:) # Filter out thinking tags from models like MiniMax M2.1 that use <think>...</think> filtered_content = (content) return if filtered_content.nil? || filtered_content.strip.empty? output = @renderer.(filtered_content) append_output(output) end |
#show_command_output ⇒ Object
Show fullscreen command output view
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 |
# File 'lib/clacky/ui2/ui_controller.rb', line 813 def show_command_output return unless @stdout_lines && !@stdout_lines.empty? return if @layout.fullscreen_mode? lines = build_command_output_lines @layout.enter_fullscreen(lines, hint: "Press Ctrl+O to return · Output updates in real-time") # Start background thread to refresh fullscreen content in real-time. # Use a dedicated stop flag so we can join() the thread cleanly and # avoid Thread#kill interrupting the thread while it holds @render_mutex. @fullscreen_refresh_stop = false @fullscreen_refresh_thread = Thread.new do until @fullscreen_refresh_stop || !@layout.fullscreen_mode? sleep 0.3 next if @fullscreen_refresh_stop || !@layout.fullscreen_mode? @layout.refresh_fullscreen(build_command_output_lines) end rescue StandardError # Silently handle thread errors end end |
#show_complete(iterations:, cost:, duration: nil, cache_stats: nil, awaiting_user_feedback: false) ⇒ Object
Show completion status (only for tasks with more than 5 iterations)
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
# File 'lib/clacky/ui2/ui_controller.rb', line 437 def show_complete(iterations:, cost:, duration: nil, cache_stats: nil, awaiting_user_feedback: false) # Update status back to 'idle' when task is complete (status: 'idle') # Clear user tip when agent stops working @input_area.clear_user_tip @layout.render_input # Don't show completion message if awaiting user feedback return if awaiting_user_feedback # Only show completion message for complex tasks (>5 iterations) return if iterations <= 5 cache_tokens = cache_stats&.dig(:cache_read_input_tokens) cache_requests = cache_stats&.dig(:total_requests) cache_hits = cache_stats&.dig(:cache_hit_requests) output = @renderer.render_task_complete( iterations: iterations, cost: cost, duration: duration, cache_tokens: cache_tokens, cache_requests: cache_requests, cache_hits: cache_hits ) append_output(output) end |
#show_config_modal(current_config, test_callback: nil) ⇒ Hash?
Show configuration modal dialog with multi-model support
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 |
# File 'lib/clacky/ui2/ui_controller.rb', line 1114 public def show_config_modal(current_config, test_callback: nil) modal = Components::ModalComponent.new loop do # Build menu choices choices = [] # Add model list current_config.models.each_with_index do |model, idx| is_current = (idx == current_config.current_model_index) model_name = model["model"] || "unnamed" masked_key = mask_api_key(model["api_key"]) # Add type badge if present type_badge = case model["type"] when "default" then "[default] " when "lite" then "[lite] " else "" end display_name = "#{type_badge}#{model_name} (#{masked_key})" choices << { name: display_name, value: { action: :switch, index: idx } } end # Add action buttons choices << { name: "─" * 50, disabled: true } choices << { name: "[+] Add New Model", value: { action: :add } } choices << { name: "[*] Edit Current Model", value: { action: :edit } } choices << { name: "[-] Delete Model", value: { action: :delete } } if current_config.models.length > 1 choices << { name: "[X] Close", value: { action: :close } } # Show menu result = modal.show( title: "Model Configuration", choices: choices, on_close: -> { @layout.rerender_all } ) return nil if result.nil? case result[:action] when :switch current_config.switch_model(result[:index]) # Auto-save after switching current_config.save # Return to indicate config changed (need to update client) return { action: :switch } when :add new_model = show_model_edit_form(nil, test_callback: test_callback) if new_model # Determine anthropic_format based on provider # For Anthropic provider, use Anthropic API format anthropic_format = new_model[:provider] == "anthropic" current_config.add_model( model: new_model[:model], api_key: new_model[:api_key], base_url: new_model[:base_url], anthropic_format: anthropic_format ) # Auto-save after adding current_config.save # Set newly added model as default current_config.switch_model(current_config.models.length - 1) current_config.save # Return to exit the menu return { action: :switch } end when :edit current_model = current_config.current_model edited = show_model_edit_form(current_model, test_callback: test_callback) if edited # Update current model in place (keep anthropic_format unchanged) current_model["api_key"] = edited[:api_key] current_model["model"] = edited[:model] current_model["base_url"] = edited[:base_url] # Auto-save after editing current_config.save # Return to indicate config changed (need to update client) return { action: :edit } end when :delete if current_config.models.length <= 1 # Can't delete - show error and continue next end # Delete current model current_config.remove_model(current_config.current_model_index) # Auto-save after deleting current_config.save when :close # Just close the modal return nil end end end |
#show_diff(old_content, new_content, max_lines: 50) ⇒ Object
Show diff between old and new content
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 |
# File 'lib/clacky/ui2/ui_controller.rb', line 753 def show_diff(old_content, new_content, max_lines: 50) require 'diffy' diff = Diffy::Diff.new(old_content, new_content, context: 3) diff_lines = diff.to_s(:color).lines # Store for fullscreen toggle @last_diff_lines = diff_lines # Show diff without line numbers diff_lines.take(max_lines).each do |line| append_output(line.chomp) end if diff_lines.size > max_lines append_output("\n... (#{diff_lines.size - max_lines} more lines hidden. Press Ctrl+O to open full diff in pager)") end rescue LoadError # Fallback if diffy is not available append_output(" Old size: #{old_content.bytesize} bytes") append_output(" New size: #{new_content.bytesize} bytes") @last_diff_lines = nil end |
#show_error(message) ⇒ Object
Show error message
633 634 635 636 |
# File 'lib/clacky/ui2/ui_controller.rb', line 633 def show_error() output = @renderer.render_error() append_output(output) end |
#show_file_edit_preview(path) ⇒ Object
Show file operation preview (Edit tool)
341 342 343 344 345 |
# File 'lib/clacky/ui2/ui_controller.rb', line 341 def show_file_edit_preview(path) theme = ThemeManager.current_theme file_label = theme.format_symbol(:file) append_output("\n#{file_label} #{path || '(unknown)'}") end |
#show_file_error(error_message) ⇒ Object
Show file operation error
349 350 351 352 |
# File 'lib/clacky/ui2/ui_controller.rb', line 349 def show_file_error() theme = ThemeManager.current_theme append_output(" #{theme.format_text("Warning:", :error)} #{}") end |
#show_file_write_preview(path, is_new_file:) ⇒ Object
Show file operation preview (Write tool)
331 332 333 334 335 336 337 |
# File 'lib/clacky/ui2/ui_controller.rb', line 331 def show_file_write_preview(path, is_new_file:) theme = ThemeManager.current_theme file_label = theme.format_symbol(:file) status = is_new_file ? theme.format_text("Creating new file", :success) : theme.format_text("Modifying existing file", :warning) append_output("\n#{file_label} #{path || '(unknown)'}") append_output(status) end |
#show_help ⇒ Object
Show help text
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 |
# File 'lib/clacky/ui2/ui_controller.rb', line 662 def show_help theme = ThemeManager.current_theme # Separator line separator = theme.format_text("─" * 60, :info) lines = [ separator, "", theme.format_text("Commands:", :info), " #{theme.format_text("/clear", :success)} - Clear output and restart session", " #{theme.format_text("/exit", :success)} - Exit application", "", theme.format_text("Input:", :info), " #{theme.format_text("Shift+Enter", :success)} - New line", " #{theme.format_text("Up/Down", :success)} - History navigation", " #{theme.format_text("Ctrl+V", :success)} - Paste image (Ctrl+D to delete, max 3)", " #{theme.format_text("Ctrl+C", :success)} - Clear input (press 2x to exit)", "", theme.format_text("Other:", :info), " Supports Emacs-style shortcuts (Ctrl+A, Ctrl+E, etc.)", "", separator ] lines.each { |line| append_output(line) } end |
#show_idle_status(phase:, message:) ⇒ Object
Show idle compression status (two-phase: start → end). In terminal mode, only the final state is printed.
618 619 620 621 622 |
# File 'lib/clacky/ui2/ui_controller.rb', line 618 def show_idle_status(phase:, message:) return unless phase.to_s == "end" output = @renderer.() append_output(output) end |
#show_info(message, prefix_newline: true) ⇒ Object
Show info message
611 612 613 614 |
# File 'lib/clacky/ui2/ui_controller.rb', line 611 def show_info(, prefix_newline: true) output = @renderer.(, prefix_newline: prefix_newline) append_output(output) end |
#show_progress(message = nil, prefix_newline: true, output_buffer: nil) ⇒ Object
Show progress indicator with dynamic elapsed time
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
# File 'lib/clacky/ui2/ui_controller.rb', line 470 def show_progress( = nil, prefix_newline: true, output_buffer: nil) # Stop any existing progress thread stop_progress_thread # Update status to 'working' (status: 'working') @progress_message = || Clacky::THINKING_VERBS.sample @progress_start_time = Time.now @progress_output_buffer = output_buffer # Flag used by the progress thread to know when to stop gracefully. # Using a flag + join is safe because Thread#kill can interrupt a thread # while it holds @render_mutex, causing a permanent deadlock. @progress_thread_stop = false # Show initial progress (yellow, active) append_output("") if prefix_newline # Initial hint — no stdout yet, so no Ctrl+O tip at this point. # The background thread will add the Ctrl+O tip as soon as any stdout arrives. output = @renderer.render_working("#{@progress_message}… (Ctrl+C to interrupt)") append_output(output) # Start background thread to update elapsed time. # Also dynamically adds "Ctrl+O to view output" hint once @stdout_lines is populated. @progress_thread = Thread.new do until @progress_thread_stop sleep 0.5 next if @progress_thread_stop start = @progress_start_time next unless start elapsed = (Time.now - start).to_i has_output = @stdout_lines && !@stdout_lines.empty? hint = has_output ? "(Ctrl+C to interrupt · Ctrl+O to view output · #{elapsed}s)" : "(Ctrl+C to interrupt · #{elapsed}s)" update_progress_line(@renderer.render_working("#{@progress_message}… #{hint}")) end rescue StandardError # Silently handle thread errors end end |
#show_shell_preview(command) ⇒ Object
Show shell command preview
356 357 358 359 360 |
# File 'lib/clacky/ui2/ui_controller.rb', line 356 def show_shell_preview(command) theme = ThemeManager.current_theme cmd_label = theme.format_symbol(:command) append_output("\n#{cmd_label} #{command}") end |
#show_success(message) ⇒ Object
Show success message
640 641 642 643 |
# File 'lib/clacky/ui2/ui_controller.rb', line 640 def show_success() output = @renderer.render_success() append_output(output) end |
#show_time_machine_menu(history) ⇒ Integer?
Show time machine menu for task undo/redo
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 |
# File 'lib/clacky/ui2/ui_controller.rb', line 1218 public def (history) modal = Components::ModalComponent.new # Build menu choices from history choices = history.map do |task| # Build visual indicator indicator = if task[:status] == :current "→ " # Current task elsif task[:status] == :future "↯ " # Future task (after undo) else " " # Past task end # Add branch indicator indicator += "⎇ " if task[:has_branches] # Truncate summary to fit on screen max_summary_length = 60 summary = task[:summary] if summary.length > max_summary_length summary = summary[0...max_summary_length] + "..." end { name: "#{indicator}Task #{task[:task_id]}: #{summary}", value: task[:task_id] } end # Show modal result = modal.show( title: "Time Machine - Select Task to Navigate", choices: choices, on_close: -> { @layout.rerender_all } ) result # Return selected task_id or nil end |
#show_token_usage(token_data) ⇒ Object
Display token usage statistics
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
# File 'lib/clacky/ui2/ui_controller.rb', line 246 def show_token_usage(token_data) theme = ThemeManager.current_theme pastel = Pastel.new token_info = [] # Delta tokens with color coding (green/yellow/red + dim) delta_tokens = token_data[:delta_tokens] delta_str = delta_tokens.negative? ? "#{delta_tokens}" : "+#{delta_tokens}" color_style = if delta_tokens > 10000 :red elsif delta_tokens > 5000 :yellow else :green end colored_delta = if delta_tokens.negative? pastel.cyan(delta_str) else pastel.decorate(delta_str, color_style, :dim) end token_info << colored_delta # Cache status indicator (using theme) cache_write = token_data[:cache_write] cache_read = token_data[:cache_read] cache_used = cache_read > 0 || cache_write > 0 if cache_used token_info << pastel.dim(theme.symbol(:cached)) end # Input tokens (with cache breakdown if available) prompt_tokens = token_data[:prompt_tokens] if cache_write > 0 || cache_read > 0 input_detail = "#{prompt_tokens} (cache: #{cache_read} read, #{cache_write} write)" token_info << pastel.dim("Input: #{input_detail}") else token_info << pastel.dim("Input: #{prompt_tokens}") end # Output tokens token_info << pastel.dim("Output: #{token_data[:completion_tokens]}") # Total token_info << pastel.dim("Total: #{token_data[:total_tokens]}") # Cost for this iteration with color coding (red/yellow for high cost, dim for normal) # :api => "$0.001234" (exact, from API) # :price => "~$0.001234" (estimated from pricing table) # :default => "N/A" (model not in pricing table, unknown cost) cost_source = token_data[:cost_source] if cost_source == :default token_info << pastel.dim("Cost: N/A") elsif token_data[:cost] cost = token_data[:cost] cost_value = cost_source == :price ? "~$#{cost.round(6)}" : "$#{cost.round(6)}" if cost >= 0.1 # High cost - red warning colored_cost = pastel.decorate(cost_value, :red, :dim) token_info << pastel.dim("Cost: ") + colored_cost elsif cost >= 0.05 # Medium cost - yellow warning colored_cost = pastel.decorate(cost_value, :yellow, :dim) token_info << pastel.dim("Cost: ") + colored_cost else # Low cost - normal gray token_info << pastel.dim("Cost: #{cost_value}") end end # Display through output system (already all dimmed, just add prefix) token_display = pastel.dim(" [Tokens] ") + token_info.join(pastel.dim(' | ')) append_output(token_display) end |
#show_tool_args(formatted_args) ⇒ Object
Show tool call arguments
323 324 325 326 |
# File 'lib/clacky/ui2/ui_controller.rb', line 323 def show_tool_args(formatted_args) theme = ThemeManager.current_theme append_output("\n#{theme.format_text("Args: #{formatted_args}", :thinking)}") end |
#show_tool_call(name, args) ⇒ Object
Show tool call
396 397 398 399 400 401 402 403 404 |
# File 'lib/clacky/ui2/ui_controller.rb', line 396 def show_tool_call(name, args) # Reset stdout buffer on each new tool call so previous command output # doesn't bleed into the next one, and so the buffer is ready before # on_output starts firing (which can happen before show_progress is called). @stdout_lines = nil formatted_call = format_tool_call(name, args) output = @renderer.render_tool_call(tool_name: name, formatted_call: formatted_call) append_output(output) end |
#show_tool_error(error) ⇒ Object
Show tool error
415 416 417 418 419 |
# File 'lib/clacky/ui2/ui_controller.rb', line 415 def show_tool_error(error) error_msg = error.is_a?(Exception) ? error. : error.to_s output = @renderer.render_tool_error(error: error_msg) append_output(output) end |
#show_tool_result(result) ⇒ Object
Show tool result
408 409 410 411 |
# File 'lib/clacky/ui2/ui_controller.rb', line 408 def show_tool_result(result) output = @renderer.render_tool_result(result: result) append_output(output) end |
#show_tool_stdout(lines) ⇒ Object
Receive a chunk of shell stdout from the on_output callback. Lines are buffered into @stdout_lines so that Ctrl+O can open a fullscreen live view, matching the original output_buffer interaction.
425 426 427 428 429 |
# File 'lib/clacky/ui2/ui_controller.rb', line 425 def show_tool_stdout(lines) return if lines.nil? || lines.empty? @stdout_lines ||= [] @stdout_lines.concat(lines.map(&:chomp)) end |
#show_warning(message) ⇒ Object
Show warning message
626 627 628 629 |
# File 'lib/clacky/ui2/ui_controller.rb', line 626 def show_warning() output = @renderer.render_warning() append_output(output) end |
#start ⇒ Object
Start the UI controller
58 59 60 61 |
# File 'lib/clacky/ui2/ui_controller.rb', line 58 def start start_input_loop end |
#start_input_loop ⇒ Object
Start input loop (separate from initialization)
88 89 90 91 |
# File 'lib/clacky/ui2/ui_controller.rb', line 88 def start_input_loop @running = true input_loop end |
#stop ⇒ Object
Stop the UI controller
139 140 141 142 |
# File 'lib/clacky/ui2/ui_controller.rb', line 139 def stop @running = false @layout.cleanup_screen end |
#stop_fullscreen_refresh_thread ⇒ Object
Stop the fullscreen refresh thread gracefully via flag + join.
581 582 583 584 585 586 587 588 589 |
# File 'lib/clacky/ui2/ui_controller.rb', line 581 def stop_fullscreen_refresh_thread @fullscreen_refresh_stop = true if @fullscreen_refresh_thread&.alive? joined = @fullscreen_refresh_thread.join(1.0) @fullscreen_refresh_thread.kill unless joined end @fullscreen_refresh_thread = nil @fullscreen_refresh_stop = false end |
#stop_progress_thread ⇒ Object
Stop the progress update thread gracefully. We signal the thread via a stop flag and then join it, avoiding Thread#kill which can interrupt a thread mid-critical-section (e.g. while holding @render_mutex) and leave the mutex permanently locked.
595 596 597 598 599 600 601 602 603 604 605 606 |
# File 'lib/clacky/ui2/ui_controller.rb', line 595 def stop_progress_thread @progress_start_time = nil @progress_output_buffer = nil @progress_thread_stop = true if @progress_thread&.alive? # Join with a short timeout; fall back to kill only as a last resort joined = @progress_thread.join(1.0) @progress_thread.kill unless joined end @progress_thread = nil @progress_thread_stop = false end |
#toggle_mode ⇒ Object
Toggle permission mode between confirm_safes and auto_approve
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/clacky/ui2/ui_controller.rb', line 119 def toggle_mode current_mode = @config[:mode] new_mode = case current_mode.to_s when /confirm_safes/ "auto_approve" when /auto_approve/ "confirm_safes" else "auto_approve" # Default to auto_approve if unknown mode end @config[:mode] = new_mode # Notify CLI to update agent_config @mode_toggle_callback&.call(new_mode) end |
#update_progress_line(content) ⇒ Object
Update the last line in output area (for progress indicator)
222 223 224 |
# File 'lib/clacky/ui2/ui_controller.rb', line 222 def update_progress_line(content) @layout.update_last_line(content) end |
#update_sessionbar(tasks: nil, cost: nil, status: nil) ⇒ Object
Update session bar with current stats
104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/clacky/ui2/ui_controller.rb', line 104 def (tasks: nil, cost: nil, status: nil) @tasks_count = tasks if tasks @total_cost = cost if cost @input_area.( working_dir: @config[:working_dir], mode: @config[:mode], model: @config[:model], tasks: @tasks_count, cost: @total_cost, status: status ) @layout.render_input end |
#update_todos(todos) ⇒ Object
Update todos display
233 234 235 |
# File 'lib/clacky/ui2/ui_controller.rb', line 233 def update_todos(todos) @layout.update_todos(todos) end |