Class: Clacky::UI2::Components::InputArea

Inherits:
Object
  • Object
show all
Includes:
LineEditor
Defined in:
lib/clacky/ui2/components/input_area.rb

Overview

InputArea manages the fixed input area at the bottom of the screen Enhanced with multi-line support, image paste, and more

Constant Summary collapse

USER_TIPS =

User tips pool - can be extended with more tips over time

[
  "Shift+Tab to toggle permission mode (confirm_safes ⇄ auto_approve)",
  "Ctrl+C to interrupt AI execution or clear input",
  "Shift+Enter to create multi-line input",
  "Ctrl+V to paste images (supports up to 3 images)",
  "Ctrl+D to delete pasted images",
  "Use /clear to restart session, /help for commands"
].freeze

Constants included from LineEditor

LineEditor::MAX_CONTENT_WIDTH_RATIO

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from LineEditor

#calculate_display_width, #clear_line_content, #cursor_column, #cursor_position_with_wrap, #initialize_line_editor, #set_line

Constructor Details

#initialize(row: 0) ⇒ InputArea

Returns a new instance of InputArea.



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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/clacky/ui2/components/input_area.rb', line 31

def initialize(row: 0)
  @row = row
  @lines = [""]
  @line_index = 0
  @cursor_position = 0
  @history = []
  @history_index = -1
  @pastel = Pastel.new
  @width = TTY::Screen.width

  @files = []
  @paste_counter = 0
  @paste_placeholders = {}
  @last_ctrl_c_time = nil
  @tips_message = nil
  @tips_type = :info
  @tips_timer = nil
  @last_render_row = nil

  # User tip (usage suggestion) - separate from system tips
  @user_tip = nil
  @user_tip_timer = nil
  @user_tip_count = 0

  # Paused state - when InlineInput is active
  @paused = false

  # Session bar info
  @sessionbar_info = {
    working_dir: nil,
    mode: nil,
    model: nil,
    tasks: 0,
    cost: 0.0,
    status: 'idle'  # Workspace status: 'idle' or 'working'
  }

  # Animation state for working status
  @animation_frame = 0
  @last_animation_update = Time.now
  @working_frames = ["", "", ""]

  # Command suggestions dropdown
  @command_suggestions = CommandSuggestions.new
  @skill_loader = nil  # Will be set via set_skill_loader method
end

Instance Attribute Details

#cursor_positionObject (readonly)

Returns the value of attribute cursor_position.



29
30
31
# File 'lib/clacky/ui2/components/input_area.rb', line 29

def cursor_position
  @cursor_position
end

#filesObject (readonly)

Returns the value of attribute files.



29
30
31
# File 'lib/clacky/ui2/components/input_area.rb', line 29

def files
  @files
end

#line_indexObject (readonly)

Returns the value of attribute line_index.



29
30
31
# File 'lib/clacky/ui2/components/input_area.rb', line 29

def line_index
  @line_index
end

#rowObject

Returns the value of attribute row.



28
29
30
# File 'lib/clacky/ui2/components/input_area.rb', line 28

def row
  @row
end

#tips_messageObject (readonly)

Returns the value of attribute tips_message.



29
30
31
# File 'lib/clacky/ui2/components/input_area.rb', line 29

def tips_message
  @tips_message
end

#tips_typeObject (readonly)

Returns the value of attribute tips_type.



29
30
31
# File 'lib/clacky/ui2/components/input_area.rb', line 29

def tips_type
  @tips_type
end

Instance Method Details

#add_to_history(entry) ⇒ Object



978
979
980
981
# File 'lib/clacky/ui2/components/input_area.rb', line 978

def add_to_history(entry)
  @history << entry
  @history = @history.last(100) if @history.size > 100
end

#backspaceObject



545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/clacky/ui2/components/input_area.rb', line 545

def backspace
  if @cursor_position > 0
    chars = current_line.chars
    chars.delete_at(@cursor_position - 1)
    @lines[@line_index] = chars.join
    @cursor_position -= 1
  elsif @line_index > 0
    prev_line = @lines[@line_index - 1]
    current = @lines[@line_index]
    @lines.delete_at(@line_index)
    @line_index -= 1
    @cursor_position = prev_line.chars.length
    @lines[@line_index] = prev_line + current
  end
end

#char_display_width(char) ⇒ Integer

Calculate display width of a single character

Parameters:

  • char (String)

    Single character

Returns:

  • (Integer)

    Display width (1 or 2)



745
746
747
# File 'lib/clacky/ui2/components/input_area.rb', line 745

def char_display_width(char)
  super(char)
end

#clearObject



584
585
586
587
588
589
590
591
592
593
594
# File 'lib/clacky/ui2/components/input_area.rb', line 584

def clear
  @lines = [""]
  @line_index = 0
  @cursor_position = 0
  @history_index = -1
  @files = []
  @paste_counter = 0
  @paste_placeholders = {}
  clear_tips
  @command_suggestions.hide if @command_suggestions
end

#clear_lineObject



1308
1309
1310
# File 'lib/clacky/ui2/components/input_area.rb', line 1308

def clear_line
  print "\e[2K"
end

#clear_tipsObject



418
419
420
421
422
423
424
# File 'lib/clacky/ui2/components/input_area.rb', line 418

def clear_tips
  # Cancel timer if any
  if @tips_timer&.alive?
    @tips_timer.kill
  end
  @tips_message = nil
end

#clear_user_tipObject

Clear user tip and stop rotation



465
466
467
468
469
# File 'lib/clacky/ui2/components/input_area.rb', line 465

def clear_user_tip
  stop_user_tip_timer
  @user_tip = nil
  @user_tip_count = 0
end

#current_contentObject



493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/clacky/ui2/components/input_area.rb', line 493

def current_content
  text = expand_placeholders(@lines.join("\n"))
  
  # If both text and images are empty, return empty string
  return "" if text.empty? && @files.empty?

  # Format user input with color and spacing from theme
  symbol = theme.format_symbol(:user)
  content = theme.format_text(text, :user)

  result = "\n#{symbol} #{content}\n"
  
  # Append file information if present
  if @files.any?
    @files.each_with_index do |f, idx|
      filename = f[:name] || f["name"] || "file"
      result += @pastel.dim("    [File #{idx + 1}] #{filename}") + "\n"
    end
  end
  
  result
end

#current_lineObject



1039
1040
1041
# File 'lib/clacky/ui2/components/input_area.rb', line 1039

def current_line
  @lines[@line_index] || ""
end

#current_valueObject



516
517
518
# File 'lib/clacky/ui2/components/input_area.rb', line 516

def current_value
  expand_placeholders(@lines.join("\n"))
end

#cursor_downObject



934
935
936
937
938
939
# File 'lib/clacky/ui2/components/input_area.rb', line 934

def cursor_down
  return false if @line_index >= @lines.size - 1
  @line_index += 1
  @cursor_position = [@cursor_position, current_line.chars.length].min
  true
end

#cursor_endObject



580
581
582
# File 'lib/clacky/ui2/components/input_area.rb', line 580

def cursor_end
  @cursor_position = current_line.chars.length
end

#cursor_homeObject



576
577
578
# File 'lib/clacky/ui2/components/input_area.rb', line 576

def cursor_home
  @cursor_position = 0
end

#cursor_leftObject



568
569
570
# File 'lib/clacky/ui2/components/input_area.rb', line 568

def cursor_left
  @cursor_position = [@cursor_position - 1, 0].max
end

#cursor_rightObject



572
573
574
# File 'lib/clacky/ui2/components/input_area.rb', line 572

def cursor_right
  @cursor_position = [@cursor_position + 1, current_line.chars.length].min
end

#cursor_upObject



927
928
929
930
931
932
# File 'lib/clacky/ui2/components/input_area.rb', line 927

def cursor_up
  return false if @line_index == 0
  @line_index -= 1
  @cursor_position = [@cursor_position, current_line.chars.length].min
  true
end

#delete_charObject



561
562
563
564
565
566
# File 'lib/clacky/ui2/components/input_area.rb', line 561

def delete_char
  chars = current_line.chars
  return if @cursor_position >= chars.length
  chars.delete_at(@cursor_position)
  @lines[@line_index] = chars.join
end

#empty?Boolean

Returns:

  • (Boolean)


520
521
522
# File 'lib/clacky/ui2/components/input_area.rb', line 520

def empty?
  @lines.all?(&:empty?) && @files.empty?
end

#expand_placeholders(text) ⇒ Object



1043
1044
1045
# File 'lib/clacky/ui2/components/input_area.rb', line 1043

def expand_placeholders(text)
  super(text, @paste_placeholders)
end

#flushObject



1312
1313
1314
# File 'lib/clacky/ui2/components/input_area.rb', line 1312

def flush
  $stdout.flush
end

#format_filesize(size) ⇒ Object



1280
1281
1282
1283
1284
1285
1286
1287
1288
# File 'lib/clacky/ui2/components/input_area.rb', line 1280

def format_filesize(size)
  if size < 1024
    "#{size}B"
  elsif size < 1024 * 1024
    "#{(size / 1024.0).round(1)}KB"
  else
    "#{(size / 1024.0 / 1024.0).round(1)}MB"
  end
end

#format_tips(message, type) ⇒ Object



1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
# File 'lib/clacky/ui2/components/input_area.rb', line 1262

def format_tips(message, type)
  # Limit message length to prevent line wrapping
  # Reserve space for prefix like "[Warn] " (about 8 chars) and some margin
  max_length = @width - 10
  if message.length > max_length
    message = message[0...(max_length - 3)] + "..."
  end
  
  case type
  when :warning
    @pastel.dim("[") + @pastel.yellow("Warn") + @pastel.dim("] ") + @pastel.yellow(message)
  when :error
    @pastel.dim("[") + @pastel.red("Error") + @pastel.dim("] ") + @pastel.red(message)
  else
    @pastel.dim("[") + @pastel.cyan("Info") + @pastel.dim("] ") + @pastel.white(message)
  end
end

#format_user_tip(tip) ⇒ String

Format user tip (usage suggestion) with lightbulb icon

Parameters:

  • tip (String)

    Tip message

Returns:

  • (String)

    Formatted tip with styling



1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
# File 'lib/clacky/ui2/components/input_area.rb', line 1293

def format_user_tip(tip)
  # Limit message length to prevent line wrapping
  max_length = @width - 5  # Reserve space for icon and margins
  if tip.length > max_length
    tip = tip[0...(max_length - 3)] + "..."
  end
  
  # Use lightbulb icon and dim cyan color for subtle appearance
  @pastel.dim(@pastel.cyan("💡 #{tip}"))
end

#get_status_indicator(status, color) ⇒ Object



1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
# File 'lib/clacky/ui2/components/input_area.rb', line 1247

def get_status_indicator(status, color)
  case status.to_s.downcase
  when 'working'
    # Update animation frame if enough time has passed
    now = Time.now
    if now - @last_animation_update >= 0.3
      @animation_frame = (@animation_frame + 1) % @working_frames.length
      @last_animation_update = now
    end
    @pastel.public_send(color, @working_frames[@animation_frame])
  else
    @pastel.public_send(color, "")  # Idle indicator with same color as text
  end
end

#handle_ctrl_cObject



860
861
862
# File 'lib/clacky/ui2/components/input_area.rb', line 860

def handle_ctrl_c
  { action: :interrupt }
end

#handle_ctrl_dObject



864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
# File 'lib/clacky/ui2/components/input_area.rb', line 864

def handle_ctrl_d
  if has_images?
    if @files.size == 1
      @files.clear
    else
      @files.shift
    end
    clear_tips
    { action: nil }
  elsif empty?
    { action: :exit }
  else
    { action: nil }
  end
end

#handle_down_arrowObject



848
849
850
851
852
853
854
855
856
857
858
# File 'lib/clacky/ui2/components/input_area.rb', line 848

def handle_down_arrow
  if multiline?
    unless cursor_down
      history_next
    end
  else
    # Navigate history when single line (empty or not)
    history_next
  end
  { action: nil }
end

#handle_enterObject



788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
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/components/input_area.rb', line 788

def handle_enter
  text = current_value.strip

  # Prepare display content and data BEFORE clearing
  content_to_display = current_content
  result_text = current_value
  result_files = @files.dup

  # Handle commands (with or without slash)
  if text.start_with?('/')
    # Check if it's a command (single slash followed by English letters only)
    # Paths like /xxx/xxxx should not be treated as commands
    if text =~ /^\/([a-zA-Z-]+)$/
      case text
      when '/clear'
        add_to_history(result_text) unless result_text.empty?
        clear
        return { action: :clear_output, data: { text: result_text, files: result_files, display: content_to_display } }
      when '/help'
        add_to_history(result_text) unless result_text.empty?
        clear
        return { action: :help, data: { text: result_text, files: result_files, display: content_to_display } }
      when '/exit', '/quit'
        return { action: :exit }
      else
        # Let other commands (like skills) pass through to agent
        # Fall through to submit
      end
    end
    # If it's not a command pattern (e.g., /xxx/xxxx), treat as normal input
  elsif text == '?'
    add_to_history(result_text) unless result_text.empty?
    clear
    return { action: :help, data: { text: result_text, files: result_files, display: content_to_display } }
  elsif text == 'exit' || text == 'quit'
    return { action: :exit }
  end

  if text.empty? && @files.empty?
    return { action: nil }
  end

  add_to_history(result_text) unless result_text.empty?
  clear

  { action: :submit, data: { text: result_text, files: result_files, display: content_to_display } }
end

#handle_key(key) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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
# File 'lib/clacky/ui2/components/input_area.rb', line 159

def handle_key(key)
  # Ignore input when paused (InlineInput is active)
  return { action: nil } if @paused

  old_height = required_height

  # Handle command suggestions navigation first if visible
  if @command_suggestions.visible
    case key
    when :up_arrow
      @command_suggestions.select_previous
      return { action: nil }
    when :down_arrow
      @command_suggestions.select_next
      return { action: nil }
    when :enter
      # Accept selected command and submit immediately
      if @command_suggestions.has_suggestions?
        selected = @command_suggestions.selected_command_text
        if selected
          # Replace current input with selected command
          @lines = [selected]
          @line_index = 0
          @cursor_position = selected.length
          @command_suggestions.hide
          # Submit the command immediately
          return handle_enter
        end
      end
      # Fall through to normal enter handling if no suggestion
    when :escape
      @command_suggestions.hide
      return { action: nil }
    when :tab
      # Tab accepts the currently highlighted suggestion
      if @command_suggestions.has_suggestions?
        selected = @command_suggestions.selected_command_text
        if selected
          hint = @command_suggestions.selected_argument_hint
          completed = "#{selected} "
          @lines = [completed]
          @line_index = 0
          @cursor_position = completed.length
          @command_suggestions.hide
          # Show argument hint as a tip if available
          set_tips("Usage: #{selected} #{hint}", type: :info) if hint && !hint.empty?
          return { action: nil }
        end
      end
    end
  end

  # Tab with no visible suggestions: trigger slash-command completion
  if key == :tab
    trigger_tab_completion
    return { action: nil }
  end

  result = case key
  when Hash
    if key[:type] == :rapid_input
      insert_text(key[:text])
      clear_tips
      update_command_suggestions
    end
    { action: nil }
  when :enter then handle_enter
  when :newline then newline; { action: nil }
  when :backspace 
    backspace
    update_command_suggestions
    { action: nil }
  when :delete 
    delete_char
    update_command_suggestions
    { action: nil }
  when :left_arrow, :ctrl_b then cursor_left; { action: nil }
  when :right_arrow, :ctrl_f then cursor_right; { action: nil }
  when :up_arrow then handle_up_arrow
  when :down_arrow then handle_down_arrow
  when :home, :ctrl_a then cursor_home; { action: nil }
  when :end, :ctrl_e then cursor_end; { action: nil }
  when :ctrl_k then kill_to_end; { action: nil }
  when :ctrl_u then kill_to_start; { action: nil }
  when :ctrl_w then kill_word; { action: nil }
  when :ctrl_c then handle_ctrl_c
  when :ctrl_d then handle_ctrl_d
  when :ctrl_v then handle_paste
  when :ctrl_o then { action: :toggle_expand }
  when :shift_tab then { action: :toggle_mode }
  when :escape 
    if @command_suggestions.visible
      @command_suggestions.hide
      { action: nil }
    else
      # Trigger time machine when ESC is pressed and suggestions not visible
      { action: :time_machine }
    end
  else
    if key.is_a?(String) && key.length >= 1 && key.ord >= 32
      insert_char(key)
      update_command_suggestions
    end
    { action: nil }
  end

  new_height = required_height
  if new_height != old_height
    result[:height_changed] = true
    result[:new_height] = new_height
  end

  result
end

#handle_pasteObject



880
881
882
883
884
885
886
887
888
889
890
891
892
893
# File 'lib/clacky/ui2/components/input_area.rb', line 880

def handle_paste
  pasted = paste_from_clipboard
  if pasted[:type] == :image
    path = pasted[:path]
    mime_type = pasted[:mime_type] || "image/png"
    size = File.exist?(path) ? File.size(path) : 0
    @files << { name: File.basename(path), mime_type: mime_type, path: path, size: size }
    clear_tips
  else
    insert_text(pasted[:text])
    clear_tips
  end
  { action: nil }
end

#handle_up_arrowObject



836
837
838
839
840
841
842
843
844
845
846
# File 'lib/clacky/ui2/components/input_area.rb', line 836

def handle_up_arrow
  if multiline?
    unless cursor_up
      history_prev
    end
  else
    # Navigate history when single line (empty or not)
    history_prev
  end
  { action: nil }
end

#has_images?Boolean

Returns:

  • (Boolean)


528
529
530
# File 'lib/clacky/ui2/components/input_area.rb', line 528

def has_images?
  @files.any?
end

#history_nextObject



614
615
616
617
618
619
620
621
622
623
624
625
# File 'lib/clacky/ui2/components/input_area.rb', line 614

def history_next
  return if @history_index == -1
  @history_index += 1
  if @history_index >= @history.size
    @history_index = -1
    @lines = [""]
    @line_index = 0
    @cursor_position = 0
  else
    load_history_entry
  end
end

#history_prevObject



604
605
606
607
608
609
610
611
612
# File 'lib/clacky/ui2/components/input_area.rb', line 604

def history_prev
  return if @history.empty?
  if @history_index == -1
    @history_index = @history.size - 1
  else
    @history_index = [@history_index - 1, 0].max
  end
  load_history_entry
end

#input_bufferObject



155
156
157
# File 'lib/clacky/ui2/components/input_area.rb', line 155

def input_buffer
  @lines.join("\n")
end

#insert_char(char) ⇒ Object

— Public editing methods —



538
539
540
541
542
543
# File 'lib/clacky/ui2/components/input_area.rb', line 538

def insert_char(char)
  chars = current_line.chars
  chars.insert(@cursor_position, char)
  @lines[@line_index] = chars.join
  @cursor_position += 1
end

#insert_text(text) ⇒ Object



895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
# File 'lib/clacky/ui2/components/input_area.rb', line 895

def insert_text(text)
  return if text.nil? || text.empty?

  text_lines = text.split(/\r\n|\r|\n/)

  if text_lines.size > 1
    @paste_counter += 1
    placeholder = "[##{@paste_counter} Paste Text]"
    @paste_placeholders[placeholder] = text

    chars = current_line.chars
    chars.insert(@cursor_position, *placeholder.chars)
    @lines[@line_index] = chars.join
    @cursor_position += placeholder.length
  else
    chars = current_line.chars
    text.chars.each_with_index do |c, i|
      chars.insert(@cursor_position + i, c)
    end
    @lines[@line_index] = chars.join
    @cursor_position += text.length
  end
end

#kill_to_endObject



941
942
943
944
# File 'lib/clacky/ui2/components/input_area.rb', line 941

def kill_to_end
  chars = current_line.chars
  @lines[@line_index] = chars[0...@cursor_position].join
end

#kill_to_startObject



946
947
948
949
950
# File 'lib/clacky/ui2/components/input_area.rb', line 946

def kill_to_start
  chars = current_line.chars
  @lines[@line_index] = chars[@cursor_position..-1]&.join || ""
  @cursor_position = 0
end

#kill_wordObject



952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
# File 'lib/clacky/ui2/components/input_area.rb', line 952

def kill_word
  chars = current_line.chars
  pos = @cursor_position - 1

  while pos >= 0 && chars[pos] =~ /\s/
    pos -= 1
  end
  while pos >= 0 && chars[pos] =~ /\S/
    pos -= 1
  end

  delete_start = pos + 1
  chars.slice!(delete_start...@cursor_position)
  @lines[@line_index] = chars.join
  @cursor_position = delete_start
end

#load_history_entryObject



969
970
971
972
973
974
975
976
# File 'lib/clacky/ui2/components/input_area.rb', line 969

def load_history_entry
  return unless @history_index >= 0 && @history_index < @history.size
  entry = @history[@history_index]
  @lines = entry.split("\n")
  @lines = [""] if @lines.empty?
  @line_index = @lines.size - 1
  @cursor_position = current_line.chars.length
end

#mode_color_for(mode) ⇒ Object



1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
# File 'lib/clacky/ui2/components/input_area.rb', line 1225

def mode_color_for(mode)
  case mode.to_s
  when /auto_approve/
    :magenta
  when /confirm_safes/
    :cyan
  else
    :white
  end
end

#move_cursor(row, col) ⇒ Object



1304
1305
1306
# File 'lib/clacky/ui2/components/input_area.rb', line 1304

def move_cursor(row, col)
  print "\e[#{row + 1};#{col + 1}H"
end

#multiline?Boolean

Returns:

  • (Boolean)


524
525
526
# File 'lib/clacky/ui2/components/input_area.rb', line 524

def multiline?
  @lines.size > 1
end

#newlineObject



919
920
921
922
923
924
925
# File 'lib/clacky/ui2/components/input_area.rb', line 919

def newline
  chars = current_line.chars
  @lines[@line_index] = chars[0...@cursor_position].join
  @lines.insert(@line_index + 1, chars[@cursor_position..-1]&.join || "")
  @line_index += 1
  @cursor_position = 0
end

#paste_from_clipboardObject



983
984
985
986
987
988
989
990
991
992
# File 'lib/clacky/ui2/components/input_area.rb', line 983

def paste_from_clipboard
  case RbConfig::CONFIG["host_os"]
  when /darwin/i
    paste_from_clipboard_macos
  when /linux/i
    paste_from_clipboard_linux
  else
    { type: :text, text: "" }
  end
end

#paste_from_clipboard_linuxObject



1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/clacky/ui2/components/input_area.rb', line 1023

def paste_from_clipboard_linux
  if system("which xclip >/dev/null 2>&1")
    text = `xclip -selection clipboard -o 2>/dev/null`.to_s
    text = Clacky::Utils::Encoding.to_utf8(text)
    { type: :text, text: text }
  elsif system("which xsel >/dev/null 2>&1")
    text = `xsel --clipboard --output 2>/dev/null`.to_s
    text = Clacky::Utils::Encoding.to_utf8(text)
    { type: :text, text: text }
  else
    { type: :text, text: "" }
  end
rescue => e
  { type: :text, text: "" }
end

#paste_from_clipboard_macosObject



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
# File 'lib/clacky/ui2/components/input_area.rb', line 994

def paste_from_clipboard_macos
  has_image = system("osascript -e 'try' -e 'the clipboard as «class PNGf»' -e 'on error' -e 'return false' -e 'end try' >/dev/null 2>&1")

  if has_image
    temp_dir = Dir.tmpdir
    temp_filename = "clipboard-#{Time.now.to_i}-#{rand(10000)}.png"
    temp_path = File.join(temp_dir, temp_filename)

    script = <<~APPLESCRIPT
      set png_data to the clipboard as «class PNGf»
      set the_file to open for access POSIX file "#{temp_path}" with write permission
      write png_data to the_file
      close access the_file
    APPLESCRIPT

    success = system("osascript", "-e", script, out: File::NULL, err: File::NULL)

    if success && File.exist?(temp_path) && File.size(temp_path) > 0
      return { type: :image, path: temp_path }
    end
  end

  text = `pbpaste 2>/dev/null`.to_s
  text = Clacky::Utils::Encoding.to_utf8(text)
  { type: :text, text: text }
rescue => e
  { type: :text, text: "" }
end

#pauseObject

Pause input area (when InlineInput is active)



479
480
481
# File 'lib/clacky/ui2/components/input_area.rb', line 479

def pause
  @paused = true
end

#paused?Boolean

Check if paused

Returns:

  • (Boolean)


489
490
491
# File 'lib/clacky/ui2/components/input_area.rb', line 489

def paused?
  @paused
end

#position_cursor(start_row) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/clacky/ui2/components/input_area.rb', line 337

def position_cursor(start_row)
  # Calculate which wrapped line the cursor is on
  cursor_row = start_row + 2 + @files.size  # session_bar + separator + images
  # Use effective content width (respecting MAX_CONTENT_WIDTH_RATIO)
  content_width = effective_content_width(@width)
  
  # Add rows for lines before current line
  @lines[0...@line_index].each_with_index do |line, idx|
    prefix = if idx == 0
      prompt
    else
      " " * prompt.length
    end
    prefix_width = calculate_display_width(strip_ansi_codes(prefix))
    available_width = [content_width - prefix_width, 20].max
    wrapped_segments = wrap_line(line, available_width)
    cursor_row += wrapped_segments.size
  end
  
  # Find which wrapped segment of current line contains cursor
  current = current_line
  prefix = if @line_index == 0
    prompt
  else
    " " * prompt.length
  end
  prefix_width = calculate_display_width(strip_ansi_codes(prefix))
  available_width = [content_width - prefix_width, 20].max
  wrapped_segments = wrap_line(current, available_width)
  
  # Find cursor segment and position within segment
  cursor_segment_idx = 0
  cursor_pos_in_segment = @cursor_position
  
  wrapped_segments.each_with_index do |segment, idx|
    if @cursor_position >= segment[:start] && @cursor_position < segment[:end]
      cursor_segment_idx = idx
      cursor_pos_in_segment = @cursor_position - segment[:start]
      break
    elsif @cursor_position >= segment[:end] && idx == wrapped_segments.size - 1
      # Cursor at very end
      cursor_segment_idx = idx
      cursor_pos_in_segment = segment[:end] - segment[:start]
      break
    end
  end
  
  cursor_row += cursor_segment_idx
  
  # Calculate display width of text before cursor in this segment
  chars = current.chars
  segment_start = wrapped_segments[cursor_segment_idx][:start]
  text_in_segment_before_cursor = chars[segment_start...(segment_start + cursor_pos_in_segment)].join
  display_width = calculate_display_width(text_in_segment_before_cursor)
  
  cursor_col = prefix_width + display_width
  move_cursor(cursor_row, cursor_col)
end

Print content and pad with spaces to clear any remaining characters from previous render This avoids flickering from clear_line while ensuring old content is erased



758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/clacky/ui2/components/input_area.rb', line 758

def print_with_padding(content)
  # Calculate visible width (strip ANSI codes for width calculation)
  visible_content = content.gsub(/\e\[[0-9;]*m/, '')
  visible_width = calculate_display_width(visible_content)
  
  # IMPORTANT: If content exceeds screen width, truncate to prevent terminal auto-wrap
  if visible_width > @width
    # Content too long - truncate to fit (loses ANSI colors but prevents wrapping)
    truncate_at = 0
    current_width = 0
    visible_content.each_char.with_index do |char, idx|
      char_width = char_display_width(char)
      break if current_width + char_width + 3 > @width  # Reserve 3 for "..."
      current_width += char_width
      truncate_at = idx + 1
    end
    print visible_content[0...truncate_at]
    print "..."
    # Pad remaining
    remaining = @width - current_width - 3
    print " " * remaining if remaining > 0
  else
    # Content fits - print normally
    print content
    # Pad with spaces if needed to clear old content
    remaining = @width - visible_width
    print " " * remaining if remaining > 0
  end
end

#promptObject

Get prompt symbol from theme



84
85
86
# File 'lib/clacky/ui2/components/input_area.rb', line 84

def prompt
  "#{theme.symbol(:user)} "
end

#render(start_row:, width: nil) ⇒ Object



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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/clacky/ui2/components/input_area.rb', line 274

def render(start_row:, width: nil)
  @width = width || TTY::Screen.width
  @last_render_row = start_row  # Save for tips auto-clear

  # When paused, don't render anything (InlineInput is active)
  return if @paused

  current_row = start_row

  # Session bar at top
  render_sessionbar(current_row)
  current_row += 1

  # Separator after session bar
  render_separator(current_row)
  current_row += 1

  # Files (images / documents)
  @files.each_with_index do |f, idx|
    move_cursor(current_row, 0)
    filename = f[:name] || f["name"] || "file"
    size     = f[:size] || f["size"]
    size_str = size ? " #{format_filesize(size)}" : ""
    content = @pastel.dim("[File #{idx + 1}] #{filename}#{size_str} (Ctrl+D to delete)")
    print_with_padding(content)
    current_row += 1
  end

  # Input lines with auto-wrap support
  current_row = render_input_lines(current_row)

  # Bottom separator
  render_separator(current_row)
  current_row += 1

  # Command suggestions (rendered above tips)
  if @command_suggestions && @command_suggestions.visible
    # Render suggestions at current row
    print @command_suggestions.render(row: current_row, col: 0, width: [@width - 4, 60].min)
    current_row += @command_suggestions.required_height
  end

  # Tips bar (if any)
  if @tips_message
    move_cursor(current_row, 0)
    content = format_tips(@tips_message, @tips_type)
    print_with_padding(content)
    current_row += 1
  end

  # User tip (if any)
  if @user_tip
    move_cursor(current_row, 0)
    content = format_user_tip(@user_tip)
    print_with_padding(content)
    current_row += 1
  end

  # Position cursor at current edit position
  position_cursor(start_row)
  flush
end

#render_input_lines(start_row) ⇒ Integer

Render all input lines with auto-wrap support

Parameters:

  • start_row (Integer)

    Starting row position

Returns:

  • (Integer)

    Next available row after rendering all lines



667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# File 'lib/clacky/ui2/components/input_area.rb', line 667

def render_input_lines(start_row)
  current_row = start_row
  # Use effective content width (respecting MAX_CONTENT_WIDTH_RATIO)
  content_width = effective_content_width(@width)
  
  @lines.each_with_index do |line, line_idx|
    prefix = calculate_line_prefix(line_idx)
    prefix_width = calculate_display_width(strip_ansi_codes(prefix))
    available_width = content_width - prefix_width
    wrapped_segments = wrap_line(line, available_width)

    wrapped_segments.each_with_index do |segment_info, wrap_idx|
      content = render_line_segment(line, line_idx, segment_info, wrap_idx, prefix, prefix_width)
      move_cursor(current_row, 0)
      print_with_padding(content)
      current_row += 1
    end
  end
  
  current_row
end

#render_line_segment_with_cursor(line, segment_start, segment_end) ⇒ String

Render a segment of a line with cursor if cursor is in this segment Applies theme colors to the text

Parameters:

  • line (String)

    Full line text

  • segment_start (Integer)

    Start position of segment in line (char index)

  • segment_end (Integer)

    End position of segment in line (char index)

Returns:

  • (String)

    Rendered segment with cursor and theme colors applied



1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
# File 'lib/clacky/ui2/components/input_area.rb', line 1062

def render_line_segment_with_cursor(line, segment_start, segment_end)
  chars = line.chars
  segment_chars = chars[segment_start...segment_end]

  # Check if cursor is in this segment
  if @cursor_position >= segment_start && @cursor_position < segment_end
    # Cursor is in this segment
    cursor_pos_in_segment = @cursor_position - segment_start
    before_cursor = segment_chars[0...cursor_pos_in_segment].join
    cursor_char = segment_chars[cursor_pos_in_segment] || " "
    after_cursor = segment_chars[(cursor_pos_in_segment + 1)..-1]&.join || ""

    # Apply theme color to text parts, keep cursor highlight as is
    "#{theme.format_text(before_cursor, :user)}#{@pastel.on_white(@pastel.black(cursor_char))}#{theme.format_text(after_cursor, :user)}"
  elsif @cursor_position == segment_end && segment_end == line.length
    # Cursor is at the very end of the line, show it in last segment
    segment_text = segment_chars.join
    "#{theme.format_text(segment_text, :user)}#{@pastel.on_white(@pastel.black(' '))}"
  else
    # Cursor is not in this segment, apply theme color
    theme.format_text(segment_chars.join, :user)
  end
end

#render_line_with_cursor(line) ⇒ Object



1047
1048
1049
1050
1051
1052
1053
1054
# File 'lib/clacky/ui2/components/input_area.rb', line 1047

def render_line_with_cursor(line)
  chars = line.chars
  before_cursor = chars[0...@cursor_position].join
  cursor_char = chars[@cursor_position] || " "
  after_cursor = chars[(@cursor_position + 1)..-1]&.join || ""

  "#{@pastel.white(before_cursor)}#{@pastel.on_white(@pastel.black(cursor_char))}#{@pastel.white(after_cursor)}"
end

#render_separator(row) ⇒ Object

Render a separator line (ensures it doesn’t exceed screen width)

Parameters:

  • row (Integer)

    Row position to render



1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
# File 'lib/clacky/ui2/components/input_area.rb', line 1088

def render_separator(row)
  move_cursor(row, 0)
  # Ensure separator doesn't exceed screen width to prevent wrapping
  separator_width = [@width, 1].max
  content = @pastel.dim("" * separator_width)
  print content
  # Clear any remaining space
  remaining = @width - separator_width
  print " " * remaining if remaining > 0
end

#render_sessionbar(row) ⇒ Integer

Render session bar with wrapping support

Parameters:

  • row (Integer)

    Starting row position

Returns:

  • (Integer)

    Number of rows actually used



1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'lib/clacky/ui2/components/input_area.rb', line 1102

def render_sessionbar(row)
  move_cursor(row, 0)

  # If no sessionbar info, just render a separator
  unless @sessionbar_info[:working_dir]
    separator_width = [@width, 1].max
    content = @pastel.dim("" * separator_width)
    print content
    remaining = @width - separator_width
    print " " * remaining if remaining > 0
    return 1
  end

  session_line = build_sessionbar_content
  
  # IMPORTANT: Always use print_with_padding which handles truncation
  # to prevent terminal auto-wrap
  print_with_padding(session_line)
  1
end

#required_heightObject



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/clacky/ui2/components/input_area.rb', line 88

def required_height
  # When paused (InlineInput active), don't take up any space
  return 0 if @paused

  height = 0
  
  # Session bar - calculate actual wrapped height
  height += calculate_sessionbar_height
  
  # Separator after session bar
  height += 1
  
  # Images
  height += @files.size
  
  # Calculate height considering wrapped lines
  # Use effective content width (respecting MAX_CONTENT_WIDTH_RATIO)
  content_width = effective_content_width(@width)
  @lines.each_with_index do |line, idx|
    prefix = if idx == 0
      prompt
    else
      " " * prompt.length
    end
    prefix_width = calculate_display_width(strip_ansi_codes(prefix))
    available_width = [content_width - prefix_width, 20].max  # At least 20 chars
    wrapped_segments = wrap_line(line, available_width)
    height += wrapped_segments.size
  end
  
  # Bottom separator
  height += 1
  
  # Command suggestions (rendered above input)
  height += @command_suggestions.required_height if @command_suggestions
  
  # Tips and user tips
  height += 1 if @tips_message
  height += 1 if @user_tip
  
  height
end

#resumeObject

Resume input area (when InlineInput is done)



484
485
486
# File 'lib/clacky/ui2/components/input_area.rb', line 484

def resume
  @paused = false
end

#set_prompt(prompt) ⇒ Object



532
533
534
# File 'lib/clacky/ui2/components/input_area.rb', line 532

def set_prompt(prompt)
  prompt = prompt
end

#set_skill_loader(skill_loader, agent_profile = nil) ⇒ Object

Set skill loader for command suggestions

Parameters:



134
135
136
137
# File 'lib/clacky/ui2/components/input_area.rb', line 134

def set_skill_loader(skill_loader, agent_profile = nil)
  @skill_loader = skill_loader
  @command_suggestions.load_skill_commands(skill_loader, agent_profile) if skill_loader
end

#set_tips(message, type: :info) ⇒ Object



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/clacky/ui2/components/input_area.rb', line 396

def set_tips(message, type: :info)
  # Cancel existing timer if any
  if @tips_timer&.alive?
    @tips_timer.kill
  end

  @tips_message = message
  @tips_type = type

  # Auto-clear tips after 2 seconds
  @tips_timer = Thread.new do
    sleep 2
    # Clear tips from state and screen
    @tips_message = nil
    # Tips row: start_row + session_bar(1) + separator(1) + images + lines + separator(1)
    tips_row = @last_render_row + 2 + @files.size + @lines.size + 1
    move_cursor(tips_row, 0)
    clear_line
    flush
  end
end

#shorten_path(path) ⇒ Object



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
# File 'lib/clacky/ui2/components/input_area.rb', line 1203

def shorten_path(path)
  return path if path.length <= 40

  # Replace home directory with ~
  home = ENV["HOME"]
  if home && path.start_with?(home)
    path = path.sub(home, "~")
  end

  # If still too long, show last parts
  if path.length > 40
    parts = path.split("/")
    if parts.length > 3
      ".../" + parts[-3..-1].join("/")
    else
      path[0..40] + "..."
    end
  else
    path
  end
end

#show_user_tip(probability: 0.4, rotation_interval: 12, max_tips: 3) ⇒ Object

Show a random user tip with probability and auto-rotation (max 3 tips)

Parameters:

  • probability (Float) (defaults to: 0.4)

    Probability of showing tip (0.0 to 1.0, default: 0.4)

  • rotation_interval (Integer) (defaults to: 12)

    Seconds between tip rotation (default: 12)

  • max_tips (Integer) (defaults to: 3)

    Maximum number of tips to show before stopping (default: 3)



430
431
432
433
434
435
436
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
# File 'lib/clacky/ui2/components/input_area.rb', line 430

def show_user_tip(probability: 0.4, rotation_interval: 12, max_tips: 3)
  # Random chance to show tip
  return unless rand < probability
  
  # Stop existing timer if any
  stop_user_tip_timer
  
  # Reset counter and pick first random tip
  @user_tip_count = 1
  @user_tip = USER_TIPS.sample
  
  # Start rotation timer (will show max_tips total)
  @user_tip_timer = Thread.new do
    while @user_tip_count < max_tips
      sleep rotation_interval
      @user_tip_count += 1
      
      # Pick a different tip
      old_tip = @user_tip
      loop do
        @user_tip = USER_TIPS.sample
        break if @user_tip != old_tip || USER_TIPS.size == 1
      end
    end
    
    # After showing max_tips, wait then clear
    sleep rotation_interval
    @user_tip = nil
    @user_tip_count = 0
  rescue => e
    # Silently handle thread errors
  end
end

#status_color_for(status) ⇒ Object



1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
# File 'lib/clacky/ui2/components/input_area.rb', line 1236

def status_color_for(status)
  case status.to_s.downcase
  when 'idle'
    :cyan  # Use darker cyan for idle state
  when 'working'
    :yellow  # Use yellow to highlight working state
  else
    :cyan
  end
end

#strip_ansi_codes(text) ⇒ String

Strip ANSI escape codes from a string

Parameters:

  • text (String)

    Text with ANSI codes

Returns:

  • (String)

    Text without ANSI codes



752
753
754
# File 'lib/clacky/ui2/components/input_area.rb', line 752

def strip_ansi_codes(text)
  text.gsub(/\e\[[0-9;]*m/, '')
end

#submitObject



596
597
598
599
600
601
602
# File 'lib/clacky/ui2/components/input_area.rb', line 596

def submit
  text = current_value
  files = @files.dup
  add_to_history(text) unless text.empty?
  clear
  { text: text, files: files }
end

#themeObject

Get current theme from ThemeManager



79
80
81
# File 'lib/clacky/ui2/components/input_area.rb', line 79

def theme
  UI2::ThemeManager.current_theme
end

#update_sessionbar(working_dir: nil, mode: nil, model: nil, tasks: nil, cost: nil, status: nil) ⇒ Object

Update session bar info

Parameters:

  • working_dir (String) (defaults to: nil)

    Working directory

  • mode (String) (defaults to: nil)

    Permission mode

  • model (String) (defaults to: nil)

    AI model name

  • tasks (Integer) (defaults to: nil)

    Number of completed tasks

  • cost (Float) (defaults to: nil)

    Total cost

  • status (String) (defaults to: nil)

    Workspace status (‘idle’ or ‘working’)



146
147
148
149
150
151
152
153
# File 'lib/clacky/ui2/components/input_area.rb', line 146

def update_sessionbar(working_dir: nil, mode: nil, model: nil, tasks: nil, cost: nil, status: nil)
  @sessionbar_info[:working_dir] = working_dir if working_dir
  @sessionbar_info[:mode] = mode if mode
  @sessionbar_info[:model] = model if model
  @sessionbar_info[:tasks] = tasks if tasks
  @sessionbar_info[:cost] = cost if cost
  @sessionbar_info[:status] = status if status
end

#wrap_line(line, max_width) ⇒ Array<Hash>

Wrap a line into multiple segments based on available width Considers display width of characters (multi-byte characters like Chinese)

Parameters:

  • line (String)

    The line to wrap

  • max_width (Integer)

    Maximum display width per wrapped line

Returns:

  • (Array<Hash>)

    Array of segment info: { text: String, start: Integer, end: Integer }



738
739
740
# File 'lib/clacky/ui2/components/input_area.rb', line 738

def wrap_line(line, max_width)
  super(line, max_width)
end