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
use std::io::Stdout;
use std::time::{Duration, Instant};
use anyhow::Result;
use ratatui::{
backend::CrosstermBackend,
crossterm::event::{self, Event, MouseEvent, MouseEventKind},
Terminal,
};
use matrixcode_core::{AgentEvent, cancel::CancellationToken};
use ratatui::crossterm::event::MouseButton;
use crate::types::{Activity, ApproveMode, Role, Message};
use crate::utils::extract_by_visual_col;
use crate::ANIM_MS;
pub struct TuiApp {
pub(crate) activity: Activity,
pub(crate) activity_detail: String,
pub(crate) messages: Vec<Message>,
pub(crate) thinking: String,
pub(crate) streaming: String,
pub(crate) input: String,
pub(crate) model: String,
// Token stats
pub(crate) tokens_in: u64,
pub(crate) tokens_out: u64,
pub(crate) session_total_out: u64,
pub(crate) current_request_tokens: u64, // Tokens for current request (real-time)
pub(crate) cache_read: u64,
pub(crate) cache_created: u64,
pub(crate) context_size: u64,
// Debug stats
pub(crate) api_calls: u64,
pub(crate) compressions: u64,
pub(crate) memory_saves: u64,
pub(crate) tool_calls: u64,
// Timing
pub(crate) request_start: Option<Instant>,
// UI state
pub(crate) frame: usize,
pub(crate) last_anim: Instant,
pub(crate) show_welcome: bool,
pub(crate) exit: bool,
// Input cursor position (character index in input string)
pub(crate) cursor_pos: usize,
// Input history (Up/Down arrow navigation)
pub(crate) input_history: Vec<String>,
pub(crate) history_index: Option<usize>, // None = not browsing history
pub(crate) history_draft: String, // Saves current input when entering history mode
// Scroll state
pub(crate) scroll_offset: u16,
pub(crate) auto_scroll: bool,
pub(crate) max_scroll: std::cell::Cell<u16>,
// Thinking display state
pub(crate) thinking_collapsed: bool,
// Approval mode
pub(crate) approve_mode: ApproveMode,
// Shared approve mode atomic - directly updates agent's mode in real-time
pub(crate) shared_approve_mode: Option<std::sync::Arc<std::sync::atomic::AtomicU8>>,
// Ask tool channel
pub(crate) ask_tx: Option<tokio::sync::mpsc::Sender<String>>,
pub(crate) waiting_for_ask: bool,
// Channels
pub(crate) tx: tokio::sync::mpsc::Sender<String>,
pub(crate) rx: tokio::sync::mpsc::Receiver<AgentEvent>,
pub(crate) cancel: CancellationToken,
// Message queue for pending inputs while AI is processing
pub(crate) pending_messages: Vec<String>,
// Loop task state
pub(crate) loop_task: Option<LoopTask>,
// Cron tasks state
pub(crate) cron_tasks: Vec<CronTask>,
// Selection state
pub(crate) selection: Option<Selection>,
pub(crate) selecting: bool, // True while mouse dragging
pub(crate) msg_area_top: std::cell::Cell<u16>, // Messages area top Y (computed in draw)
// Debug mode
pub(crate) debug_mode: bool,
}
/// Text selection in messages area
#[derive(Clone, Copy, Debug)]
pub struct Selection {
pub start_line: usize,
pub start_col: usize,
pub end_line: usize,
pub end_col: usize,
}
impl Selection {
pub fn new(start_line: usize, start_col: usize) -> Self {
Self {
start_line,
start_col,
end_line: start_line,
end_col: start_col,
}
}
pub fn extend_to(&mut self, line: usize, col: usize) {
self.end_line = line;
self.end_col = col;
}
#[allow(dead_code)]
pub fn is_empty(&self) -> bool {
self.start_line == self.end_line && self.start_col == self.end_col
}
pub fn normalized(&self) -> Self {
// Normalize so start <= end
if self.start_line > self.end_line ||
(self.start_line == self.end_line && self.start_col > self.end_col) {
Self {
start_line: self.end_line,
start_col: self.end_col,
end_line: self.start_line,
end_col: self.start_col,
}
} else {
*self
}
}
#[allow(dead_code)]
pub fn contains(&self, line: usize, col: usize) -> bool {
let norm = self.normalized();
if line < norm.start_line || line > norm.end_line {
return false;
}
if line == norm.start_line && line == norm.end_line {
return col >= norm.start_col && col <= norm.end_col;
}
if line == norm.start_line {
return col >= norm.start_col;
}
if line == norm.end_line {
return col <= norm.end_col;
}
true // Middle line
}
}
/// Loop task - repeatedly send message
#[derive(Clone)]
pub struct LoopTask {
pub message: String,
pub interval_secs: u64,
pub count: u64,
pub max_count: Option<u64>,
pub cancel_token: CancellationToken,
}
/// Cron task - scheduled message sending
#[derive(Clone)]
pub struct CronTask {
pub id: usize,
pub message: String,
pub minute_interval: u64, // Simplified: run every N minutes
#[allow(dead_code)]
pub next_run: Instant, // For future use: precise scheduling
pub cancel_token: CancellationToken,
}
impl TuiApp {
pub fn new(
tx: tokio::sync::mpsc::Sender<String>,
rx: tokio::sync::mpsc::Receiver<AgentEvent>,
cancel: CancellationToken,
) -> Self {
Self {
activity: Activity::Idle,
activity_detail: String::new(),
messages: Vec::new(),
thinking: String::new(),
streaming: String::new(),
input: String::new(),
model: "claude-sonnet-4".into(),
tokens_in: 0,
tokens_out: 0,
session_total_out: 0,
current_request_tokens: 0,
cache_read: 0,
cache_created: 0,
context_size: 200_000,
api_calls: 0,
compressions: 0,
memory_saves: 0,
tool_calls: 0,
request_start: None,
frame: 0,
last_anim: Instant::now(),
show_welcome: true,
exit: false,
cursor_pos: 0,
input_history: Vec::new(),
history_index: None,
history_draft: String::new(),
scroll_offset: 0,
auto_scroll: true,
max_scroll: std::cell::Cell::new(0),
thinking_collapsed: false, // Default: expanded
approve_mode: ApproveMode::Ask,
shared_approve_mode: None,
ask_tx: None,
waiting_for_ask: false,
tx, rx, cancel,
pending_messages: Vec::new(),
loop_task: None,
cron_tasks: Vec::new(),
selection: None,
selecting: false,
msg_area_top: std::cell::Cell::new(0),
debug_mode: false,
}
}
pub fn with_ask_channel(mut self, ask_tx: tokio::sync::mpsc::Sender<String>) -> Self {
self.ask_tx = Some(ask_tx);
self
}
/// Set shared approve mode atomic for real-time mode switching during agent execution.
pub fn with_shared_approve_mode(mut self, shared: std::sync::Arc<std::sync::atomic::AtomicU8>) -> Self {
self.shared_approve_mode = Some(shared);
self
}
pub fn with_config(mut self, model: &str, _think: bool, _max_tokens: u32, context_size: Option<u64>) -> Self {
self.model = model.to_string();
self.context_size = context_size.unwrap_or_else(|| {
let m = model.to_ascii_lowercase();
if m.contains("1m") || m.contains("opus-4-7") {
1_000_000
} else if m.contains("claude-3") || m.contains("claude-4") || m.contains("claude-sonnet") {
200_000
} else {
128_000
}
});
self
}
pub fn load_messages(&mut self, core_messages: Vec<matrixcode_core::Message>) {
for msg in core_messages {
// Handle different content block types separately
match &msg.content {
matrixcode_core::MessageContent::Text(t) => {
if t.is_empty() { continue; }
let role = match msg.role {
matrixcode_core::Role::User => Role::User,
matrixcode_core::Role::Assistant => Role::Assistant,
matrixcode_core::Role::System => Role::System,
matrixcode_core::Role::Tool => Role::Tool { name: "tool".into(), is_error: false },
};
// Restore input history from user messages
if role == Role::User && !t.starts_with('/')
&& self.input_history.last().map(|s| s.as_str()) != Some(t) {
self.input_history.push(t.clone());
}
self.messages.push(Message { role, content: t.clone() });
}
matrixcode_core::MessageContent::Blocks(blocks) => {
// Process each block separately to maintain proper message types
for b in blocks {
match b {
matrixcode_core::ContentBlock::Text { text } => {
if text.is_empty() { continue; }
let role = match msg.role {
matrixcode_core::Role::User => Role::User,
matrixcode_core::Role::Assistant => Role::Assistant,
matrixcode_core::Role::System => Role::System,
matrixcode_core::Role::Tool => Role::Tool { name: "tool".into(), is_error: false },
};
// Restore input history from user messages
if role == Role::User && !text.starts_with('/')
&& self.input_history.last().map(|s| s.as_str()) != Some(text) {
self.input_history.push(text.clone());
}
self.messages.push(Message { role, content: text.clone() });
}
matrixcode_core::ContentBlock::Thinking { thinking, .. } => {
if thinking.is_empty() { continue; }
// Create separate Thinking message for proper rendering
self.messages.push(Message { role: Role::Thinking, content: thinking.clone() });
}
matrixcode_core::ContentBlock::ToolUse { name: _, .. } => {
// Skip tool_use blocks - metadata only
}
matrixcode_core::ContentBlock::ToolResult { content, tool_use_id, .. } => {
if content.is_empty() { continue; }
// Try to determine if this is an error from content
let is_error = content.contains("error") || content.contains("failed") || content.contains("Error");
self.messages.push(Message {
role: Role::Tool {
name: if tool_use_id.starts_with("bash") { "bash".into() } else { tool_use_id.clone() },
is_error
},
content: content.clone()
});
}
_ => {}
}
}
}
}
}
if !self.messages.is_empty() {
self.show_welcome = false;
}
}
/// Get selected text from messages
/// Simplified: returns raw message content for the selected range
/// Maps rendered line numbers to original message content
pub(crate) fn get_selected_text(&self, selection: Selection) -> String {
let norm = selection.normalized();
// Build a mapping from rendered line index to message content
// This matches the rendering logic in draw_messages
let mut line_to_content: Vec<(usize, String)> = Vec::new(); // (message_idx, line_content)
let mut rendered_lines: Vec<String> = Vec::new();
// Welcome message lines (7 MATRIX lines + 1 subtitle + 1 empty)
if self.show_welcome && self.messages.is_empty() {
// MATRIX ASCII art lines (user wants to copy these)
rendered_lines.push(" █ █ █ ███████ ██████ ███ █ █ ".into());
rendered_lines.push(" ██ ██ █ █ █ █ █ █ █ █ ".into());
rendered_lines.push(" █ █ █ █ █ █ █ █ █ █ █ █ ".into());
rendered_lines.push(" █ █ █ █ █ █ ██████ █ █ ".into());
rendered_lines.push(" █ █ ███████ █ █ █ █ █ █ ".into());
rendered_lines.push(" █ █ █ █ █ █ █ █ █ █ ".into());
rendered_lines.push(" █ █ █ █ █ █ █ ███ █ █ ".into());
rendered_lines.push(" AI coding assistant | /help for commands".into());
rendered_lines.push(String::new());
}
// Process messages - simplified format matching actual rendering
for (msg_idx, msg) in self.messages.iter().enumerate() {
match &msg.role {
Role::User => {
// User: │ prefix for each content line
for line in msg.content.lines() {
rendered_lines.push(format!("│ {}", line));
line_to_content.push((msg_idx, line.to_string()));
}
rendered_lines.push(String::new());
}
Role::Assistant => {
// Assistant: ── separator + content lines
rendered_lines.push(" ──".into());
for line in msg.content.lines() {
rendered_lines.push(format!(" {}", line));
line_to_content.push((msg_idx, line.to_string()));
}
rendered_lines.push(String::new());
}
Role::Thinking => {
// Thinking: 💭 prefix
rendered_lines.push(" 💭 ▼ Thinking".into());
for line in msg.content.lines() {
rendered_lines.push(format!(" {}", line));
line_to_content.push((msg_idx, line.to_string()));
}
}
Role::Tool { name, .. } => {
// Tool: simplified header + content
rendered_lines.push(format!(" {} →", name));
for line in msg.content.lines() {
rendered_lines.push(format!(" {}", line));
line_to_content.push((msg_idx, line.to_string()));
}
rendered_lines.push(String::new());
}
Role::System => {
// System: ⚡ prefix or just content
if msg.content.contains("APPROVAL") {
for line in msg.content.lines() {
rendered_lines.push(format!(" ⚡ {}", line));
}
} else {
for line in msg.content.lines() {
rendered_lines.push(format!(" {}", line));
}
}
rendered_lines.push(String::new());
}
Role::Ask => {
// Ask: full content with borders
for line in msg.content.lines() {
rendered_lines.push(line.to_string());
line_to_content.push((msg_idx, line.to_string()));
}
rendered_lines.push(String::new());
}
}
}
// Extract selected range
let mut result = String::new();
for i in norm.start_line..=norm.end_line {
if let Some(line) = rendered_lines.get(i) {
let (start_col, end_col) = if i == norm.start_line && i == norm.end_line {
(norm.start_col, norm.end_col)
} else if i == norm.start_line {
(norm.start_col, usize::MAX)
} else if i == norm.end_line {
(0, norm.end_col)
} else {
(0, usize::MAX)
};
// Extract substring from visual column position
let extracted = extract_by_visual_col(line, start_col, end_col);
result.push_str(&extracted);
if i != norm.end_line {
result.push('\n');
}
}
}
result
}
pub fn run(&mut self, term: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
loop {
// Animation frame - cycle through 10 frames for spinner
if self.last_anim.elapsed().as_millis() >= ANIM_MS as u128 {
self.frame = (self.frame + 1) % 10;
self.last_anim = Instant::now();
}
term.draw(|f| self.draw(f))?;
// Handle events
if event::poll(Duration::from_millis(16))? {
match event::read()? {
Event::Key(k) => self.on_key(k),
Event::Mouse(m) => self.on_mouse(m, self.msg_area_top.get()),
Event::Paste(text) => self.on_paste(&text),
_ => {}
}
}
// Process agent events
while let Ok(e) = self.rx.try_recv() {
self.on_event(e);
}
if self.exit { break; }
}
Ok(())
}
fn on_mouse(&mut self, m: MouseEvent, msg_area_y: u16) {
match m.kind {
MouseEventKind::ScrollUp => {
// Scroll up = view earlier content = decrease offset
// ratatui scroll(offset) skips first N lines, so:
// - scroll_offset=0 shows top, scroll_offset=max shows bottom
// - scroll up (earlier) = decrease offset
if self.auto_scroll {
self.auto_scroll = false;
// We need to start from bottom, then scroll up
// Use max_scroll (will be updated in draw) or a large value
self.scroll_offset = self.max_scroll.get().max(50);
}
self.scroll_offset = self.scroll_offset.saturating_sub(3);
self.selection = None; // Clear selection on scroll
}
MouseEventKind::ScrollDown => {
// Scroll down = view newer content = increase offset
if !self.auto_scroll {
self.scroll_offset = self.scroll_offset.saturating_add(3);
// Check if we've scrolled to the bottom
// Use max_scroll if available, otherwise just keep scrolling
let max = self.max_scroll.get();
if max > 0 && self.scroll_offset >= max {
self.auto_scroll = true;
self.scroll_offset = 0;
}
}
self.selection = None; // Clear selection on scroll
}
MouseEventKind::Down(MouseButton::Left) => {
// Start selection in messages area
if m.row >= msg_area_y {
// If auto_scroll is on, sync scroll_offset first before disabling it
if self.auto_scroll {
self.scroll_offset = self.max_scroll.get().max(50);
}
let line = self.scroll_offset as usize + (m.row - msg_area_y) as usize;
let col = m.column as usize;
self.selection = Some(Selection::new(line, col));
self.selecting = true;
self.auto_scroll = false; // Stop auto scroll when selecting
}
}
MouseEventKind::Drag(MouseButton::Left) => {
// Extend selection
if self.selecting && m.row >= msg_area_y {
// Sync scroll_offset if auto_scroll was on
if self.auto_scroll {
self.scroll_offset = self.max_scroll.get().max(50);
self.auto_scroll = false;
}
let line = self.scroll_offset as usize + (m.row - msg_area_y) as usize;
let col = m.column as usize;
if let Some(ref mut sel) = self.selection {
sel.extend_to(line, col);
}
}
}
MouseEventKind::Up(MouseButton::Left) => {
self.selecting = false;
// Auto-copy to clipboard on mouse release (like terminal behavior)
if let Some(sel) = self.selection {
let text = self.get_selected_text(sel);
if !text.is_empty() {
// Try clipboard and show result in debug mode
let result = arboard::Clipboard::new()
.and_then(|mut cb| cb.set_text(&text));
if self.debug_mode {
match result {
Ok(_) => self.messages.push(Message {
role: Role::System,
content: format!("✓ Copied {} chars", text.len())
}),
Err(e) => self.messages.push(Message {
role: Role::System,
content: format!("❌ Copy failed: {}", e)
}),
}
self.auto_scroll = true;
}
}
}
}
_ => {}
}
}
}