workmux 0.1.179

An opinionated workflow tool that orchestrates git worktrees and tmux
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
//! Dashboard TUI for monitoring and managing workmux agents.
//!
//! This module provides an interactive terminal UI that displays:
//! - All running agent panes across tmux sessions
//! - Git status for each worktree
//! - Agent status (working/waiting/done) with elapsed time
//! - Live preview of selected agent's terminal output
//!
//! # Module Structure
//!
//! - `app`: Application state and business logic
//! - `actions`: Action enum and dispatcher for all dashboard actions
//! - `agent`: Pure helper functions for agent data extraction
//! - `ansi`: ANSI escape sequence parsing and stripping
//! - `diff`: Diff domain types and helper functions
//! - `keymap`: Key-to-action mapping per context with help text
//! - `settings`: Tmux-persisted dashboard settings
//! - `sort`: Sort mode enum and tmux persistence
//! - `spinner`: Spinner animation constants
//! - `ui/`: TUI rendering modules
//!   - `dashboard`: Table, preview, and footer
//!   - `diff`: Normal diff, patch mode, file list
//!   - `format`: Git status formatting
//!   - `help`: Help overlay

mod actions;
pub mod agent;
mod ansi;
mod app;
mod diff;
mod diff_ops;
mod keymap;
mod scope;
mod settings;
mod sort;
pub mod spinner;
pub mod ui;

use anyhow::Result;
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyEventKind, MouseEventKind},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::backend::CrosstermBackend;
use std::io;
use std::sync::mpsc;
use std::time::Duration;

use crate::git;
use crate::github;
use crate::multiplexer::{create_backend, detect_backend};

use self::actions::apply_action;
use self::app::{App, AppEvent, DashboardTab, ViewMode};
use self::diff_ops::DiffOps;
use self::keymap::{Context, action_for_key};
use self::spinner::SPINNER_FRAME_COUNT;
use self::ui::ui;

/// Determine the current keymap context based on app state.
fn get_context(app: &App) -> Context {
    match &app.view_mode {
        ViewMode::Dashboard => match app.active_tab {
            DashboardTab::Agents => {
                if app.filter_active {
                    Context::DashboardFilter
                } else if app.input_mode {
                    Context::DashboardInput
                } else {
                    Context::DashboardNormal
                }
            }
            DashboardTab::Worktrees => {
                if app.worktree_filter_active {
                    Context::WorktreeFilter
                } else {
                    Context::WorktreeNormal
                }
            }
        },
        ViewMode::Diff(diff) => {
            if diff.patch_mode {
                if diff.comment_input.is_some() {
                    Context::Comment
                } else {
                    Context::Patch
                }
            } else {
                Context::DiffNormal
            }
        }
    }
}

/// Handle mouse events for diff view scrolling.
fn handle_mouse_event(app: &mut App, kind: MouseEventKind) {
    if let ViewMode::Diff(ref mut diff_view) = app.view_mode {
        let total_lines = if diff_view.patch_mode {
            diff_view
                .hunks
                .get(diff_view.current_hunk)
                .map(|h| h.parsed_lines.len())
                .unwrap_or(0)
        } else {
            diff_view.line_count
        };

        match kind {
            MouseEventKind::ScrollUp => {
                diff_view.scroll = diff_view.scroll.saturating_sub(3);
            }
            MouseEventKind::ScrollDown => {
                let max_scroll = total_lines.saturating_sub(diff_view.viewport_height as usize);
                diff_view.scroll = (diff_view.scroll + 3).min(max_scroll);
            }
            _ => {}
        }
    }
}

pub fn run(cli_preview_size: Option<u8>, open_diff: bool, session_filter: bool) -> Result<()> {
    let mux = create_backend(detect_backend());

    // Check if multiplexer is running
    if !mux.is_running().unwrap_or(false) {
        println!("No {} server running.", mux.name());
        return Ok(());
    }

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = ratatui::Terminal::new(backend)?;

    // Unified event channel: all background threads and the input thread send here
    let (event_tx, event_rx) = mpsc::channel::<AppEvent>();

    // Create app state before spawning the input thread to avoid a race condition
    // where stray terminal events (e.g. the Enter key used to launch the command)
    // get queued and processed before the app is ready.
    let mut app = App::new(mux, session_filter, event_tx.clone())?;

    // CLI preview size overrides config/tmux if provided
    if let Some(size) = cli_preview_size {
        app.preview_size = size;
    }

    // Open diff view for current worktree if requested
    if open_diff && let Some(ref current_path) = app.current_worktree {
        // Find the agent matching the current worktree path
        if let Some(idx) = app.agents.iter().position(|a| &a.path == current_path) {
            app.table_state.select(Some(idx));
            app.load_diff(false); // WIP diff (uncommitted changes)
        }
    }

    // Discard any terminal events buffered during startup (e.g. the Enter used to
    // launch the command from the shell). Intentionally discards typeahead.
    while crossterm::event::poll(Duration::ZERO).unwrap_or(false) {
        if crossterm::event::read().is_err() {
            break;
        }
    }

    // Dedicated input thread: reads crossterm events and forwards them.
    // Spawned after init + drain so stray keypresses can't trigger actions.
    let input_tx = event_tx;
    std::thread::spawn(move || {
        while let Ok(ev) = event::read() {
            if input_tx.send(AppEvent::Terminal(ev)).is_err() {
                break; // receiver dropped, app is shutting down
            }
        }
    });

    // Main loop
    let tick_rate = Duration::from_millis(250);
    let mut last_tick = std::time::Instant::now();
    let refresh_interval = Duration::from_secs(2);
    let mut last_refresh = std::time::Instant::now();
    // Preview refreshes more frequently than the agent list
    // Use a faster refresh rate when in input mode for responsive typing feedback
    let preview_refresh_interval_normal = Duration::from_millis(500);
    let preview_refresh_interval_input = Duration::from_millis(100);
    let mut last_preview_refresh = std::time::Instant::now();

    loop {
        terminal.draw(|f| ui(f, &mut app))?;

        // Calculate timeout: wake for the earliest timer deadline
        let current_preview_interval = if app.input_mode {
            preview_refresh_interval_input
        } else {
            preview_refresh_interval_normal
        };
        let time_until_preview =
            current_preview_interval.saturating_sub(last_preview_refresh.elapsed());
        let time_until_tick = tick_rate.saturating_sub(last_tick.elapsed());
        let timeout = time_until_tick.min(time_until_preview);

        // Block until an event arrives OR the timeout fires
        match event_rx.recv_timeout(timeout) {
            Ok(event) => {
                handle_event(&mut app, event, &mut last_preview_refresh);

                // Drain any other pending events to coalesce bursts
                while let Ok(event) = event_rx.try_recv() {
                    handle_event(&mut app, event, &mut last_preview_refresh);
                }
            }
            Err(mpsc::RecvTimeoutError::Timeout) => {}
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
        }

        if last_tick.elapsed() >= tick_rate {
            last_tick = std::time::Instant::now();
            // Advance spinner animation frame (wrap at frame count to avoid skip artifact)
            app.spinner_frame = (app.spinner_frame + 1) % SPINNER_FRAME_COUNT;
        }

        // Auto-refresh agent list every 2 seconds
        if last_refresh.elapsed() >= refresh_interval {
            app.refresh();
            last_refresh = std::time::Instant::now();
        }

        // Auto-refresh preview more frequently for live updates
        // Uses faster refresh rate in input mode (set at top of loop)
        if app.mux.supports_preview() && last_preview_refresh.elapsed() >= current_preview_interval
        {
            app.refresh_preview();
            last_preview_refresh = std::time::Instant::now();
        }

        if app.should_quit || app.should_jump {
            break;
        }
    }

    // Save git status cache before exiting
    git::save_status_cache(&app.git_statuses);

    // Save PR status cache before exiting
    github::save_pr_cache(app.pr_statuses());

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    Ok(())
}

/// Handle a single AppEvent, dispatching terminal input or applying background data.
fn handle_event(app: &mut App, event: AppEvent, last_preview_refresh: &mut std::time::Instant) {
    match event {
        AppEvent::Terminal(terminal_event) => {
            handle_terminal_event(app, terminal_event, last_preview_refresh);
        }
        bg_event => app.apply_event(bg_event),
    }
}

/// Handle a crossterm terminal event (key press, mouse scroll, etc.)
fn handle_terminal_event(
    app: &mut App,
    event: Event,
    last_preview_refresh: &mut std::time::Instant,
) {
    // Handle mouse scroll events in diff view
    if let Event::Mouse(mouse) = &event {
        handle_mouse_event(app, mouse.kind);
        return;
    }

    // Handle key events
    let Event::Key(key) = event else { return };
    if key.kind != KeyEventKind::Press {
        return;
    }

    // Help overlay handling - close on any key if open
    if app.show_help {
        app.show_help = false;
        return;
    }

    // Kill confirmation popup - y confirms, anything else cancels
    if app.pending_kill_pane_id.is_some() {
        if key.code == crossterm::event::KeyCode::Char('y') {
            app.confirm_kill();
        } else {
            app.pending_kill_pane_id = None;
        }
        return;
    }

    // Remove worktree confirmation modal
    if app.pending_remove.is_some() {
        match key.code {
            crossterm::event::KeyCode::Char('y') => app.confirm_remove(),
            crossterm::event::KeyCode::Char('k') => app.toggle_remove_keep_branch(),
            crossterm::event::KeyCode::Char('f') => app.arm_remove_force(),
            _ => app.pending_remove = None, // n, Esc, or any other key cancels
        }
        return;
    }

    // Base branch picker modal
    if app.pending_base_picker.is_some() {
        match key.code {
            crossterm::event::KeyCode::Char('j') | crossterm::event::KeyCode::Down => {
                app.base_picker_down()
            }
            crossterm::event::KeyCode::Char('k') | crossterm::event::KeyCode::Up => {
                app.base_picker_up()
            }
            crossterm::event::KeyCode::Enter => app.confirm_base_picker(),
            crossterm::event::KeyCode::Backspace => app.base_picker_filter_delete(),
            crossterm::event::KeyCode::Esc => app.pending_base_picker = None,
            crossterm::event::KeyCode::Char(c) => app.base_picker_filter_append(c),
            _ => {}
        }
        return;
    }

    // Project picker modal
    if app.pending_project_picker.is_some() {
        match key.code {
            crossterm::event::KeyCode::Char('j') | crossterm::event::KeyCode::Down => {
                app.project_picker_down()
            }
            crossterm::event::KeyCode::Char('k') | crossterm::event::KeyCode::Up => {
                app.project_picker_up()
            }
            crossterm::event::KeyCode::Enter => app.confirm_project_picker(),
            crossterm::event::KeyCode::Backspace => app.project_picker_filter_delete(),
            crossterm::event::KeyCode::Esc => app.pending_project_picker = None,
            crossterm::event::KeyCode::Char(c) => app.project_picker_filter_append(c),
            _ => {}
        }
        return;
    }

    // Add worktree modal
    if let Some(ref state) = app.pending_add_worktree {
        if state.editing_base {
            // Base branch editing mode
            match key.code {
                crossterm::event::KeyCode::Tab => app.add_worktree_base_tab_complete(),
                crossterm::event::KeyCode::Enter => app.add_worktree_toggle_base(),
                crossterm::event::KeyCode::Backspace => app.add_worktree_base_delete(),
                crossterm::event::KeyCode::Esc => app.add_worktree_toggle_base(),
                crossterm::event::KeyCode::Char('w')
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    app.add_worktree_base_delete_word()
                }
                crossterm::event::KeyCode::Char('u')
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    app.add_worktree_base_clear()
                }
                crossterm::event::KeyCode::Char('b')
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    app.add_worktree_toggle_base()
                }
                crossterm::event::KeyCode::Char(c) => app.add_worktree_base_append(c),
                _ => {}
            }
        } else {
            // Main picker mode
            match key.code {
                crossterm::event::KeyCode::Down => app.add_worktree_down(),
                crossterm::event::KeyCode::Up => app.add_worktree_up(),
                crossterm::event::KeyCode::Tab => app.add_worktree_tab_complete(),
                crossterm::event::KeyCode::Enter => app.add_worktree_confirm_selection(),
                crossterm::event::KeyCode::Backspace => app.add_worktree_delete(),
                crossterm::event::KeyCode::Esc => app.pending_add_worktree = None,
                crossterm::event::KeyCode::Char('w')
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    app.add_worktree_delete_word()
                }
                crossterm::event::KeyCode::Char('u')
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    app.add_worktree_clear()
                }
                crossterm::event::KeyCode::Char('b')
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    app.add_worktree_toggle_base()
                }
                crossterm::event::KeyCode::Char('p')
                    if key
                        .modifiers
                        .contains(crossterm::event::KeyModifiers::CONTROL) =>
                {
                    app.add_worktree_toggle_pr_mode()
                }
                crossterm::event::KeyCode::Char(c) => app.add_worktree_append(c),
                _ => {}
            }
        }
        return;
    }

    // Sweep modal
    if app.pending_sweep.is_some() {
        match key.code {
            crossterm::event::KeyCode::Char(' ') => app.sweep_toggle(),
            crossterm::event::KeyCode::Char('j') | crossterm::event::KeyCode::Down => {
                app.sweep_down()
            }
            crossterm::event::KeyCode::Char('k') | crossterm::event::KeyCode::Up => app.sweep_up(),
            crossterm::event::KeyCode::Enter => app.confirm_sweep(),
            _ => app.pending_sweep = None, // Esc or any other key cancels
        }
        return;
    }

    // Get current context and map key to action
    let ctx = get_context(app);

    // Special case: EnterPatchMode only works in WIP diff view (not branch diff)
    if ctx == Context::DiffNormal
        && let ViewMode::Diff(ref diff) = app.view_mode
        && diff.is_branch_diff
        && let Some(actions::Action::EnterPatchMode) = action_for_key(ctx, key)
    {
        return;
    }

    if let Some(action) = action_for_key(ctx, key) {
        let refreshed_preview = apply_action(app, action);
        if refreshed_preview {
            *last_preview_refresh = std::time::Instant::now();
        }
    }
}