1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
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
mod agent_events;
mod key_handler;
mod popup_handler;
use anyhow::Result;
use tokio::sync::mpsc;
use crate::agent::r#loop::AgentEvent;
use crate::app::App;
use crate::app::utils::{build_system_prompt, build_system_prompt_with_agent, popup_max_scroll};
use crate::tui::event::{self, AppEvent};
use crate::tui::render;
use crate::tui::terminal::Tui;
/// Minimum render interval during active user interaction (~60 fps).
const FRAME_BUDGET_INTERACTIVE: std::time::Duration = std::time::Duration::from_millis(16);
/// Minimum render interval while agent is streaming (~30 fps).
/// Reduces CPU load during long generations without visible quality loss --
/// streaming text arrives at ~10-100 tokens/sec, well within 30 fps budget.
const FRAME_BUDGET_STREAMING: std::time::Duration = std::time::Duration::from_millis(33);
/// Max agent events to drain per frame in single-agent mode.
const AGENT_BATCH_LIMIT: usize = 128;
/// Max agent events to drain per frame in swarm/hive mode (more agents -> more events).
const AGENT_BATCH_LIMIT_SWARM: usize = 256;
/// Spinner/animation tick interval -- independent of event queue.
const TICK_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);
/// Max scroll lines applied per frame (prevents runaway after input freeze).
const MAX_SCROLL_DELTA: u16 = 30;
/// Signal from extracted handler methods back to the main loop.
pub(super) enum LoopControl {
/// Equivalent to `continue` in the main loop.
Continue,
/// Equivalent to `break` in the main loop.
Break,
/// Normal fall-through — no special control flow needed.
Proceed,
}
impl App {
pub(super) async fn main_loop(
&mut self,
tui: &mut Tui,
event_tx: &mpsc::UnboundedSender<AgentEvent>,
event_rx: &mut mpsc::UnboundedReceiver<AgentEvent>,
key_rx: &mut mpsc::Receiver<event::AppEvent>,
) -> Result<()> {
let mut last_render = std::time::Instant::now();
let mut last_tick = std::time::Instant::now();
let mut needs_render = true; // render on first iteration
loop {
// -- Time-based animation tick --
// Runs regardless of event queue volume so animations never freeze
// (Tick events from select! can be starved when agent_rx is always full).
if last_tick.elapsed() >= TICK_INTERVAL {
self.state.tick_spinner();
if self.state.agent_busy
&& let Some(since) = self.agent_busy_since
{
self.state.elapsed_secs = since.elapsed().as_secs();
}
last_tick = std::time::Instant::now();
needs_render = true;
}
// -- Background repo map: apply when build completes --
if let Some(ref mut rx) = self.repo_map_receiver
&& let Ok(new_repo_map) = rx.try_recv()
{
self.repo_map = new_repo_map;
self.repo_map_receiver = None;
// Rebuild system prompt now that code context is available
if let Some(ref mut ctx) = self.context {
let prompt = build_system_prompt(&self.repo_map, None);
ctx.update_system_prompt(prompt);
}
tracing::info!(
"Repo map ready: {} files, {} symbols",
self.repo_map.file_count(),
self.repo_map.symbol_count(),
);
needs_render = true;
}
// -- Background repo map incremental rebuild (triggered at submit) --
// Spawned by submit_message() so the UI renders immediately without
// blocking on tree-sitter. Once ready: update repo_map, refresh the
// system prompt, then fire any pending agent dispatch.
// -- Background git diff (sidebar file click) --
if let Some((ref short, ref mut rx)) = self.pending_diff_rx
&& let Ok(result) = rx.try_recv()
{
let short = short.clone();
self.pending_diff_rx = None;
if let Some(diff) = result {
self.state.popup = Some(crate::tui::state::PopupState {
title: format!(" {short} "),
content: diff,
scroll: 0,
kind: crate::tui::state::PopupKind::Info,
saved_theme: None,
select_prefix: None,
search: String::new(),
});
}
self.state.status_msg = "Ready".to_string();
needs_render = true;
}
if let Some(ref mut rx) = self.repo_map_rebuild_rx
&& let Ok(rebuilt_map) = rx.try_recv()
{
self.repo_map = rebuilt_map;
self.repo_map_rebuild_rx = None;
let agent_name = self.state.agent_mode.as_str();
let agent_def = self.config.agents.iter().find(|a| a.name == agent_name);
let agent_behavior = agent_def
.map(|a| a.system_prompt.clone())
.filter(|s| !s.is_empty());
let soul_content = if crate::agent::soul::is_enabled(&self.config, agent_def) {
crate::agent::soul::load(&self.config.collet_home, agent_name).or_else(|| {
crate::agent::soul::load(
&self.config.collet_home,
crate::agent::soul::GLOBAL_SOUL,
)
})
} else {
None
};
if let Some(ref mut ctx) = self.context {
ctx.update_system_prompt(build_system_prompt_with_agent(
&self.repo_map,
None,
agent_behavior.as_deref(),
soul_content.as_deref(),
));
}
let top_symbol_names: Vec<&str> = self
.repo_map
.all_symbols()
.flat_map(|(_, syms)| syms.iter().map(|s| s.name.as_str()))
.take(5)
.collect();
tracing::debug!(
files = self.repo_map.file_count(),
symbols = self.repo_map.symbol_count(),
sample = ?top_symbol_names,
"Repo map rebuilt"
);
// Fire any agent dispatch that was waiting for this rebuild.
if let Some(dispatch) = self.pending_dispatch.take() {
self.fire_pending_dispatch(dispatch);
}
needs_render = true;
}
// -- Smooth scroll: step scroll_offset toward target --
if self.state.scroll_offset != self.scroll_target {
// Clamp scroll_target to a sane upper bound to prevent the
// output area from scrolling past all content. u16::MAX / 2
// is more than enough for any realistic terminal height.
self.scroll_target = self.scroll_target.min(u16::MAX / 2);
let cur = self.state.scroll_offset as i32;
let tgt = self.scroll_target as i32;
let diff = tgt - cur;
// Step size: fast for large gaps, 1 for small gaps (easing)
let step = if diff.abs() > 12 {
diff / 3
} else {
diff.signum()
};
self.state.scroll_offset = (cur + step).max(0) as u16;
needs_render = true;
}
// Only render when state changed AND frame budget elapsed.
// Drop to 30 fps during agent streaming to halve render CPU load.
// Snap back to 60 fps the moment the user interacts (input event sets needs_render
// and the budget check below uses the interactive constant).
let frame_budget = if self.state.agent_busy {
FRAME_BUDGET_STREAMING
} else {
FRAME_BUDGET_INTERACTIVE
};
if needs_render && last_render.elapsed() >= frame_budget {
let wd = self.working_dir.clone();
tui.draw(|frame| render::render(frame, &self.state, &wd))?;
last_render = std::time::Instant::now();
needs_render = false;
}
let app_event = event::next_event(key_rx, event_rx).await?;
// Drain any pending approval requests from the agent loop.
// The agent is blocked waiting for a response, so max ~16ms latency is fine.
if self.state.popup.is_none()
&& let Some(rx) = &mut self.approval_req_rx
&& let Ok(req) = rx.try_recv()
{
self.pending_approval_tx = Some(req.response_tx);
self.state.popup = Some(crate::tui::state::PopupState {
title: "Tool Approval".to_string(),
content: String::new(),
scroll: 0,
kind: crate::tui::state::PopupKind::ToolApproval {
tool_name: req.tool_name,
tool_args: req.tool_args,
selected: 0,
},
saved_theme: None,
select_prefix: None,
search: String::new(),
});
needs_render = true;
}
// Track whether this was an input event for immediate render.
let is_input_event = matches!(app_event, AppEvent::Key(_) | AppEvent::Mouse(_));
match app_event {
AppEvent::Key(key) => {
// Popup intercepts most keys when open
if self.state.popup.is_some() {
self.handle_popup_key(key, event_tx, tui).await;
continue;
}
match self.handle_normal_key(key, event_tx) {
LoopControl::Continue => continue,
LoopControl::Break => break,
LoopControl::Proceed => {}
}
}
AppEvent::Mouse(mouse) => {
match event::interpret_mouse(mouse) {
event::MouseAction::ScrollUp => {
// If a scrollable popup is open and its content overflows, scroll it.
let th = tui.size().map(|s| s.height).unwrap_or(24);
let popup_scrolled = if let Some(ref mut p) = self.state.popup {
let max = popup_max_scroll(p, th);
if max > 0 {
p.scroll = p.scroll.saturating_sub(1);
true
} else {
false
}
} else {
false
};
if !popup_scrolled {
// Drain consecutive scroll events to batch into one step.
// Capped to MAX_SCROLL_DELTA to prevent runaway after input freeze.
let mut delta: u16 = 3;
while delta < MAX_SCROLL_DELTA {
match key_rx.try_recv() {
Ok(event::AppEvent::Mouse(m)) => {
match event::interpret_mouse(m) {
event::MouseAction::ScrollUp => delta += 3,
event::MouseAction::ScrollDown => {
delta = delta.saturating_sub(3);
break;
}
_ => break,
}
}
_ => break,
}
}
self.scroll_target = self.scroll_target.saturating_add(delta);
}
}
event::MouseAction::ScrollDown => {
let th = tui.size().map(|s| s.height).unwrap_or(24);
let popup_scrolled = if let Some(ref mut p) = self.state.popup {
let max = popup_max_scroll(p, th);
if max > 0 {
p.scroll = p.scroll.saturating_add(1).min(max);
true
} else {
false
}
} else {
false
};
if !popup_scrolled {
let mut delta: u16 = 3;
while delta < MAX_SCROLL_DELTA {
match key_rx.try_recv() {
Ok(event::AppEvent::Mouse(m)) => {
match event::interpret_mouse(m) {
event::MouseAction::ScrollDown => delta += 3,
event::MouseAction::ScrollUp => {
delta = delta.saturating_sub(3);
break;
}
_ => break,
}
}
_ => break,
}
}
self.scroll_target = self.scroll_target.saturating_sub(delta);
}
}
event::MouseAction::Click { column, row } => {
if self.state.popup.is_none() {
let sidebar = *self.state.last_sidebar_area.borrow();
let on_sidebar =
column >= sidebar.x && column < sidebar.x + sidebar.width;
// Check if click is on a swarm agent entry
let agents_start = self.state.sidebar_swarm_agents_start_row.get();
let files_start_peek = self.state.sidebar_files_start_row.get();
let on_swarm_agent = on_sidebar
&& agents_start > 0
&& row >= agents_start
&& (files_start_peek == 0 || row < files_start_peek)
&& self.state.swarm_status.is_some();
// Check if click is on a Changed Files entry in sidebar
// (on_swarm_agent is checked first in the if-else chain,
// so no need to exclude the swarm range here)
let on_sidebar_file =
on_sidebar && files_start_peek > 0 && row >= files_start_peek;
if on_swarm_agent {
// Each agent occupies 1-2 rows (name row + optional preview row).
// Determine which agent was clicked.
let clicked_agent =
self.state.swarm_status.as_ref().and_then(|hive| {
let mut cursor = agents_start;
for entry in &hive.agents {
let has_preview = !entry.task_preview.is_empty();
let entry_rows =
if has_preview { 2u16 } else { 1u16 };
if row >= cursor && row < cursor + entry_rows {
return Some((
entry.agent_id.clone(),
entry.status.clone(),
entry.output.clone(),
));
}
cursor += entry_rows;
if self.state.debug_mode
&& (entry.input_tokens > 0
|| entry.output_tokens > 0)
{
cursor += 1;
}
}
None
});
if let Some((agent_id, status, output)) = clicked_agent {
match status {
crate::tui::state::SwarmAgentStatus::Running
| crate::tui::state::SwarmAgentStatus::Paused => {
// Attach to running/paused worker
self.state.attach_worker(&agent_id);
}
_ => {
// Completed worker -- show popup with output
if !output.is_empty() {
self.state.popup =
Some(crate::tui::state::PopupState {
title: format!(
" [{}] output ",
agent_id
),
content: output,
scroll: 0,
kind:
crate::tui::state::PopupKind::Info,
saved_theme: None,
select_prefix: None,
search: String::new(),
});
}
}
}
}
} else if on_sidebar_file {
let idx = (row - files_start_peek) as usize
+ self.state.sidebar_scroll as usize;
if let Some(entry) = self.state.changed_files.get(idx) {
let path = entry.path.clone();
// Spawn git diff in a background thread to avoid
// blocking the TUI event loop (100-500ms on large repos).
let working_dir = self.working_dir.clone();
let (tx, rx) = tokio::sync::oneshot::channel();
std::thread::spawn(move || {
let result = run_git_diff_for_file(&path, &working_dir);
let _ = tx.send(result);
});
let short = std::path::Path::new(&entry.path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&entry.path)
.to_string();
self.pending_diff_rx = Some((short, rx));
self.state.status_msg = "Loading diff…".to_string();
}
} else {
self.handle_output_click(column, row);
}
}
}
event::MouseAction::None => {}
}
}
AppEvent::Agent(agent_event) => {
self.handle_agent_event_batch(*agent_event, event_tx, event_rx)
.await;
}
AppEvent::Paste(text) => {
// Allow paste even during agent_busy (user can queue input).
const PASTE_ABBREV_THRESHOLD: usize = 200;
let insert_pos = self.state.cursor.min(self.state.input.len());
// Walk backwards to the nearest valid char boundary instead
// of jumping to end (which would confuse IME/CJK users).
let safe_pos = {
let mut p = insert_pos;
while p > 0 && !self.state.input.is_char_boundary(p) {
p -= 1;
}
p
};
if text.len() > PASTE_ABBREV_THRESHOLD {
// Large paste: show abbreviated preview, store full text
let line_count = text.lines().count();
let char_count = text.chars().count();
let abbrev = format!("[Pasted {char_count} chars {line_count} lines]");
// Store the full content: prefix + pasted text + suffix
let mut full = self.state.input[..safe_pos].to_string();
full.push_str(&text);
full.push_str(&self.state.input[safe_pos..]);
self.state.paste_buffer = Some(full);
// Display abbreviated version
self.state.input.insert_str(safe_pos, &abbrev);
self.state.cursor = safe_pos + abbrev.len();
} else {
// Small paste: insert directly
self.state.paste_buffer = None;
self.state.input.insert_str(safe_pos, &text);
self.state.cursor = safe_pos + text.len();
}
// Check if there is also an image on the clipboard and
// attach it alongside the text so the LLM can see both.
if let Ok(mut cb) = crate::clipboard::Clipboard::new() {
// has_image() is a quick pre-check before the heavier get_image().
if cb.has_image() {
if let Ok(Some(img)) =
cb.get_image() as anyhow::Result<Option<crate::api::ImageData>>
{
self.state.add_pending_image(img);
}
} else if text.is_empty() {
// Fallback: if the paste event carried no text, attempt a
// clipboard text read directly (e.g. from a bracketed-paste miss).
if let Ok(Some(cb_text)) = cb.get_text()
&& !cb_text.is_empty()
{
self.state.input.push_str(&cb_text);
self.state.cursor = self.state.input.len();
}
}
}
}
AppEvent::Tick => {
// Spinner and elapsed_secs are now driven by the time-based
// tick at the top of the loop (immune to agent_rx starvation).
// Update debug monitor metrics (preserve perf fields set by PerformanceUpdate)
if let Some(ref mut collector) = self.metrics_collector {
let metrics = collector.sample();
let stats = &self.state.token_stats;
let dm = &mut self.state.debug_monitor;
dm.memory_bytes = metrics.rss_bytes;
dm.cpu_percent = metrics.cpu_percent;
dm.input_tokens = stats.prompt_tokens;
dm.output_tokens = stats.completion_tokens;
dm.total_tool_calls = self.state.tool_log.len() as u32;
dm.total_api_calls = stats.api_calls;
dm.active_agents = {
let swarm_running = self
.state
.swarm_status
.as_ref()
.map(|h| {
h.agents
.iter()
.filter(|a| {
matches!(
a.status,
crate::tui::state::SwarmAgentStatus::Running
)
})
.count()
})
.unwrap_or(0);
(if self.state.agent_busy { 1 } else { 0 }) + swarm_running
};
// Measure MCP/LSP child process memory
dm.mcp_memory_bytes = self
.mcp_pids
.iter()
.map(|&pid| crate::util::process_metrics::child_rss_bytes(pid))
.sum();
let lsp_pids = self.lsp_manager.cached_child_pids();
dm.lsp_memory_bytes = lsp_pids
.iter()
.map(|&pid| crate::util::process_metrics::child_rss_bytes(pid))
.sum();
}
// Auto-reset esc_pending warning after 3-second timeout
if self.esc_pending {
let expired = self
.esc_pending_at
.map(|t| t.elapsed().as_secs() > 3)
.unwrap_or(true);
if expired {
self.esc_pending = false;
self.esc_pending_at = None;
if self.state.agent_busy {
self.state.status_msg = "Running...".to_string();
} else {
self.state.status_msg.clear();
}
}
}
}
}
// Mark that state changed and needs re-render.
needs_render = true;
// Input events force immediate render for responsiveness.
if is_input_event {
last_render = std::time::Instant::now() - FRAME_BUDGET_INTERACTIVE;
}
if self.state.should_quit {
break;
}
}
Ok(())
}
}
/// Run `git diff HEAD -- <path>` and return the output as a String.
/// Falls back to `git diff --cached` for staged-only changes, then to a short message.
fn run_git_diff_for_file(path: &str, working_dir: &str) -> Option<String> {
// Try unstaged changes first
if let Ok(out) = std::process::Command::new("git")
.args(["diff", "HEAD", "--", path])
.current_dir(working_dir)
.output()
{
let text = String::from_utf8_lossy(&out.stdout).into_owned();
if !text.trim().is_empty() {
return Some(text);
}
}
// Staged (cached) changes
if let Ok(out) = std::process::Command::new("git")
.args(["diff", "--cached", "--", path])
.current_dir(working_dir)
.output()
{
let text = String::from_utf8_lossy(&out.stdout).into_owned();
if !text.trim().is_empty() {
return Some(text);
}
}
Some(format!("No diff available for {path}"))
}