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
use anyhow::Result;
use chrono::Local;
use crossterm::event;
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use crate::models::{MessageRole, ModelConfig, StreamCallback};
use super::state::GenerationStatus;
use crate::tui::render::render_ui;
use crate::tui::App;
use crate::utils::FileSystemWatcher;
/// Import our specialized handlers
use super::action_handler;
use super::command_handler;
use super::event_handler::{handle_event, EventAction};
use super::stream_handler::{process_stream_chunks, StreamStatus};
/// Run the main application event loop
///
/// This function coordinates all the specialized handlers and manages
/// the lifecycle of the TUI application.
///
/// The loop performs these steps each iteration:
/// 1. Render the UI
/// 2. Poll for events (keyboard, mouse)
/// 3. Process streaming chunks from LLM
/// 4. Handle events and delegate to specialized handlers
/// 5. Check for file system changes
/// 6. Auto-scroll management
pub async fn run_app_loop(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
app: &mut App,
tx: mpsc::Sender<String>,
rx: &mut mpsc::Receiver<String>,
) -> Result<()> {
// Initialize file watcher for the current directory
let watcher = FileSystemWatcher::new(Path::new("."))?;
let mut last_refresh = std::time::Instant::now();
// Main event loop
loop {
// Get viewport height for proper scrolling
let viewport_height = terminal.size()?.height.saturating_sub(8); // 3 header + 3 input + 1 status + 1 margin
// Draw UI
terminal.draw(|f| render_ui(f, app))?;
// Check if we should transition from Sending to Thinking (after 1 second with no chunks)
if app.app_state.generation_status() == Some(GenerationStatus::Sending) {
if let Some(start_time) = app.app_state.generation_start_time() {
if start_time.elapsed().as_secs() >= 1 {
app.transition_to_thinking();
}
}
}
// Handle input events
if event::poll(std::time::Duration::from_millis(50))? {
let event = event::read()?;
// Use event_handler to process the event
match handle_event(app, event, viewport_height)? {
EventAction::Continue => {
// Continue normal loop
},
EventAction::Quit => {
break;
},
EventAction::SubmitMessage(input) => {
// Submit message to model
handle_message_submit(app, input, &tx, viewport_height).await;
},
EventAction::ExecuteCommand(command) => {
// Execute slash command
command_handler::handle_command(app, &command).await?;
},
}
}
// Process streaming responses
match process_stream_chunks(app, rx).await? {
StreamStatus::Streaming => {
// During streaming: content is buffered and NOT rendered (block streaming mode)
// Auto-scroll happens naturally via u16::MAX in render (if not user-scrolling)
},
StreamStatus::Complete { tool_calls } => {
// Stream complete: response is now rendered
// AGENT LOOP: Execute tool calls and continue until model stops
if !tool_calls.is_empty() {
run_agent_loop(app, tool_calls, &tx, rx, terminal).await?;
}
// Process any queued messages after generation completes
// This handles the case where user typed messages while model was generating
// and there were no tool calls to trigger the agent loop
'queue_loop: while app.operation_state.has_queued_message() {
if let Some(queued_msg) = app.operation_state.take_queued_message() {
// Submit the queued message as if user pressed Enter
handle_message_submit(app, queued_msg, &tx, viewport_height).await;
// Wait for this message's response to complete before sending next
loop {
// Draw UI while waiting
terminal.draw(|f| render_ui(f, app))?;
// Check for Esc or Ctrl+C to interrupt queued message processing
if event::poll(Duration::from_millis(10))? {
if let event::Event::Key(key) = event::read()? {
if key.kind == crossterm::event::KeyEventKind::Press {
match key.code {
crossterm::event::KeyCode::Esc => {
// Abort current generation
if let Some(abort) = app.abort_generation() {
abort.abort();
}
// Save partial response
if !app.current_response.is_empty() {
app.add_message(MessageRole::Assistant, app.current_response.clone());
app.current_response.clear();
}
// Clear remaining queued messages
let cleared = app.operation_state.queued_message_count();
while app.operation_state.take_queued_message().is_some() {}
if cleared > 0 {
app.set_status(format!("Interrupted - cleared {} queued message(s)", cleared));
} else {
app.set_status("Generation stopped");
}
break 'queue_loop;
},
crossterm::event::KeyCode::Char('c') if key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL) => {
// Ctrl+C: same as Esc
if let Some(abort) = app.abort_generation() {
abort.abort();
}
if !app.current_response.is_empty() {
app.add_message(MessageRole::Assistant, app.current_response.clone());
app.current_response.clear();
}
while app.operation_state.take_queued_message().is_some() {}
app.set_status("Interrupted");
break 'queue_loop;
},
_ => {
// Ignore other keys during queue processing
}
}
}
}
}
match process_stream_chunks(app, rx).await? {
StreamStatus::Streaming => {
// Continue processing
},
StreamStatus::Complete { tool_calls: new_tool_calls } => {
// If this response has tool calls, run agent loop
if !new_tool_calls.is_empty() {
run_agent_loop(app, new_tool_calls, &tx, rx, terminal).await?;
}
break; // Done with this queued message
},
StreamStatus::FeedbackComplete => {
break;
},
StreamStatus::Error(error) => {
app.display_error(&error.summary, &error.message);
break;
},
}
}
}
}
// Generate conversation title after first exchange (if not already generated)
if app.session_state.conversation_title.is_none() && app.session_state.messages.len() >= 2 {
app.generate_conversation_title().await;
}
},
StreamStatus::FeedbackComplete => {
// Feedback loop complete, nothing to do
},
StreamStatus::Error(_error) => {
// Error already handled by stream_handler (status message set)
},
}
// Check for external file system changes (throttled to once per second)
// Note: We don't maintain context anymore, but we keep the watcher for potential future use
if last_refresh.elapsed() >= std::time::Duration::from_secs(1) {
let _events = watcher.check_events();
last_refresh = std::time::Instant::now();
}
// Clear stale file reading status after 5 seconds
if app.operation_state.reading_file_status.is_some() && !app.app_state.is_generating() {
if let Some(timestamp) = app.status_state.status_timestamp {
if timestamp.elapsed() >= std::time::Duration::from_secs(5) {
app.operation_state.reading_file_status = None;
app.operation_state.pending_file_read = false;
app.status_state.status_timestamp = None;
}
}
}
// Check if app should quit
if !app.running {
break;
}
}
Ok(())
}
/// Handle message submission to the model
///
/// This spawns an async task to stream the model's response.
async fn handle_message_submit(
app: &mut App,
input: String,
tx: &mpsc::Sender<String>,
_viewport_height: u16,
) {
// Clear any stuck status messages when sending new message
app.operation_state.pending_file_read = false;
app.operation_state.reading_file_status = None;
// Add timestamp to message for temporal awareness
let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S %Z").to_string();
let timestamped_input = format!("[Sent at: {}]\n{}", timestamp, input);
// Take any attached images before adding message
let images = app.attachment_state.take_base64_data();
// Add user message to history with timestamp (and images if any)
app.add_message_with_images(MessageRole::User, timestamped_input, images);
// Build message history including the new message
let messages = app.build_managed_message_history(75_000, 4_000);
// Auto-scroll happens naturally via u16::MAX in render (if not user-scrolling)
app.current_response.clear();
// Save input to history and reset navigation
app.session_state.input_history.push_back(input.clone());
app.session_state.history_index = None;
app.session_state.history_buffer.clear();
// Persist to conversation if available
if let Some(ref mut conv) = app.session_state.current_conversation {
conv.add_to_input_history(input.clone());
if let Some(ref manager) = app.session_state.conversation_manager {
let _ = manager.save_conversation(conv);
}
}
// Process message asynchronously
let model = app.model_state.model.clone();
let tx_clone = tx.clone();
let tx_done = tx.clone();
let model_id = app.model_state.model_id.clone();
let thinking_enabled = app.model_state.is_thinking_active();
let handle = tokio::spawn(async move {
let mut config = ModelConfig::default();
config.model = model_id.clone();
config.thinking_enabled = thinking_enabled;
let callback: StreamCallback = Arc::new(move |chunk| {
let _ = tx_clone.try_send(chunk.to_string());
});
let model = model.write().await;
match model
.chat(&messages, &config, Some(callback))
.await
{
Ok(response) => {
// Send real token count from Ollama with [DONE] message
let tokens = response.usage.map(|u| u.completion_tokens).unwrap_or(0);
let _ = tx_done.send(format!("[DONE]:tokens={}", tokens)).await;
},
Err(e) => {
// Send structured error for rich UX display
let error_json = e.to_channel_message();
let _ = tx_done.send(format!("[ERROR_JSON]:{}", error_json)).await;
},
}
});
// Start generation state with abort handle
app.start_generation(handle.abort_handle());
}
/// Render the UI and check for Esc/Ctrl+C interruption (non-blocking).
/// Returns Ok(true) if the user wants to interrupt the agent loop.
fn render_and_check_interrupt(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
app: &mut App,
) -> Result<bool> {
terminal.draw(|f| render_ui(f, app))?;
if event::poll(Duration::from_millis(0))? {
if let event::Event::Key(key) = event::read()? {
if key.kind == crossterm::event::KeyEventKind::Press {
match key.code {
crossterm::event::KeyCode::Esc => {
if let Some(abort) = app.abort_generation() {
abort.abort();
}
if !app.current_response.is_empty() {
app.add_message(MessageRole::Assistant, app.current_response.clone());
app.current_response.clear();
}
app.set_status("Agent loop interrupted");
return Ok(true);
}
crossterm::event::KeyCode::Char('c')
if key.modifiers.contains(crossterm::event::KeyModifiers::CONTROL) =>
{
if let Some(abort) = app.abort_generation() {
abort.abort();
}
if !app.current_response.is_empty() {
app.add_message(MessageRole::Assistant, app.current_response.clone());
app.current_response.clear();
}
app.set_status("Agent loop interrupted");
return Ok(true);
}
_ => {}
}
}
}
}
Ok(false)
}
/// Run the agent loop for tool calling
///
/// This implements the proper agent loop pattern:
/// 1. Execute tool calls
/// 2. Add Tool messages for each result
/// 3. Call the model again
/// 4. Loop until no more tool_calls
///
/// Each completed step renders immediately to the TUI so the user
/// sees tool actions and model responses as they happen (block streaming).
///
/// This follows the Ollama API pattern documented at:
/// https://ollama.com/blog/tool-support
async fn run_agent_loop(
app: &mut App,
initial_tool_calls: Vec<crate::models::ToolCall>,
tx: &mpsc::Sender<String>,
rx: &mut mpsc::Receiver<String>,
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
) -> Result<()> {
let mut current_tool_calls = initial_tool_calls;
let mut iteration = 0;
while !current_tool_calls.is_empty() {
iteration += 1;
app.set_status(format!("Agent loop iteration {}", iteration));
// Render so user sees iteration status; check for Esc interrupt
if render_and_check_interrupt(terminal, app)? {
return Ok(());
}
// Check for queued message BEFORE executing tool calls
// This allows the user to intercept and redirect the agent
if let Some(queued_msg) = app.operation_state.take_queued_message() {
app.set_status("Processing queued message...");
// Add the queued message as a user message (with timestamp)
let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S %Z").to_string();
let timestamped_input = format!("[Sent at: {}]\n{}", timestamp, queued_msg);
app.add_message(MessageRole::User, timestamped_input);
// Save to input history
app.session_state.input_history.push_back(queued_msg);
// Clear current tool calls - the model will decide what to do next
// based on the new user message
current_tool_calls.clear();
// Build message history and call model with the new context
let messages = app.build_managed_message_history(75_000, 4_000);
app.current_response.clear();
let model = app.model_state.model.clone();
let tx_clone = tx.clone();
let tx_done = tx.clone();
let model_id = app.model_state.model_id.clone();
let thinking_enabled = app.model_state.is_thinking_active();
let handle = tokio::spawn(async move {
let mut config = ModelConfig::default();
config.model = model_id;
config.thinking_enabled = thinking_enabled;
let callback: StreamCallback = Arc::new(move |chunk| {
let _ = tx_clone.try_send(chunk.to_string());
});
let model = model.write().await;
match model
.chat(&messages, &config, Some(callback))
.await
{
Ok(response) => {
let tokens = response.usage.map(|u| u.completion_tokens).unwrap_or(0);
let _ = tx_done.send(format!("[DONE]:tokens={}", tokens)).await;
},
Err(e) => {
let error_json = e.to_channel_message();
let _ = tx_done.send(format!("[ERROR_JSON]:{}", error_json)).await;
},
}
});
app.start_generation(handle.abort_handle());
// Wait for the model response (render each tick for live status)
loop {
if render_and_check_interrupt(terminal, app)? {
return Ok(());
}
match process_stream_chunks(app, rx).await? {
StreamStatus::Streaming => {},
StreamStatus::Complete { tool_calls: new_tool_calls } => {
if !new_tool_calls.is_empty() {
current_tool_calls = new_tool_calls;
}
break;
},
StreamStatus::FeedbackComplete => {
return Ok(());
},
StreamStatus::Error(error) => {
app.display_error(&error.summary, &error.message);
return Ok(());
},
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
// Continue the loop with potentially new tool calls
continue;
}
// Execute tool calls and get results
let results = action_handler::execute_tool_calls_for_agent_loop(app, ¤t_tool_calls).await;
// Update the last assistant message to include tool_calls
// (This is needed for the API to understand the conversation flow)
if let Some(last_assistant) = app
.session_state
.messages
.iter_mut()
.rev()
.find(|m| matches!(m.role, MessageRole::Assistant))
{
last_assistant.tool_calls = Some(current_tool_calls.clone());
}
// Add Tool messages for each result
for result in &results {
app.add_tool_result(
result.tool_call_id.clone(),
result.tool_name.clone(),
result.content.clone(),
);
}
// Render to show completed tool actions immediately
app.set_status(format!(
"Iteration {} - {} tool(s) executed, calling model...",
iteration,
results.len()
));
if render_and_check_interrupt(terminal, app)? {
return Ok(());
}
// Note: Even if all tool calls failed, we continue the loop so the model
// can see the error messages and retry with a different approach.
// Call the model again with the updated message history
let messages = app.build_managed_message_history(75_000, 4_000);
app.current_response.clear();
let model = app.model_state.model.clone();
let tx_clone = tx.clone();
let tx_done = tx.clone();
let model_id = app.model_state.model_id.clone();
let thinking_enabled = app.model_state.is_thinking_active();
let handle = tokio::spawn(async move {
let mut config = ModelConfig::default();
config.model = model_id;
config.thinking_enabled = thinking_enabled;
let callback: StreamCallback = Arc::new(move |chunk| {
let _ = tx_clone.try_send(chunk.to_string());
});
let model = model.write().await;
match model
.chat(&messages, &config, Some(callback))
.await
{
Ok(response) => {
// Send real token count from Ollama with [DONE] message
let tokens = response.usage.map(|u| u.completion_tokens).unwrap_or(0);
let _ = tx_done.send(format!("[DONE]:tokens={}", tokens)).await;
},
Err(e) => {
let error_json = e.to_channel_message();
let _ = tx_done.send(format!("[ERROR_JSON]:{}", error_json)).await;
},
}
});
app.start_generation(handle.abort_handle());
// Wait for the model response by processing stream chunks until Complete
// Render on each tick so status bar updates and Esc works
loop {
// Render to show streaming progress (timer, tokens, status)
if render_and_check_interrupt(terminal, app)? {
return Ok(());
}
match process_stream_chunks(app, rx).await? {
StreamStatus::Streaming => {
// Continue processing
},
StreamStatus::Complete { tool_calls: new_tool_calls } => {
// Got a new response - check if there are more tool calls
if new_tool_calls.is_empty() {
// No more tool calls - agent loop complete
app.set_status(format!("Agent loop complete after {} iterations", iteration));
return Ok(());
} else {
// More tool calls - continue the loop
current_tool_calls = new_tool_calls;
break; // Break inner loop to continue outer agent loop
}
},
StreamStatus::FeedbackComplete => {
// Feedback complete - exit loop
return Ok(());
},
StreamStatus::Error(error) => {
// Error occurred - display and exit
app.display_error(&error.summary, &error.message);
return Ok(());
},
}
// Sleep briefly to avoid busy-wait spin loop
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
Ok(())
}