Class: Clacky::UI2::UIController

Inherits:
Object
  • Object
show all
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

Constant Summary collapse

CHORE_PHASE_KINDS =

Phases the user never asked for: post-task chores that run after the answer is already on screen. The web UI folds them into a card; a line-oriented terminal has no folding, so their transcript is swallowed and only a one-line progress indicator remains.

%w[memory_update skill_evolution].freeze
CHORE_DIGEST_MAX_FILES =

Caps for the post-chore digest. A chore is background work the user never asked for, so its recap must stay far shorter than the answer.

5
CHORE_DIGEST_MAX_TOOLS =
4
CHORE_DIGEST_MAX_ERRORS =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Clacky::UIInterface

#emit, #show_feedback_request, #show_subagent_end, #show_subagent_start, #with_phase

Constructor Details

#initialize(config = {}) ⇒ UIController

Returns a new instance of UIController.



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
56
57
58
59
60
61
62
63
64
65
# File 'lib/clacky/ui2/ui_controller.rb', line 23

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
  @feedback_countdown = nil  # Active auto-approve feedback countdown session
  @layout = LayoutManager.new(
    input_area: @input_area,
    todo_area: @todo_area
  )

  @running = false
  @input_callback = nil
  @interrupt_callback = nil
  @time_machine_callback = nil
  @model_switch_callback = nil
  @tasks_count = 0
  @total_cost = 0.0
  @session_id = nil
  @last_diff_lines = nil

  # ── Progress subsystem (v2: owned handles, stacked) ──────────────
  # Every progress indicator is an owned ProgressHandle. UiController
  # is the "owner" in the handle protocol: it keeps a stack of live
  # handles, only the top of which is rendered. See ProgressHandle
  # for the full protocol and stack semantics.
  @progress_stack = []
  @progress_mutex = Mutex.new
end

Instance Attribute Details

#available_modelsObject

Returns the value of attribute available_models.



21
22
23
# File 'lib/clacky/ui2/ui_controller.rb', line 21

def available_models
  @available_models
end

#configObject

Returns the value of attribute config.



21
22
23
# File 'lib/clacky/ui2/ui_controller.rb', line 21

def config
  @config
end

#inline_inputObject (readonly)

Returns the value of attribute inline_input.



20
21
22
# File 'lib/clacky/ui2/ui_controller.rb', line 20

def inline_input
  @inline_input
end

#input_areaObject (readonly)

Returns the value of attribute input_area.



20
21
22
# File 'lib/clacky/ui2/ui_controller.rb', line 20

def input_area
  @input_area
end

#layoutObject (readonly)

Returns the value of attribute layout.



20
21
22
# File 'lib/clacky/ui2/ui_controller.rb', line 20

def layout
  @layout
end

#rendererObject (readonly)

Returns the value of attribute renderer.



20
21
22
# File 'lib/clacky/ui2/ui_controller.rb', line 20

def renderer
  @renderer
end

#runningObject (readonly)

Returns the value of attribute running.



20
21
22
# File 'lib/clacky/ui2/ui_controller.rb', line 20

def running
  @running
end

Instance Method Details

#append_output(content) ⇒ Object

Append output to the output area.

If a progress indicator is currently active (somewhere in the buffer), rotate it to the tail after the append: business content ends up above, the spinner stays at the bottom. Without this, every subsequent ticker tick on a non-tail progress entry would trigger a full output repaint (visible flicker) and the visual order would have business messages appearing below the spinner.



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/clacky/ui2/ui_controller.rb', line 229

def append_output(content)
  return nil if Thread.current[:clacky_chore_phase]
  return nil if Thread.current[:clacky_concurrent_phase]

  content = prefix_with_phase_label(content)
  @progress_mutex.synchronize do
    top = @progress_stack.last
    if top && top.entry_id
      @layout.remove_entry(top.entry_id)
      top.__detach_entry!
      new_id = @layout.append_output(content)
      progress_id = @layout.append_output(render_for(top))
      top.__rebind_entry!(progress_id)
      new_id
    else
      @layout.append_output(content)
    end
  end
end

#clear_inputObject

Clear the input area



173
174
175
# File 'lib/clacky/ui2/ui_controller.rb', line 173

def clear_input
  @input_area.clear
end

#display_session_history(user_messages) ⇒ Object

Display recent user messages when loading session

Parameters:

  • user_messages (Array<String>)

    Array of recent user message texts



1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
# File 'lib/clacky/ui2/ui_controller.rb', line 1625

def display_session_history(user_messages)
  theme = ThemeManager.current_theme

  # Show logo banner only
  append_output(@welcome_banner.(width: @layout.screen.width))

  # Show simple header
  append_output(theme.format_text("Recent conversation:", :info))

  # Display each user message with numbering
  user_messages.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_bannerObject

Display welcome banner with logo and agent info



1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
# File 'lib/clacky/ui2/ui_controller.rb', line 1600

def display_welcome_banner
  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 ... tags

Parameters:

  • content (String)

    Raw content from model

Returns:

  • (String)

    Content with thinking tags removed



464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'lib/clacky/ui2/ui_controller.rb', line 464

def filter_thinking_tags(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

Parameters:

  • name (String)

    Tool name

  • args (String, Hash)

    Tool arguments

Returns:

  • (String)

    Formatted call string



1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
# File 'lib/clacky/ui2/ui_controller.rb', line 1562

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

Parameters:

  • tool_name (String)

    Tool name

Returns:

  • (Object, nil)

    Tool instance or nil



1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
# File 'lib/clacky/ui2/ui_controller.rb', line 1584

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



1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
# File 'lib/clacky/ui2/ui_controller.rb', line 1762

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.update_sessionbar(
      session_id: @session_id,
      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

Parameters:

  • key (Symbol, String, Hash)

    Key input or rapid input hash



1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
# File 'lib/clacky/ui2/ui_controller.rb', line 1679

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

  # During an auto-approve feedback countdown the normal input box stays
  # live; the first meaningful keystroke cancels the auto-timeout so the
  # user can finish typing their answer without being rushed.
  if @feedback_countdown && !@feedback_countdown[:intervened] && countdown_intervening_key?(key)
    intervene_feedback_countdown
  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 all active progress indicators (ticker threads + entries).
    # An interrupt may happen at any point in a nested flow (e.g.
    # idle compression during a task); finish the whole stack from
    # top to bottom so nothing is left running.
    interrupt_all_progress

    # 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)

Parameters:

  • recent_user_messages (Array<String>, nil) (defaults to: nil)

    Recent user messages when loading session



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/clacky/ui2/ui_controller.rb', line 75

def initialize_and_show_banner(recent_user_messages: nil)
  @running = true

  # Set session bar data before initializing screen
  @input_area.update_sessionbar(
    session_id: @session_id,
    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 recent_user_messages && !recent_user_messages.empty?
    display_session_history(recent_user_messages)
  else
    display_welcome_banner
  end
end

#input_loopObject

Main input loop



1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
# File 'lib/clacky/ui2/ui_controller.rb', line 1653

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

#interrupt_all_progressObject

Finish every active progress handle, top to bottom. Used by the interrupt path (Ctrl+C) so a single keypress guarantees the UI is quiescent regardless of how many nested/background progresses are running.



724
725
726
727
728
729
730
731
732
733
734
# File 'lib/clacky/ui2/ui_controller.rb', line 724

def interrupt_all_progress
  # Snapshot outside the handle's finish() (which also grabs the
  # mutex via unregister_progress) to avoid re-entrant lock issues.
  handles = @progress_mutex.synchronize { @progress_stack.dup }
  # Finish from top (newest) to bottom (oldest) so each top is the
  # one currently rendering when it finishes.
  handles.reverse_each(&:finish)
  # Also drop legacy-shim handle registry so a subsequent
  # show_progress(phase: "done") from unmigrated callers is a no-op.
  @legacy_progress_handles&.clear
end

#log(message, level: :info) ⇒ Object

Log message to output area (use instead of puts)

Parameters:

  • message (String)

    Message to log

  • level (Symbol) (defaults to: :info)

    Log level (:debug, :info, :warning, :error)



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/clacky/ui2/ui_controller.rb', line 271

def log(message, level: :info)
  theme = ThemeManager.current_theme

  output = case level
  when :debug
    # Gray dimmed text for debug messages
    theme.format_text("    [DEBUG] #{message}", :thinking)
  when :info
    # Info symbol with normal text
    "#{theme.format_symbol(:info)} #{message}"
  when :warning
    # Warning rendering
    @renderer.render_warning(message)
  when :error
    # Error rendering
    @renderer.render_error(message)
  else
    # Default to info
    "#{theme.format_symbol(:info)} #{message}"
  end

  append_output(output)
end

#on_input(&block) ⇒ Object

Set callback for user input

Parameters:

  • block (Proc)

    Callback to execute with user input



186
187
188
# File 'lib/clacky/ui2/ui_controller.rb', line 186

def on_input(&block)
  @input_callback = block
end

#on_interrupt(&block) ⇒ Object

Set callback for interrupt (Ctrl+C)

Parameters:

  • block (Proc)

    Callback to execute on interrupt



192
193
194
# File 'lib/clacky/ui2/ui_controller.rb', line 192

def on_interrupt(&block)
  @interrupt_callback = block
end

#on_mode_toggle(&block) ⇒ Object

Set callback for mode toggle (Shift+Tab)

Parameters:

  • block (Proc)

    Callback to execute on mode toggle



198
199
200
# File 'lib/clacky/ui2/ui_controller.rb', line 198

def on_mode_toggle(&block)
  @mode_toggle_callback = block
end

#on_model_switch(&block) ⇒ Object

Set callback for model switch (from /model slash command)

Parameters:

  • block (Proc)

    Callback to execute on model switch



210
211
212
# File 'lib/clacky/ui2/ui_controller.rb', line 210

def on_model_switch(&block)
  @model_switch_callback = block
end

#on_time_machine(&block) ⇒ Object

Set callback for time machine (ESC key)

Parameters:

  • block (Proc)

    Callback to execute on time machine



204
205
206
# File 'lib/clacky/ui2/ui_controller.rb', line 204

def on_time_machine(&block)
  @time_machine_callback = block
end

#phase_end(phase_id, summary: nil) ⇒ Object



1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
# File 'lib/clacky/ui2/ui_controller.rb', line 1084

def phase_end(phase_id, summary: nil)
  return if concurrent_phase_end(phase_id, summary: summary)

  Thread.current[:clacky_phase_id] = nil if Thread.current[:clacky_phase_id] == phase_id
  Thread.current[:clacky_phase_label] = nil
  @phase_mutex ||= Mutex.new
  info = @phase_mutex.synchronize { @active_phases&.delete(phase_id) }
  return unless info

  label = info[:label]

  if info[:chore]
    Thread.current[:clacky_chore_phase] = nil
    handle = @chore_progress
    @chore_progress = nil
    @chore_nested = nil
    @chore_steps = 0
    handle&.discard

    digest = chore_digest_lines
    @phase_mutex.synchronize { @chore_digest = nil }

    # No summary and nothing captured means nothing worth reporting
    # happened (the common "no memory updates needed" path) — leave no
    # trace at all.
    has_summary = summary && !summary.to_s.strip.empty?
    return if !has_summary && digest.empty?

    elapsed = (Time.now - info[:started_at]).round
    head = has_summary ? "#{label}#{summary.to_s.strip} (#{elapsed}s)" : "#{label} (#{elapsed}s)"
    append_output(@renderer.render_system_message(head, prefix_newline: false))
    theme = ThemeManager.current_theme
    digest.each { |line| append_output(theme.format_text("    #{line}", :thinking)) }
    return
  end

  tail = summary && !summary.to_s.strip.empty? ? "#{summary.to_s.strip}" : ""
  banner = "──────── ▲ #{label} done#{tail} ────────"
  append_output(@renderer.render_system_message(banner, prefix_newline: false))
end

#phase_start(kind:, label:, concurrent: false) ⇒ Object



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
# File 'lib/clacky/ui2/ui_controller.rb', line 1057

def phase_start(kind:, label:, concurrent: false)
  return concurrent_phase_start(kind: kind, label: label) if concurrent && !verbose_phases?

  phase_id = SecureRandom.uuid
  chore = CHORE_PHASE_KINDS.include?(kind.to_s) && !verbose_phases?
  @phase_mutex ||= Mutex.new
  @phase_mutex.synchronize do
    @active_phases ||= {}
    @active_phases[phase_id] = { kind: kind, label: label, started_at: Time.now, chore: chore }
  end
  Thread.current[:clacky_phase_id] = phase_id

  if chore
    # Start the indicator before arming the gate: this handle is the
    # one thing that stays visible during the chore.
    @chore_progress = start_progress(message: label, style: :quiet)
    Thread.current[:clacky_chore_phase] = phase_id
    return phase_id
  end

  banner = "──────── ▼ #{label} ────────"
  append_output(@renderer.render_system_message(banner, prefix_newline: true))
  # Only concurrent phases interleave, so only they need per-line tagging.
  Thread.current[:clacky_phase_label] = concurrent ? label : nil
  phase_id
end

#progress_active?Boolean

Returns true if any progress indicator is currently active.

Returns:

  • (Boolean)


716
717
718
# File 'lib/clacky/ui2/ui_controller.rb', line 716

def progress_active?
  @progress_mutex.synchronize { !@progress_stack.empty? }
end

#register_progress(handle) ⇒ Object

Called by ProgressHandle#start.



744
745
746
747
748
749
750
751
752
753
754
755
756
757
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
# File 'lib/clacky/ui2/ui_controller.rb', line 744

def register_progress(handle)
  # Inside a chore phase only the phase's own indicator occupies a line.
  # Nested handles (the subagent's LLM calls and tool runs) get no entry
  # of their own — otherwise each one commits a permanent final frame on
  # finish, since unregister_progress writes straight into the buffer and
  # never passes through append_output's chore gate. Their activity is
  # instead folded into the chore line by +fold_into_chore_line+.
  if Thread.current[:clacky_chore_phase] && @chore_progress
    @progress_mutex.synchronize do
      @chore_nested ||= []
      @chore_nested << handle
      @chore_steps = @chore_steps.to_i + 1 if handle.style == :primary
      fold_into_chore_line(handle)
    end
    return nil
  end

  # Same reasoning inside a concurrent phase: its nested handles own no
  # line, since the shared parallel-progress line is the only thing on
  # screen. Without this, unregister_progress would commit a permanent
  # final frame straight into the buffer, bypassing append_output's gate.
  return nil if Thread.current[:clacky_concurrent_phase]

  @progress_mutex.synchronize do
    prev_top = @progress_stack.last
    if prev_top
      # Plan B: the lower handle loses its OutputBuffer entry until
      # the new top finishes. We remove its on-screen line now and
      # tell it to forget its id; we'll allocate a new id on restore.
      remove_entry(prev_top.entry_id)
      prev_top.__detach_entry!
    end

    @progress_stack.push(handle)
    entry_id = append_output_unlocked(render_for(handle))
    recompute_sessionbar_status
    entry_id
  end
end

#render_frame(handle, frame) ⇒ Object

Called by ProgressHandle's ticker and update. Writes frame into the handle's entry iff it is currently top-of-stack. Non-top handles silently do nothing (their entry was detached in register_progress).



826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
# File 'lib/clacky/ui2/ui_controller.rb', line 826

def render_frame(handle, frame)
  @progress_mutex.synchronize do
    if @chore_nested&.include?(handle)
      fold_into_chore_line(handle)
      return
    end

    # The chore's own ticker must render the folded view too, otherwise
    # every tick repaints the bare label and the line flickers between
    # "<label>…" and "<label> · <activity>…".
    if @chore_progress && @chore_progress == handle && @chore_nested&.any?
      fold_into_chore_line(@chore_nested.last)
      return
    end

    return unless @progress_stack.last == handle
    return unless handle.entry_id

    has_output = @stdout_lines && !@stdout_lines.empty?
    suffix = has_output ?
      " (Ctrl+C to interrupt · Ctrl+O to view output)" :
      " (Ctrl+C to interrupt)"
    decorated = "#{frame}#{suffix}"

    painted = handle.style == :primary ?
      @renderer.render_working(decorated) :
      @renderer.render_progress(decorated)
    update_entry(handle.entry_id, painted)

    # Re-evaluate sessionbar: a quiet handle that crosses the fast-finish
    # threshold should upgrade the status bar to "working" so long-running
    # tools (terminal running a build, web_fetch) visibly reflect activity.
    recompute_sessionbar_status
  end
end

#request_confirmation(message, default: true) ⇒ Boolean, ...

Request confirmation from user (blocking)

Parameters:

  • message (String)

    Confirmation prompt

  • default (Boolean) (defaults to: true)

    Default value if user presses Enter

Returns:

  • (Boolean, String, nil)

    true/false for yes/no, String for feedback, nil for cancelled



1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
# File 'lib/clacky/ui2/ui_controller.rb', line 1304

def request_confirmation(message, default: true)
  # Show question in output with theme styling
  theme = ThemeManager.current_theme
  question_symbol = theme.format_symbol(:info)
  append_output("#{question_symbol} #{message}")

  # 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)
  inline_id = @layout.append_output(inline_input.render)
  @layout.position_inline_input_cursor(inline_input)

  result_text = nil
  begin
    # Collect input (blocks until user presses Enter).
    # May raise AgentInterrupted if main thread Thread#raises the
    # worker mid-pop — we MUST still restore input state in ensure.
    result_text = inline_input.collect
  ensure
    # Clean up - remove the inline input lines (handle wrapped lines).
    # Use the tracked id so removal is safe even when more output
    # was appended in between.
    @layout.remove_entry(inline_id) if inline_id

    # Deactivate InlineInput and restore the main InputArea. This
    # MUST run even on exception so the user can type after
    # interrupting a confirmation prompt.
    @inline_input = nil
    @input_area.resume
    @layout.recalculate_layout
    @layout.render_all
  end

  # Append the final response to output (only on normal return)
  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

  # 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

#request_feedback_with_countdown(seconds: 10) ⇒ String, Symbol

Auto-approve countdown for ask_user: show a single live countdown line. If the user presses any key before timeout, collect their answer and return it (intervention). Otherwise return :timeout so the agent auto-decides and continues. Show a live single-line countdown in the output area while keeping the normal input box usable. The agent thread blocks here until either:

* the user submits a message in the regular input box -> returns the text
* the user starts typing (cancels the auto-timeout but keeps waiting)
* the countdown reaches zero with no interaction -> returns :timeout

Parameters:

  • seconds (Integer) (defaults to: 10)

    Countdown duration

  • seconds (Integer) (defaults to: 10)

    Countdown duration

Returns:

  • (String, Symbol)

    feedback string, "" (bare Enter), or :timeout

  • (String, Symbol)

    feedback text, or :timeout



1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
# File 'lib/clacky/ui2/ui_controller.rb', line 1380

def request_feedback_with_countdown(seconds: 10)
  theme = ThemeManager.current_theme

  queue = Queue.new
  entry_id = @layout.append_output(countdown_prompt(seconds, theme))

  session = {
    queue: queue,
    entry_id: entry_id,
    intervened: false,
    watchdog: nil
  }
  @feedback_countdown = session

  session[:watchdog] = Clacky::ThreadRegistry.spawn(name: "ui-watchdog") do
    remaining = seconds.to_i
    while remaining.positive?
      break if session[:intervened]

      @layout.replace_entry(entry_id, countdown_prompt(remaining, theme))
      sleep 1
      remaining -= 1
    end
    queue.push(:timeout) unless session[:intervened]
  end

  begin
    result = queue.pop
  ensure
    session[:watchdog].kill if session[:watchdog]&.alive?
    @feedback_countdown = nil
    @layout.remove_entry(entry_id) if entry_id
    @layout.recalculate_layout
    @layout.render_all
  end

  if result == :timeout
    append_output(theme.format_text("  No response — continuing automatically.", :thinking))
  elsif result.to_s.strip.empty?
    append_output(theme.format_text("  → (continue)", :success))
    result = ""
  end

  result
end

#set_agent(agent, agent_profile = nil) ⇒ Object

Set agent for command suggestions

Parameters:

  • agent (Clacky::Agent)

    The agent instance with skill management

  • agent_profile (Clacky::AgentProfile, nil) (defaults to: nil)

    Current agent profile for skill filtering



217
218
219
# File 'lib/clacky/ui2/ui_controller.rb', line 217

def set_agent(agent, agent_profile = nil)
  @input_area.set_agent(agent, agent_profile)
end

#set_idle_statusObject

Set workspace status to idle (called when agent stops working)



1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
# File 'lib/clacky/ui2/ui_controller.rb', line 1215

def set_idle_status
  # Safety net: close any legacy progress slots that were opened via
  # show_progress(progress_type: X, phase: "active") but never paired
  # with a corresponding phase: "done" call. Historically the
  # "retrying" slot in LlmCaller was leaked on every successful
  # recovery, leaving the user with a stale "Network failed ... (NNN s)"
  # line ticking forever. LlmCaller now closes its own slot (see the
  # ensure in call_llm), but we mirror that defense here so any
  # future code path that forgets to close a slot still gets cleaned
  # up at the well-defined idle boundary.
  close_leaked_legacy_progress_handles

  update_sessionbar(status: 'idle')
  @last_sessionbar_status = 'idle'
  # Clear user tip when agent stops working
  @input_area.clear_user_tip
  # Hide todo area while idle (data preserved, restored on next work)
  @layout.hide_todos
  @layout.render_input
end

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

Set input tips message

Parameters:

  • message (String)

    Tip message to display

  • type (Symbol) (defaults to: :info)

    Tip type (:info, :warning, etc.)



180
181
182
# File 'lib/clacky/ui2/ui_controller.rb', line 180

def set_input_tips(message, type: :info)
  @input_area.set_tips(message, type: type)
end

#set_skill_loader(skill_loader, agent_profile = nil) ⇒ Object

Set skill loader for command suggestions in the input area

Parameters:



107
108
109
# File 'lib/clacky/ui2/ui_controller.rb', line 107

def set_skill_loader(skill_loader, agent_profile = nil)
  @input_area.set_skill_loader(skill_loader, agent_profile)
end

#set_working_statusObject

Set workspace status to working (called when agent starts working)



1253
1254
1255
1256
1257
1258
1259
1260
# File 'lib/clacky/ui2/ui_controller.rb', line 1253

def set_working_status
  update_sessionbar(status: 'working')
  # Restore todo area if it was hidden during idle
  @layout.show_todos
  # 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:, interim: false, created_at: nil) ⇒ Object

Show assistant message

Parameters:

  • content (String)

    Message content



451
452
453
454
455
456
457
458
# File 'lib/clacky/ui2/ui_controller.rb', line 451

def show_assistant_message(content, files:, interim: false, created_at: nil)
  # Filter out thinking tags from models like MiniMax M2.1 that use <think>...</think>
  filtered_content = filter_thinking_tags(content)
  return if filtered_content.nil? || filtered_content.strip.empty?

  output = @renderer.render_assistant_message(filtered_content)
  append_output(output)
end

#show_command_outputObject

Show fullscreen command output view



1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
# File 'lib/clacky/ui2/ui_controller.rb', line 1527

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 = Clacky::ThreadRegistry.spawn(name: "ui-fullscreen-refresh") 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, cost_source: nil, task_id: nil) ⇒ Object

Show completion status (only for tasks with more than 5 iterations)

Parameters:

  • iterations (Integer)

    Number of iterations

  • cost (Float)

    Cost of this run

  • duration (Float) (defaults to: nil)

    Duration in seconds

  • cache_stats (Hash) (defaults to: nil)

    Cache statistics

  • awaiting_user_feedback (Boolean) (defaults to: false)

    Whether agent is waiting for user feedback



632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'lib/clacky/ui2/ui_controller.rb', line 632

def show_complete(iterations:, cost:, duration: nil, cache_stats: nil, awaiting_user_feedback: false, cost_source: nil, task_id: nil)
  # Update status back to 'idle' when task is complete
  update_sessionbar(status: 'idle')

  # Clear user tip when agent stops working
  @input_area.clear_user_tip
  # Hide todo area while idle (data preserved, restored on next work)
  @layout.hide_todos
  @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

Parameters:

Returns:

  • (Hash, nil)

    Hash with updated config values, or nil if cancelled



1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
# File 'lib/clacky/ui2/ui_controller.rb', line 1847

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, model_id: model["id"] }
      }
    end

    # Add action buttons
    choices << { name: "" * 50, disabled: true }
    choices << { name: "[+] Add New Model", value: { action: :add } }
    if current_config.models.length > 0
      choices << { name: "[*] Edit Current Model", value: { action: :edit } }
      choices << { name: "[-] Delete Model", value: { action: :delete } } if current_config.models.length > 1
    end
    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
      # Just signal the caller which model to switch to.
      # All side effects (agent.switch_model_by_id to rebuild the Client,
      # set_default_model_by_id, persistence) are done by the CLI layer
      # in handle_config_command — this keeps show_config_modal a pure
      # UI component and avoids the modal half-mutating config while
      # the agent's @client still points at the old credentials.
      return { action: :switch, model_id: result[:model_id] }
    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
        )
        # Hand off the new model's stable id to the caller. CLI layer
        # decides whether to switch to it / mark default / persist.
        new_id = current_config.models.last["id"]
        return { action: :add, model_id: new_id }
      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).
        # Because we mutate the same hash that's in @models, the model's
        # stable id is preserved — the caller will rebuild the agent's
        # Client by calling agent.switch_model_by_id with the same id,
        # which reruns the Bedrock/anthropic/api_key detection.
        current_model["api_key"] = edited[:api_key]
        current_model["model"] = edited[:model]
        current_model["base_url"] = edited[:base_url]
        return { action: :edit, model_id: current_model["id"] }
      end
    when :delete
      if current_config.models.length <= 1
        # Can't delete - show error and continue
        next
      end

      # Delete current model — this clears @current_model_id so the
      # next current_model lookup picks type:default or index fallback.
      current_config.remove_model(current_config.current_model_index)
      # New current model id after deletion (may be nil briefly; resolved
      # on next current_model call, which also re-anchors @current_model_id).
      new_current = current_config.current_model
      return { action: :delete, model_id: new_current && new_current["id"] }
    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

Parameters:

  • old_content (String)

    Old content

  • new_content (String)

    New content

  • max_lines (Integer) (defaults to: 50)

    Maximum lines to show



1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
# File 'lib/clacky/ui2/ui_controller.rb', line 1467

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, code: nil, top_up_url: nil, raw_message: nil) ⇒ Object

Show error message

Parameters:

  • message (String)

    Error message



1033
1034
1035
1036
# File 'lib/clacky/ui2/ui_controller.rb', line 1033

def show_error(message, code: nil, top_up_url: nil, raw_message: nil)
  output = @renderer.render_error(message)
  append_output(output)
end

#show_file_edit_preview(path) ⇒ Object

Show file operation preview (Edit tool)

Parameters:

  • path (String)

    File path



422
423
424
425
426
427
428
# File 'lib/clacky/ui2/ui_controller.rb', line 422

def show_file_edit_preview(path)
  return if chore_capture(:file, 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

Parameters:

  • error_message (String)

    Error message



432
433
434
435
436
437
# File 'lib/clacky/ui2/ui_controller.rb', line 432

def show_file_error(error_message)
  return if chore_capture(:error, error_message)

  theme = ThemeManager.current_theme
  append_output("   #{theme.format_text("Warning:", :error)} #{error_message}")
end

#show_file_write_preview(path, is_new_file:) ⇒ Object

Show file operation preview (Write tool)

Parameters:

  • path (String)

    File path

  • is_new_file (Boolean)

    Whether this is a new file



410
411
412
413
414
415
416
417
418
# File 'lib/clacky/ui2/ui_controller.rb', line 410

def show_file_write_preview(path, is_new_file:)
  return if chore_capture(:file, path)

  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_goal_status(goal) ⇒ Object



135
136
137
138
# File 'lib/clacky/ui2/ui_controller.rb', line 135

def show_goal_status(goal)
  @input_area.set_goal(goal)
  @layout.render_input
end

#show_helpObject

Show help text



1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
# File 'lib/clacky/ui2/ui_controller.rb', line 1263

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("/model", :success)}       - Quickly switch the current model",
    "  #{theme.format_text("/config", :success)}      - Configure models, API keys, settings",
    "  #{theme.format_text("/goal", :success)}        - Set a standing goal for autonomous work",
    "    #{theme.format_text("/goal <text>", :dim)}       Set a goal and start working toward it",
    "    #{theme.format_text("/goal status", :dim)}       Show current goal and turn budget",
    "    #{theme.format_text("/goal pause", :dim)}       Pause the goal loop (keeps progress)",
    "    #{theme.format_text("/goal resume", :dim)}      Resume a paused goal",
    "    #{theme.format_text("/goal clear", :dim)}       Clear the goal entirely",
    "    #{theme.format_text("/goal --turns N <text>", :dim)}  Set goal with custom turn budget (default 20)",
    "  #{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_info(message, prefix_newline: true) ⇒ Object

Show info message

Parameters:

  • message (String)

    Info message

  • prefix_newline (Boolean) (defaults to: true)

    Whether to add newline before message (default: true)



1019
1020
1021
1022
# File 'lib/clacky/ui2/ui_controller.rb', line 1019

def show_info(message, prefix_newline: true)
  output = @renderer.render_system_message(message, prefix_newline: prefix_newline)
  append_output(output)
end

#show_model_switch_modal(current_config, submodels_for) ⇒ Hash?

Quick model switcher — lists configured model cards and returns the picked card's stable id. Unlike show_config_modal this never mutates config; it's a pure picker. All side effects live in the CLI layer. Two-level drawer picker for /model.

Level 1 (card list): Enter selects a card and uses its default model (clearing any sub-model overlay); → opens that card's sub-model drawer (only for cards whose provider exposes >= 2 sub-models, marked "›").

Level 2 (sub-model list): Enter pins the chosen sub-model (or Default); ← / Esc returns to the card list.

Parameters:

  • current_config (AgentConfig)
  • submodels_for (Proc)

    called with a card hash, returns its provider sub-model names (or [] if none / single).

Returns:

  • (Hash, nil)

    { model_id: } or nil if cancelled / no models

  • (Hash, nil)

    { model_id:, model_name: } where model_name is the chosen sub-model (nil = the card's own default), or nil if cancelled.



1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
# File 'lib/clacky/ui2/ui_controller.rb', line 1971

public def show_model_switch_modal(current_config, submodels_for)
  return nil if current_config.models.empty?

  on_close = -> { @layout.rerender_all }

  loop do
    card = show_model_card_level(current_config, submodels_for, on_close)
    return nil if card.nil?

    # Plain card pick (Enter): use the card default, clear overlay.
    return { model_id: card[:model_id], model_name: nil } unless card[:expand]

    # → opened the drawer: let the user pick a sub-model for this card.
    model = current_config.models.find { |m| m["id"] == card[:model_id] }
    drawer = {
      model_id: card[:model_id],
      card_model: card[:card_model],
      submodels: submodels_for.call(model) || [],
      current_overlay: current_config.session_model_overlay_name
    }
    sub = show_model_submodel_level(drawer, on_close)
    next if sub == :back  # ← / Esc: back to the card list

    return { model_id: card[:model_id], model_name: sub }
  end
end

#show_progress(message = nil, prefix_newline: true, progress_type: "thinking", phase: "active", metadata: {}) ⇒ Object


Legacy shim: show_progress(message, phase:, progress_type:, ...)

This method preserves the pre-refactor API so existing call sites (Agent#run, Agent#think, LlmCaller retry, trigger_idle_compression, MemoryUpdater) keep working until they're migrated to the owned- handle API.

Each progress_type owns its own handle slot so two concurrent background flows (e.g. idle compression + thinking) can coexist without stomping on each other — exactly the race that caused the yellow/gray flicker bug.



946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/clacky/ui2/ui_controller.rb', line 946

def show_progress(message = nil, prefix_newline: true, progress_type: "thinking", phase: "active", metadata: {})
  _ = prefix_newline # ignored in v2; layout is not the caller's concern

  type = progress_type.to_s
  style = %w[retrying idle_compress].include?(type) ? :quiet : :primary

  @legacy_progress_handles ||= {}

  if phase.to_s == "done"
    handle = @legacy_progress_handles[type]
    handle&.finish(final_message: message)
    @legacy_progress_handles.delete(type)
    return
  end

  # "active" phase — start a new handle or update the existing one.
  existing = @legacy_progress_handles[type]
  if existing&.running?
    # Bare re-entry: no new info → just leave the existing spinner alone.
    # This preserves the long-standing "Agent#run and Agent#think both
    # call show_progress for fast feedback" idiom.
    return if message.nil? && .empty?

    attempt = [:attempt]
    total   = [:total]
    suffix  = (attempt && total) ? " (#{attempt}/#{total})" : ""
    existing.update(message: "#{message || existing.message}#{suffix}", metadata: )
    return
  end

  attempt = [:attempt]
  total   = [:total]
  suffix  = (attempt && total) ? " (#{attempt}/#{total})" : ""
  display = ((message && !message.to_s.strip.empty?) ? message.to_s : Clacky::THINKING_VERBS.sample) + suffix

  @legacy_progress_handles[type] = start_progress(message: display, style: style)
end

#show_shell_preview(command) ⇒ Object

Show shell command preview

Parameters:

  • command (String)

    Shell command



441
442
443
444
445
# File 'lib/clacky/ui2/ui_controller.rb', line 441

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

Parameters:

  • message (String)

    Success message



1040
1041
1042
1043
# File 'lib/clacky/ui2/ui_controller.rb', line 1040

def show_success(message)
  output = @renderer.render_success(message)
  append_output(output)
end

#show_time_machine_menu(history) ⇒ Integer?

Show time machine menu for task undo/redo

Parameters:

  • history (Array<Hash>)

    Task history with format: [summary, status, has_branches]

Returns:

  • (Integer, nil)

    Selected task ID or nil if cancelled



2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
# File 'lib/clacky/ui2/ui_controller.rb', line 2073

public def show_time_machine_menu(history)
  modal = Components::ModalComponent.new

  active_index = nil

  # Build menu choices from history
  choices = history.each_with_index.map do |task, idx|
    # Status marker. The cursor itself draws a "→", so use distinct
    # glyphs here to avoid visual collision:
    #   ● current   · on-path history   ✗ undone/abandoned branch
    marker = case task[:status]
    when :current
      active_index = idx
      ""
    when :undone
      ""
    else
      "· "
    end

    # Branch indicator
    marker += "" 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

    label = "#{marker}Task #{task[:task_id]}: #{summary}"
    label += "  (undone)" if task[:status] == :undone

    {
      name: label,
      value: task[:task_id],
      dim: task[:status] == :undone
    }
  end

  # Show modal, landing the cursor on the currently-active task.
  result = modal.show(
    title: "Time Machine - Select Task to Navigate",
    choices: choices,
    initial_index: active_index,
    on_close: -> { @layout.rerender_all }
  )

  result # Return selected task_id or nil
end

#show_token_usage(token_data) ⇒ Object

Display token usage statistics

Parameters:

  • token_data (Hash)

    Token usage data containing:

    • delta_tokens: token delta from previous iteration
    • prompt_tokens: input tokens
    • completion_tokens: output tokens
    • total_tokens: total tokens
    • cache_write: cache write tokens
    • cache_read: cache read tokens
    • cost: cost for this iteration


325
326
327
328
329
330
331
332
333
334
335
336
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
395
396
397
398
# File 'lib/clacky/ui2/ui_controller.rb', line 325

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

Parameters:

  • formatted_args (String)

    Formatted arguments string



402
403
404
405
# File 'lib/clacky/ui2/ui_controller.rb', line 402

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

Parameters:

  • name (String)

    Tool name

  • args (String, Hash)

    Tool arguments (JSON string or Hash)



538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/clacky/ui2/ui_controller.rb', line 538

def show_tool_call(name, args)
  return if chore_capture(:tool, name)

  # 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
  @stdout_partial_tail = false

  # Special handling for ask_user: render as a readable interactive card
  # with the full questions and options, rather than the truncated format_call summary.
  if Clacky::Tools::AskUser.feedback_tool?(name)
    args_data = args.is_a?(String) ? (JSON.parse(args, symbolize_names: true) rescue {}) : args
    questions = Clacky::Tools::AskUser.normalize_questions(args_data)
    context   = Clacky::Tools::AskUser.fetch_key(args_data, :context).to_s.strip

    parts = []
    parts << context unless context.empty?

    multiple = questions.size > 1
    questions.each_with_index do |q, q_index|
      parts << "" unless parts.empty?
      parts << (multiple ? "#{q_index + 1}. #{q[:question]}" : q[:question])
      parts << q[:description] unless q[:description].empty?

      next if q[:options].empty?

      q[:options].each_with_index do |opt, i|
        marker = q[:recommended] == i ? "  ← recommended" : ""
        parts << "  #{i + 1}. #{opt}#{marker}"
      end
      parts << "  #{q[:options].size + 1}. Other — type your own answer" if q[:allow_free_text]
    end

    card_text = parts.join("\n")
    output = @renderer.render_system_message(card_text, prefix_newline: true)
    append_output(output)
    return
  end

  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

Parameters:

  • error (String, Exception)

    Error message or exception



592
593
594
595
596
597
598
# File 'lib/clacky/ui2/ui_controller.rb', line 592

def show_tool_error(error)
  error_msg = error.is_a?(Exception) ? error.message : error.to_s
  return if chore_capture(:error, error_msg)

  output = @renderer.render_tool_error(error: error_msg)
  append_output(output)
end

#show_tool_result(result) ⇒ Object

Show tool result

Parameters:

  • result (String)

    Formatted tool result



585
586
587
588
# File 'lib/clacky/ui2/ui_controller.rb', line 585

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.

Parameters:

  • lines (Array<String>)

    One or more stdout chunks (may contain embedded newlines or be partial lines)



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# File 'lib/clacky/ui2/ui_controller.rb', line 605

def show_tool_stdout(lines)
  return if lines.nil? || lines.empty?
  @stdout_lines ||= []
  # Chunks may carry multiple newlines or trailing partial lines.
  # Re-split on \n so the fullscreen view renders one logical line per row.
  lines.each do |chunk|
    next if chunk.nil? || chunk.empty?
    chunk.to_s.split("\n", -1).each_with_index do |part, idx|
      if idx == 0 && !@stdout_lines.empty? && @stdout_partial_tail
        @stdout_lines[-1] = @stdout_lines[-1] + part
      else
        @stdout_lines << part
      end
    end
    # Track whether the chunk ended on a partial line (no trailing \n)
    # so the next chunk's first segment appends to it instead of
    # starting a new row.
    @stdout_partial_tail = !chunk.to_s.end_with?("\n")
  end
end

#show_warning(message) ⇒ Object

Show warning message

Parameters:

  • message (String)

    Warning message



1026
1027
1028
1029
# File 'lib/clacky/ui2/ui_controller.rb', line 1026

def show_warning(message)
  output = @renderer.render_warning(message)
  append_output(output)
end

#startObject

Start the UI controller



68
69
70
71
# File 'lib/clacky/ui2/ui_controller.rb', line 68

def start
  initialize_and_show_banner
  start_input_loop
end

#start_input_loopObject

Start input loop (separate from initialization)



99
100
101
102
# File 'lib/clacky/ui2/ui_controller.rb', line 99

def start_input_loop
  @running = true
  input_loop
end

#start_progress(message: nil, style: :primary, quiet_on_fast_finish: false) ⇒ Clacky::UI2::ProgressHandle

Start a new progress indicator and return its owned handle.

Parameters:

  • message (String) (defaults to: nil)

    Initial progress message.

  • style (Symbol) (defaults to: :primary)

    :primary (foreground, yellow, bumps sessionbar) or :quiet (background, gray, no sessionbar change).

  • quiet_on_fast_finish (Boolean) (defaults to: false)

    See ProgressHandle — when true, a finish that elapses under FAST_FINISH_THRESHOLD_SECONDS removes the entry instead of leaving a permanent final frame. Preferred for tool-execution wrappers.

Returns:



687
688
689
690
691
692
693
694
695
# File 'lib/clacky/ui2/ui_controller.rb', line 687

def start_progress(message: nil, style: :primary, quiet_on_fast_finish: false)
  display = (message.nil? || message.to_s.strip.empty?) ? Clacky::THINKING_VERBS.sample : message.to_s
  ProgressHandle.new(
    owner: self,
    message: display,
    style: style,
    quiet_on_fast_finish: quiet_on_fast_finish
  ).start
end

#stop(clear_screen: false) ⇒ Object

Stop the UI controller. Keeps the screen by default so any final output (e.g. the "clacky -a " resume hint) survives in scrollback.



167
168
169
170
# File 'lib/clacky/ui2/ui_controller.rb', line 167

def stop(clear_screen: false)
  @running = false
  @layout.cleanup_screen(clear_screen: clear_screen)
end

#stop_fullscreen_refresh_threadObject

Stop the fullscreen refresh thread gracefully via flag + join.



1006
1007
1008
1009
1010
1011
1012
1013
1014
# File 'lib/clacky/ui2/ui_controller.rb', line 1006

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

#stream_thinking_progress(input_tokens:, output_tokens:) ⇒ Object

Stream-only update for the live thinking progress. Unlike show_progress(progress_type: "thinking", phase: "active"), this NEVER creates a new handle — if no thinking handle is currently alive (e.g. we're inside an idle-compression call_llm where only the quiet "Compressing..." handle is on the stack), the streamed token counts are silently dropped instead of spawning a primary spinner that would push the compression progress off-screen.



991
992
993
994
995
996
# File 'lib/clacky/ui2/ui_controller.rb', line 991

def stream_thinking_progress(input_tokens:, output_tokens:)
  @legacy_progress_handles ||= {}
  existing = @legacy_progress_handles["thinking"]
  return unless existing&.running?
  existing.update(metadata: { input_tokens: input_tokens, output_tokens: output_tokens })
end

#toggle_modeObject

Toggle permission mode between confirm_safes and auto_approve



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/clacky/ui2/ui_controller.rb', line 146

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)

  update_sessionbar
end

#unregister_progress(handle, final_frame:) ⇒ Object

Called by ProgressHandle#finish.



785
786
787
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
# File 'lib/clacky/ui2/ui_controller.rb', line 785

def unregister_progress(handle, final_frame:)
  @progress_mutex.synchronize do
    if @chore_nested&.delete(handle)
      # Folded handles own no entry; hand the chore line back to
      # whatever is still running underneath (or the bare label).
      fold_into_chore_line(@chore_nested.last)
      next
    end

    # A handle that was never stacked owns nothing here: restoring
    # "the new top" would duplicate what is legitimately on screen.
    next unless @progress_stack.include?(handle)

    if handle.entry_id
      if final_frame && !final_frame.to_s.strip.empty?
        update_entry(handle.entry_id, @renderer.render_progress(final_frame))
      else
        remove_entry(handle.entry_id)
      end
    end

    @progress_stack.delete(handle)

    # Restore the new top, if any: allocate a fresh entry and let it
    # resume rendering from where it left off.
    if (restored = @progress_stack.last)
      new_id = append_output_unlocked(render_for(restored))
      restored.__reattach_entry!(new_id)
    end

    # Recompute sessionbar status from whatever remains on the stack.
    # This handles: (a) empty stack → idle, (b) mixed stack (e.g. a
    # long-running quiet tool still active underneath) → working.
    recompute_sessionbar_status
  end
end

#update_permission_mode(mode) ⇒ Object



140
141
142
143
# File 'lib/clacky/ui2/ui_controller.rb', line 140

def update_permission_mode(mode)
  @config[:mode] = mode.to_s
  update_sessionbar
end

#update_sessionbar(tasks: nil, cost: nil, cost_source: nil, status: nil, latency: nil, session_id: nil) ⇒ Object

Update session bar with current stats

Parameters:

  • tasks (Integer) (defaults to: nil)

    Number of completed tasks (optional)

  • cost (Float) (defaults to: nil)

    Total cost (optional)

  • cost_source (Symbol, nil) (defaults to: nil)

    :api / :price / :default (optional)

  • status (String) (defaults to: nil)

    Workspace status ('idle' or 'working') (optional)

  • latency (Hash, nil) (defaults to: nil)

    Latency metrics; accepted but not displayed in the TUI.

  • session_id (String, nil) (defaults to: nil)

    Full session id; rendered as first 8 chars (parity with WebUI).



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/clacky/ui2/ui_controller.rb', line 118

def update_sessionbar(tasks: nil, cost: nil, cost_source: nil, status: nil, latency: nil, session_id: nil)
  @tasks_count = tasks if tasks
  @total_cost = cost if cost
  @session_id = session_id if session_id
  @input_area.update_sessionbar(
    session_id: @session_id,
    working_dir: @config[:working_dir],
    mode: @config[:mode],
    model: @config[:model],
    tasks: @tasks_count,
    cost: @total_cost,
    cost_source: cost_source,
    status: status
  )
  @layout.render_input
end

#update_todos(todos) ⇒ Object

Update todos display

Parameters:

  • todos (Array<Hash>)

    Array of todo items



312
313
314
# File 'lib/clacky/ui2/ui_controller.rb', line 312

def update_todos(todos)
  @layout.update_todos(todos)
end

#with_progress(message: nil, style: :primary, quiet_on_fast_finish: false) {|handle| ... } ⇒ Object

Run the given block with a progress indicator active. The handle is always finished in an ensure block, so exceptions (including Thread#raise) cannot leave the ticker or entry orphaned.

Yield Parameters:



702
703
704
705
706
707
708
709
710
711
712
713
# File 'lib/clacky/ui2/ui_controller.rb', line 702

def with_progress(message: nil, style: :primary, quiet_on_fast_finish: false)
  handle = start_progress(
    message: message,
    style: style,
    quiet_on_fast_finish: quiet_on_fast_finish
  )
  begin
    yield handle
  ensure
    handle.finish
  end
end