tmux-deck 0.1.10

A Tmux session manager. Monitoring multi session Realtime preview.
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
use std::io;
use std::time::Duration;

use color_eyre::Result;
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use tokio::sync::{mpsc, oneshot};

use crate::actor::messages::{RefreshControl, TmuxCommand, TmuxResponse, UIEvent};
use crate::app::{Focus, GroupChoice, InputMode, PopupMode, UIState, ViewMode};
use crate::ui::render_ui;

// =============================================================================
// Key Event Poller (runs in dedicated blocking thread)
// =============================================================================

fn spawn_key_event_poller(key_tx: mpsc::Sender<Event>) {
    std::thread::spawn(move || {
        loop {
            // Poll with moderate timeout for balance between responsiveness and CPU usage
            if event::poll(Duration::from_millis(50)).unwrap_or(false)
                && let Ok(evt) = event::read()
                && key_tx.blocking_send(evt).is_err()
            {
                // Receiver dropped, exit thread
                break;
            }
        }
    });
}

// =============================================================================
// UIActor
// =============================================================================

pub struct UIActor {
    terminal: Terminal<CrosstermBackend<io::Stdout>>,
    state: UIState,
    /// High-priority channel: user-initiated commands.
    tmux_cmd_tx: mpsc::Sender<TmuxCommand>,
    /// Low-priority channel: periodic capture-pane.
    tmux_capture_tx: mpsc::Sender<TmuxCommand>,
    tmux_res_rx: mpsc::Receiver<TmuxResponse>,
    ui_event_rx: mpsc::Receiver<UIEvent>,
    key_rx: mpsc::Receiver<Event>,
    refresh_control: RefreshControl,
}

impl UIActor {
    pub fn new(
        terminal: Terminal<CrosstermBackend<io::Stdout>>,
        state: UIState,
        tmux_cmd_tx: mpsc::Sender<TmuxCommand>,
        tmux_capture_tx: mpsc::Sender<TmuxCommand>,
        tmux_res_rx: mpsc::Receiver<TmuxResponse>,
        ui_event_rx: mpsc::Receiver<UIEvent>,
        refresh_control: RefreshControl,
    ) -> Self {
        // Spawn dedicated key event poller thread
        let (key_tx, key_rx) = mpsc::channel::<Event>(64);
        spawn_key_event_poller(key_tx);

        Self {
            terminal,
            state,
            tmux_cmd_tx,
            tmux_capture_tx,
            tmux_res_rx,
            ui_event_rx,
            key_rx,
            refresh_control,
        }
    }

    pub async fn run(mut self) -> Result<()> {
        // Request initial data
        let _ = self.tmux_cmd_tx.send(TmuxCommand::RefreshAll).await;

        // Initial render before entering event loop
        self.terminal.draw(|frame| {
            render_ui(frame, &mut self.state);
        })?;

        // Drives the Claude "Working" dots spinner. Ticks frequently, but only
        // forces a redraw while something is actually animating, so an idle TUI
        // stays event-driven.
        let mut anim = tokio::time::interval(Duration::from_millis(80));

        loop {
            // Default to redrawing; the animation tick decides for itself.
            let mut redraw = true;

            // Use select to handle multiple event sources
            // biased; ensures key events are checked first (top-to-bottom priority)
            tokio::select! {
                biased;

                // Key events from dedicated poller thread (highest priority)
                Some(event) = self.key_rx.recv() => {
                    if self.handle_key_event(event).await? {
                        break; // Exit requested
                    }
                }

                // TmuxActor responses
                Some(response) = self.tmux_res_rx.recv() => {
                    self.handle_tmux_response(response);
                }

                // RefreshActor events
                Some(event) = self.ui_event_rx.recv() => {
                    match event {
                        UIEvent::Tick => {
                            // Cheap, local: fold the latest Claude hook states
                            // into the tree so markers stay live between full
                            // tmux refreshes.
                            self.state.refresh_claude_states();

                            // Request pane capture if in TreeView mode (low-priority channel)
                            if self.state.view_mode == ViewMode::TreeView
                                && let Some((target, start, end)) =
                                    self.state.get_selected_pane_target_with_capture_range()
                            {
                                let _ = self
                                    .tmux_capture_tx
                                    .send(TmuxCommand::CapturePane { target, start, end })
                                    .await;
                            }
                        }
                        UIEvent::Shutdown => {
                            break;
                        }
                        _ => (),
                    }
                }

                // Spinner animation tick: only redraw if a spinner is active.
                _ = anim.tick() => {
                    redraw = self.state.has_working_claude();
                }
            }

            // Render UI after processing event (event-driven rendering)
            if redraw {
                self.terminal.draw(|frame| {
                    render_ui(frame, &mut self.state);
                })?;
            }
        }

        Ok(())
    }

    async fn handle_key_event(&mut self, event: Event) -> Result<bool> {
        if let Event::Key(key) = event {
            if key.kind != KeyEventKind::Press {
                return Ok(false);
            }

            // Handle popup mode first
            if let Some(popup_mode) = self.state.popup_mode {
                return self.handle_popup_key(key, popup_mode).await;
            }

            // Handle input mode
            match self.state.input_mode {
                InputMode::Normal => {
                    return self.handle_normal_mode_key(key).await;
                }
                InputMode::Input => {
                    self.handle_input_mode_key(key).await?;
                }
            }
        }
        Ok(false)
    }

    async fn handle_popup_key(
        &mut self,
        key: event::KeyEvent,
        popup_mode: PopupMode,
    ) -> Result<bool> {
        match popup_mode {
            PopupMode::GroupSession => {
                // Selecting an existing group (or "ungroup") is handled entirely
                // tmux-deck-side: no tmux command and no RefreshAll, since
                // grouping does not change anything tmux knows about.
                match key.code {
                    KeyCode::Esc => {
                        self.state.close_popup();
                        self.refresh_control.resume();
                    }
                    KeyCode::Up | KeyCode::Char('k') => self.state.group_choice_up(),
                    KeyCode::Down | KeyCode::Char('j') => self.state.group_choice_down(),
                    KeyCode::Enter => match self.state.selected_group_choice() {
                        GroupChoice::Existing(group) => {
                            self.state.assign_selected_group(Some(group));
                            self.state.close_popup();
                            self.refresh_control.resume();
                        }
                        GroupChoice::Ungrouped => {
                            self.state.assign_selected_group(None);
                            self.state.close_popup();
                            self.refresh_control.resume();
                        }
                        // Switch to text entry; stay in popup so the refresh
                        // control remains paused until the name is confirmed.
                        GroupChoice::New => self.state.begin_new_group_entry(),
                    },
                    _ => {}
                }
            }
            PopupMode::NewSession | PopupMode::RenameSession | PopupMode::NewGroup => {
                match key.code {
                    KeyCode::Esc => {
                        self.state.close_popup();
                        self.refresh_control.resume();
                    }
                    KeyCode::Enter => {
                        // A new group is handled entirely tmux-deck-side: no
                        // tmux command and no RefreshAll, since grouping does
                        // not change anything tmux knows about.
                        if popup_mode == PopupMode::NewGroup {
                            let group = self.state.get_group_session_input();
                            self.state.assign_selected_group(group);
                            self.state.close_popup();
                            self.refresh_control.resume();
                            return Ok(false);
                        }
                        if popup_mode == PopupMode::NewSession {
                            let name = self.state.get_new_session_name();
                            if !name.is_empty() {
                                let _ = self.tmux_cmd_tx.send(TmuxCommand::NewSession { name }).await;
                            }
                        } else if let Some((old_name, new_name)) =
                            self.state.get_rename_session_info()
                        {
                            // Carry the group label across the rename so the
                            // session does not silently fall out of its group.
                            self.state.groups.rename_session(&old_name, &new_name);
                            let _ = self
                                .tmux_cmd_tx
                                .send(TmuxCommand::RenameSession { old_name, new_name })
                                .await;
                        }
                        self.state.close_popup();
                        self.refresh_control.resume();
                        // Refresh after operation
                        let _ = self.tmux_cmd_tx.send(TmuxCommand::RefreshAll).await;
                    }
                    KeyCode::Backspace => self.state.input_backspace(),
                    KeyCode::Delete => self.state.input_delete(),
                    KeyCode::Left => self.state.input_move_left(),
                    KeyCode::Right => self.state.input_move_right(),
                    KeyCode::Home => self.state.input_move_home(),
                    KeyCode::End => self.state.input_move_end(),
                    KeyCode::Char(c) => self.state.input_char(c),
                    _ => {}
                }
            }
            PopupMode::ConfirmKill => {
                match key.code {
                    KeyCode::Esc => {
                        self.state.close_popup();
                        self.refresh_control.resume();
                    }
                    KeyCode::Enter => {
                        if let Some(name) = self.state.get_kill_session_name() {
                            // Drop the killed session's group assignment so the
                            // store does not keep stale entries around.
                            self.state.groups.forget(&name);
                            let _ = self.tmux_cmd_tx.send(TmuxCommand::KillSession { name }).await;
                            // Refresh after operation
                            let _ = self.tmux_cmd_tx.send(TmuxCommand::RefreshAll).await;
                        }
                        self.state.close_popup();
                        self.refresh_control.resume();
                    }
                    KeyCode::Left
                    | KeyCode::Right
                    | KeyCode::Tab
                    | KeyCode::Char('h')
                    | KeyCode::Char('l') => {
                        self.state.toggle_confirm_selection();
                    }
                    KeyCode::Char('y') => {
                        self.state.confirm_yes_selected = true;
                    }
                    KeyCode::Char('n') => {
                        self.state.confirm_yes_selected = false;
                    }
                    _ => {}
                }
            }
        }
        Ok(false)
    }

    async fn handle_normal_mode_key(&mut self, key: event::KeyEvent) -> Result<bool> {
        let is_ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

        // `za` fold chord: a pending `z` followed by `a` toggles the current
        // group's fold. Any other key cancels the chord and is then processed
        // normally below.
        if self.state.pending_z {
            self.state.pending_z = false;
            if !is_ctrl && key.code == KeyCode::Char('a') {
                self.state.toggle_fold_current_group();
                return Ok(false);
            }
        }

        if is_ctrl {
            match key.code {
                KeyCode::Char('n') => {
                    self.state.open_new_session_popup();
                    self.refresh_control.pause();
                }
                KeyCode::Char('r') => {
                    self.state.open_rename_session_popup();
                    self.refresh_control.pause();
                }
                KeyCode::Char('x') => {
                    self.state.open_kill_session_popup();
                    self.refresh_control.pause();
                }
                _ => {}
            }
        } else {
            match key.code {
                KeyCode::Char('q') | KeyCode::Esc => return Ok(true), // Exit
                KeyCode::Char('r') => {
                    let _ = self.tmux_cmd_tx.send(TmuxCommand::RefreshAll).await;
                }
                KeyCode::Char('s')
                    if self.state.view_mode == ViewMode::TreeView
                        && self.state.focus == Focus::Sessions =>
                {
                    self.state.cycle_session_sort();
                }
                KeyCode::Char('g')
                    if self.state.view_mode == ViewMode::TreeView
                        && self.state.focus == Focus::Sessions =>
                {
                    self.state.open_group_session_popup();
                    self.refresh_control.pause();
                }
                KeyCode::Char('z')
                    if self.state.view_mode == ViewMode::TreeView
                        && self.state.focus == Focus::Sessions =>
                {
                    // Begin the `za` fold chord; the next key resolves it.
                    self.state.pending_z = true;
                }
                KeyCode::Char(' ') => {
                    self.state.handle_space_press();
                }
                KeyCode::Char('i') => {
                    self.state.enter_input_mode();
                    self.refresh_control.pause();
                }
                KeyCode::Enter => {
                    if let Some(target) = self.state.get_enter_target() {
                        let (reply_tx, reply_rx) = oneshot::channel();
                        let _ = self
                            .tmux_cmd_tx
                            .send(TmuxCommand::SwitchClient {
                                target,
                                reply: Some(reply_tx),
                            })
                            .await;
                        let _ = reply_rx.await;
                        return Ok(true); // Exit after switch
                    }
                }
                _ => {
                    // View-specific key handling
                    self.handle_navigation_key(key.code);
                }
            }
        }
        Ok(false)
    }

    async fn handle_input_mode_key(&mut self, key: event::KeyEvent) -> Result<()> {
        match key.code {
            KeyCode::Esc => {
                self.state.exit_input_mode();
                self.refresh_control.resume();
            }
            KeyCode::Enter => {
                if let Some(target) = self.state.get_current_target() {
                    let keys = self.state.input_buffer.clone();
                    let (reply_tx, reply_rx) = oneshot::channel();
                    let _ = self
                        .tmux_cmd_tx
                        .send(TmuxCommand::SendKeys {
                            target,
                            keys,
                            reply: Some(reply_tx),
                        })
                        .await;
                    let _ = reply_rx.await;
                }
                self.state.exit_input_mode();
                self.refresh_control.resume();
            }
            KeyCode::Backspace => self.state.input_backspace(),
            KeyCode::Delete => self.state.input_delete(),
            KeyCode::Left => self.state.input_move_left(),
            KeyCode::Right => self.state.input_move_right(),
            KeyCode::Home => self.state.input_move_home(),
            KeyCode::End => self.state.input_move_end(),
            KeyCode::Char(c) => self.state.input_char(c),
            _ => {}
        }
        Ok(())
    }

    fn handle_navigation_key(&mut self, code: KeyCode) {
        match self.state.view_mode {
            ViewMode::TreeView => match code {
                KeyCode::Up | KeyCode::Char('k') => self.state.tree_move_up(),
                KeyCode::Down | KeyCode::Char('j') => self.state.tree_move_down(),
                KeyCode::Tab => self.state.tree_next_focus(),
                KeyCode::BackTab => self.state.tree_prev_focus(),
                KeyCode::Left | KeyCode::Char('h') => self.state.tree_prev_focus(),
                KeyCode::Right | KeyCode::Char('l') => self.state.tree_next_focus(),
                _ => {}
            },
            ViewMode::MultiPreview => match code {
                KeyCode::Up | KeyCode::Char('k') => self.state.multi_move_up(),
                KeyCode::Down | KeyCode::Char('j') => self.state.multi_move_down(),
                KeyCode::Left | KeyCode::Char('h') => self.state.multi_move_left(),
                KeyCode::Right | KeyCode::Char('l') => self.state.multi_move_right(),
                _ => {}
            },
        }
    }

    fn handle_tmux_response(&mut self, response: TmuxResponse) {
        match response {
            TmuxResponse::SessionsRefreshed { sessions } => {
                self.state.update_sessions(sessions);
            }
            TmuxResponse::PaneCaptured { target: _, content } => {
                self.state.update_pane_content(content);
            }
            TmuxResponse::SessionCreated {
                name,
                success,
                error,
            } => {
                if success {
                    // Select the new session
                    if let Some(idx) = self.state.sessions.iter().position(|s| s.name == name) {
                        self.state.selected_session = idx;
                        self.state.session_list_state.select(Some(idx));
                    }
                } else if let Some(err) = error {
                    self.state.set_error(err);
                }
            }
            TmuxResponse::SessionRenamed { success, error } => {
                if !success && let Some(err) = error {
                    self.state.set_error(err);
                }
            }
            TmuxResponse::SessionKilled { success, error } => {
                if success {
                    // Adjust selection if needed
                    if !self.state.sessions.is_empty() {
                        self.state.selected_session = self
                            .state
                            .selected_session
                            .min(self.state.sessions.len().saturating_sub(1));
                        self.state
                            .session_list_state
                            .select(Some(self.state.selected_session));
                    }
                } else if let Some(err) = error {
                    self.state.set_error(err);
                }
            }
            TmuxResponse::KeysSent { success: _, error } => {
                if let Some(err) = error {
                    self.state.set_error(err);
                }
            }
            TmuxResponse::ClientSwitched {
                target,
                success,
                error,
            } => {
                if !success {
                    let message = match error {
                        Some(err) if !err.trim().is_empty() => {
                            format!("Failed to switch to {}: {}", target, err)
                        }
                        _ => format!("Failed to switch to {}", target),
                    };
                    self.state.set_error(message);
                }
            }
            TmuxResponse::Error { message } => {
                self.state.set_error(message);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_handle_key_event() {}
}