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
//! TUI command implementation
use crate::agent::{AgentStatus, WorkState};
use crate::app::{App, AppMode, FocusedPane, InputMode, ReviewFocus};
use crate::tui::{handle_command_mode, handle_keybinding, handle_navigation_mode, handle_theme_picker_input, ui};
use anyhow::{Context, Result};
use cctakt::{create_theme, debug, set_theme, Config, IssuePickerResult, LockFile};
use crossterm::{
cursor::Hide,
event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
execute,
terminal::{
self, disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io;
use std::time::Duration;
/// Run the TUI application
pub fn run_tui() -> Result<()> {
// Acquire lock to prevent duplicate instances
// The lock is automatically released when _lock goes out of scope
let _lock = LockFile::acquire()?;
// Load configuration
let config = Config::load().unwrap_or_default();
// Initialize theme from config
set_theme(create_theme(&config.theme));
// Get terminal size
let (cols, rows) = terminal::size().context("Failed to get terminal size")?;
let content_rows = rows.saturating_sub(3); // Header 1 line + border 2 lines
let content_cols = cols.saturating_sub(2); // Border 2 columns
// Setup terminal
enable_raw_mode().context("Failed to enable raw mode")?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, Hide)?;
execute!(
stdout,
crossterm::terminal::SetTitle("cctakt - Claude Code Orchestrator")
)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Initialize app
let mut app = App::new(content_rows, content_cols, config);
// Add initial agent
if let Err(e) = app.add_agent() {
// Cleanup and return error
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
crossterm::cursor::Show,
LeaveAlternateScreen
)?;
return Err(e);
}
// Main loop
loop {
// Draw
terminal.draw(|f| ui(f, &mut app))?;
// Handle pending agent prompt (wait ~1 second for agent to initialize)
if app.pending_agent_prompt.is_some() {
app.prompt_delay_frames += 1;
// After 60 frames (~1 sec), send the task
if app.prompt_delay_frames > 60 {
if let Some(prompt) = app.pending_agent_prompt.take() {
if let Some(agent) = app.agent_manager.active_mut() {
agent.send_bytes(prompt.as_bytes());
agent.send_bytes(b"\r"); // Carriage return for Enter
agent.task_sent = true;
agent.work_state = WorkState::Working;
}
}
app.prompt_delay_frames = 0;
}
}
// Check agent work states and auto-transition to review mode
app.check_agent_completion();
// Poll events (16ms ≈ 60fps)
if event::poll(Duration::from_millis(16))? {
match event::read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => {
// Debug: log every key event received
debug::log(&format!(
"KEY_EVENT: {:?}, mode={:?}, input_mode={:?}",
key.code, app.mode, app.input_mode
));
match app.mode {
AppMode::ReviewMerge => {
// Handle review mode input with split pane
// Use InputMode for vim-style navigation
match app.input_mode {
InputMode::Navigation => {
// NAV mode: hjkl for scroll/focus, q to quit, i/Enter to enter Input mode
match key.code {
KeyCode::Char('i') | KeyCode::Enter => {
app.input_mode = InputMode::Input;
}
KeyCode::Char('q') | KeyCode::Char('Q') => {
// Cancel review
app.cancel_review();
}
KeyCode::Char('m') | KeyCode::Char('M') => {
// Enqueue merge (handled by MergeWorker)
app.enqueue_merge();
}
// Scroll focused pane with j/k
KeyCode::Char('k') | KeyCode::Up => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll =
state.summary_scroll.saturating_sub(1);
}
ReviewFocus::Diff => {
state.diff_view.scroll_up(1);
}
}
}
}
KeyCode::Char('j') | KeyCode::Down => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
let max_scroll = state
.commit_log
.lines()
.count()
.saturating_sub(1)
as u16;
state.summary_scroll =
(state.summary_scroll + 1).min(max_scroll);
}
ReviewFocus::Diff => {
state.diff_view.scroll_down(1);
}
}
}
}
// Pane navigation with h/l
KeyCode::Char('h') => {
app.focused_pane = FocusedPane::Left;
}
KeyCode::Char('l') => {
app.focused_pane = FocusedPane::Right;
}
// Focus switching between Summary/Diff with Tab
KeyCode::Tab => {
if let Some(ref mut state) = app.review_state {
state.focus = match state.focus {
ReviewFocus::Summary => ReviewFocus::Diff,
ReviewFocus::Diff => ReviewFocus::Summary,
};
}
}
KeyCode::PageUp => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll =
state.summary_scroll.saturating_sub(10);
}
ReviewFocus::Diff => {
state.diff_view.page_up(20);
}
}
}
}
KeyCode::PageDown => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
let max_scroll = state
.commit_log
.lines()
.count()
.saturating_sub(1)
as u16;
state.summary_scroll =
(state.summary_scroll + 10).min(max_scroll);
}
ReviewFocus::Diff => {
state.diff_view.page_down(20);
}
}
}
}
KeyCode::Home => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll = 0;
}
ReviewFocus::Diff => {
state.diff_view.scroll_to_top();
}
}
}
}
KeyCode::End => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll = state
.commit_log
.lines()
.count()
.saturating_sub(1)
as u16;
}
ReviewFocus::Diff => {
state.diff_view.scroll_to_bottom();
}
}
}
}
_ => {}
}
}
InputMode::Input => {
// Input mode: Esc to enter NAV mode, other keys for review actions
match key.code {
KeyCode::Esc => {
app.input_mode = InputMode::Navigation;
}
KeyCode::Char('m') | KeyCode::Char('M') => {
// Enqueue merge (handled by MergeWorker)
app.enqueue_merge();
}
KeyCode::Char('c') | KeyCode::Char('C') => {
// Cancel review
app.cancel_review();
}
// Focus switching between Summary/Diff with Tab
KeyCode::Tab => {
if let Some(ref mut state) = app.review_state {
state.focus = match state.focus {
ReviewFocus::Summary => ReviewFocus::Diff,
ReviewFocus::Diff => ReviewFocus::Summary,
};
}
}
// Scroll focused pane with arrow keys
KeyCode::Up => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll =
state.summary_scroll.saturating_sub(1);
}
ReviewFocus::Diff => {
state.diff_view.scroll_up(1);
}
}
}
}
KeyCode::Down => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
let max_scroll = state
.commit_log
.lines()
.count()
.saturating_sub(1)
as u16;
state.summary_scroll =
(state.summary_scroll + 1).min(max_scroll);
}
ReviewFocus::Diff => {
state.diff_view.scroll_down(1);
}
}
}
}
KeyCode::PageUp => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll =
state.summary_scroll.saturating_sub(10);
}
ReviewFocus::Diff => {
state.diff_view.page_up(20);
}
}
}
}
KeyCode::PageDown => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
let max_scroll = state
.commit_log
.lines()
.count()
.saturating_sub(1)
as u16;
state.summary_scroll =
(state.summary_scroll + 10).min(max_scroll);
}
ReviewFocus::Diff => {
state.diff_view.page_down(20);
}
}
}
}
KeyCode::Home => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll = 0;
}
ReviewFocus::Diff => {
state.diff_view.scroll_to_top();
}
}
}
}
KeyCode::End => {
if let Some(ref mut state) = app.review_state {
match state.focus {
ReviewFocus::Summary => {
state.summary_scroll = state
.commit_log
.lines()
.count()
.saturating_sub(1)
as u16;
}
ReviewFocus::Diff => {
state.diff_view.scroll_to_bottom();
}
}
}
}
_ => {}
}
}
InputMode::Command => {
// Command mode not used in review, treat as Input
if key.code == KeyCode::Esc {
app.input_mode = InputMode::Navigation;
}
}
}
}
AppMode::IssuePicker => {
// Handle issue picker input
if let Some(result) = app.issue_picker.handle_key(key.code) {
match result {
IssuePickerResult::Selected(issue) => {
app.mode = AppMode::Normal;
let _ = app.add_agent_from_issue(issue);
}
IssuePickerResult::Cancel => {
app.mode = AppMode::Normal;
}
IssuePickerResult::Refresh => {
app.fetch_issues();
}
}
}
}
AppMode::Normal => {
debug::log("Entering AppMode::Normal branch");
if app.agent_manager.is_empty() {
// No agents - orchestrator was closed, quit app
debug::log("agent_manager.is_empty() = true, quitting");
app.should_quit = true;
} else {
// Always handle global keybindings (Ctrl+Q, Ctrl+T, etc)
let handled = handle_keybinding(&mut app, key.modifiers, key.code);
debug::log(&format!("handle_keybinding returned: {}", handled));
if !handled {
// Debug: log current mode and key
debug::log(&format!(
"Key: {:?}, Mode: {:?}, InputMode: {:?}",
key.code, app.mode, app.input_mode
));
match app.input_mode {
InputMode::Navigation => {
// Navigation mode: hjkl for pane navigation
debug::log("Processing Navigation mode key");
handle_navigation_mode(&mut app, key.code);
}
InputMode::Input => {
// Input mode: forward keys to focused agent
// Esc switches back to navigation mode
debug::log("Processing Input mode key");
if key.code == KeyCode::Esc {
debug::log(
"Esc pressed - switching to Navigation mode",
);
app.input_mode = InputMode::Navigation;
} else {
// Determine which agent to send input to
// Fallback: if focused pane has no agent, try the other pane
let has_interactive =
app.agent_manager.get_interactive().is_some();
let has_worker = app
.agent_manager
.get_active_non_interactive()
.is_some();
let use_interactive = match app.focused_pane {
FocusedPane::Left => {
has_interactive || !has_worker
}
FocusedPane::Right => {
!has_worker && has_interactive
}
};
// If focused on non-interactive agent (worker),
// allow h/l for pane navigation since workers don't accept input
if !use_interactive {
match key.code {
KeyCode::Char('h') => {
app.focused_pane = FocusedPane::Left;
continue;
}
KeyCode::Char('l') => {
app.focused_pane = FocusedPane::Right;
continue;
}
_ => {}
}
}
let agent = if use_interactive {
app.agent_manager.get_interactive_mut()
} else {
app.agent_manager.get_active_non_interactive_mut()
};
if let Some(agent) = agent {
if agent.status == AgentStatus::Running {
match (key.modifiers, key.code) {
(
KeyModifiers::CONTROL,
KeyCode::Char(c),
) => {
let ctrl_char = (c as u8) & 0x1f;
agent.send_bytes(&[ctrl_char]);
}
(_, KeyCode::Enter) => {
agent.send_bytes(b"\r")
}
(_, KeyCode::Backspace) => {
agent.send_bytes(&[0x7f])
}
(_, KeyCode::Tab) => {
agent.send_bytes(b"\t")
}
(_, KeyCode::Up) => {
agent.send_bytes(b"\x1b[A")
}
(_, KeyCode::Down) => {
agent.send_bytes(b"\x1b[B")
}
(_, KeyCode::Right) => {
agent.send_bytes(b"\x1b[C")
}
(_, KeyCode::Left) => {
agent.send_bytes(b"\x1b[D")
}
(_, KeyCode::Home) => {
agent.send_bytes(b"\x1b[H")
}
(_, KeyCode::End) => {
agent.send_bytes(b"\x1b[F")
}
(_, KeyCode::PageUp) => {
agent.send_bytes(b"\x1b[5~")
}
(_, KeyCode::PageDown) => {
agent.send_bytes(b"\x1b[6~")
}
(_, KeyCode::Delete) => {
agent.send_bytes(b"\x1b[3~")
}
(_, KeyCode::Char(c)) => {
let mut buf = [0u8; 4];
let s = c.encode_utf8(&mut buf);
agent.send_bytes(s.as_bytes());
}
_ => {}
}
}
}
}
}
InputMode::Command => {
// Command mode: handle :q, :quit, etc.
debug::log("Processing Command mode key");
handle_command_mode(&mut app, key.code);
}
}
}
}
}
AppMode::ThemePicker => {
// Handle theme picker input
handle_theme_picker_input(&mut app, key.code);
}
}
}
Event::Resize(new_cols, new_rows) => {
let content_rows = new_rows.saturating_sub(3);
let content_cols = new_cols.saturating_sub(2);
app.resize(content_cols, content_rows);
}
_ => {}
}
}
// Check all agents' status
app.agent_manager.check_all_status();
// Plan processing
app.check_plan();
app.check_agent_task_completions();
app.process_plan();
// Check MergeWorker completion
app.check_merge_worker_completion();
// Check BuildWorker completion
app.check_build_worker_completion();
app.cleanup_notifications();
// Check if active agent just ended and has a worktree (for review)
if app.mode == AppMode::Normal {
let active_index = app.agent_manager.active_index();
if let Some(agent) = app.agent_manager.active() {
if agent.status == AgentStatus::Ended {
// Check if this agent has a worktree
let has_worktree = active_index < app.agent_worktrees.len()
&& app.agent_worktrees[active_index].is_some();
if has_worktree {
app.start_review(active_index);
}
}
}
}
if app.should_quit {
break;
}
}
// Cleanup
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
crossterm::cursor::Show,
LeaveAlternateScreen
)?;
Ok(())
}