tmx-cli 1.0.1

Project-aware tmux session manager
Documentation
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
use std::io::Write;
use std::path::Path;

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};

use crate::agents;
use crate::config::{self, Config};
use crate::project::{self};
use crate::shell_init;
use crate::tmux;
use crate::ui;
use crate::worktree::{self, RemoveDecision};

#[derive(Parser, Debug)]
#[command(
    name = "tmx",
    about = "Project-aware tmux session manager",
    long_about = "Scan project directories, show git status, and manage tmux sessions with project-type layouts.",
    version
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Show a live dashboard of agents running in tmux panes
    #[command(
        long_about = "Open a terminal dashboard listing every tmux pane and any Claude/Codex agent\nrunning inside it, plus codex-companion background jobs. Reads tmux + local\nstate (~/.claude/state/), no daemon required. Works the same in GUI tmux and\nover SSH.\n\nKeys:\n  j/k or ↑/↓   navigate\n  enter        switch tmux client to the selected pane\n  q / esc      quit\n\nWith --json: skip the TUI, emit one snapshot to stdout as JSON and exit.\nUseful for agent-driven consumers (jq, scripts, other LLMs)."
    )]
    Agents {
        /// Emit one snapshot to stdout as JSON instead of opening the TUI.
        #[arg(long)]
        json: bool,
    },

    /// Kill all unattached tmux sessions
    Cleanup,

    /// List all tmux sessions
    List {
        /// Emit the session list to stdout as JSON.
        #[arg(long)]
        json: bool,
    },

    /// Switch to a tmux session (interactive picker or by name)
    Switch {
        /// Optional session name. If provided, switch directly (creating if needed).
        session: Option<String>,
    },

    /// Manage git worktrees for the current repo
    Worktree {
        #[command(subcommand)]
        command: WorktreeCommand,
    },

    /// Emit shell integration code (defines the 'twt' wrapper)
    #[command(
        name = "shell-init",
        long_about = "Emit shell initialization code that defines a 'twt' function\nrouting to 'tmx worktree …'.\n\nAdd to your shell rc:\n\n    eval \"$(tmx shell-init zsh)\"\n\nThen:\n\n    twt feat-x                 # create worktree + spawn/switch tmux session (default)\n    twt feat-x --keep-current  # create only; cd into the new worktree (no tmux switch)\n    twt feat-x -p              # create only; print path (no cd, no tmux switch)\n    twt rm [target]            # remove a worktree (picker if no target)\n    twt list                   # picker → cd into the selected worktree\n    twt list <target>          # cd into the named worktree (path or short branch)\n    twt list --plain           # dump all worktrees as plain text (no cd)\n\nSupported shells: zsh."
    )]
    ShellInit {
        /// Shell name (currently only 'zsh')
        shell: String,
    },
}

#[derive(Subcommand, Debug)]
enum WorktreeCommand {
    /// Create a sibling git worktree for the current repo
    #[command(
        long_about = "Create a sibling git worktree, optionally run a post-create command,\nand by default spawn a tmux session at the new worktree and switch to it.\n\nWorktree is placed next to the source repo (sibling), named via the\n'worktree.naming' template in ~/.config/tmx/config.toml\n(default: '{repo}-{branch}'). Slashes in branch names are replaced\nwith dashes for the directory name.\n\nWith --keep-current, no tmux session is created and the worktree path is\nprinted on stdout (useful for shell wrappers that cd into the new path)."
    )]
    Create {
        /// New branch to create (also used to derive the directory name)
        branch: String,

        /// Do not spawn / switch to a tmux session for the new worktree;
        /// just create it and print the path on stdout.
        #[arg(long = "keep-current")]
        keep_current: bool,

        /// Base ref for the new branch (default: HEAD)
        #[arg(long = "from")]
        from: Option<String>,
    },

    /// List worktrees and print the chosen path on stdout
    #[command(
        long_about = "Print a worktree path on stdout, intended for shell wrappers (`cd \"$(tmx worktree list)\"`).\n\nWith no target, an interactive picker is shown on stderr (so stdout stays clean for `$(...)` capture).\nWith a target (path or short branch), the resolved path is printed directly.\nWith --plain, all worktrees are dumped as 'path  branch  [flags]' lines on stdout.\nWith --json, all worktrees (or just the resolved target) are emitted as a JSON array."
    )]
    List {
        /// Worktree path or short branch name. Picker shown if omitted.
        target: Option<String>,

        /// Dump all worktrees as plain text instead of running the picker.
        #[arg(long = "plain", conflicts_with = "json")]
        plain: bool,

        /// Emit worktrees to stdout as a JSON array.
        #[arg(long)]
        json: bool,
    },

    /// Remove a sibling git worktree (fuzzy picker if no target given)
    #[command(
        long_about = "Remove a worktree by exact path or short branch name (e.g. 'feat-x').\nIf no target is provided, an interactive picker is shown.\n\nSafety rules (apply even with --force):\n  - Locked worktrees are refused; run 'git worktree unlock' first.\n  - The worktree containing the current working directory is refused.\n  - The worktree containing the current tmux session is refused.\n\nWithout --force, any tmux session attached to the worktree blocks removal.\nWith --force, attached sessions are killed (by id) and 'git worktree remove --force'\nis used (covers dirty worktrees)."
    )]
    Rm {
        /// Worktree path or short branch name. Picker shown if omitted.
        target: Option<String>,

        /// Kill conflicting sessions and pass --force to git.
        #[arg(short = 'f', long = "force")]
        force: bool,
    },
}

pub fn run() -> Result<()> {
    config::ensure_config_dir();
    let cli = Cli::parse();
    match cli.command {
        None => run_selector(),
        Some(Command::Agents { json }) => run_agents(json),
        Some(Command::Cleanup) => run_cleanup(),
        Some(Command::List { json }) => run_list(json),
        Some(Command::Switch { session }) => run_switch(session.as_deref()),
        Some(Command::Worktree { command }) => match command {
            WorktreeCommand::Create {
                branch,
                keep_current,
                from,
            } => run_worktree_create(&branch, keep_current, from.as_deref().unwrap_or("")),
            WorktreeCommand::List {
                target,
                plain,
                json,
            } => run_worktree_list(target.as_deref(), plain, json),
            WorktreeCommand::Rm { target, force } => run_worktree_rm(target.as_deref(), force),
        },
        Some(Command::ShellInit { shell }) => run_shell_init(&shell),
    }
}

fn run_selector() -> Result<()> {
    let cfg = Config::load();
    let projects = project::scan_projects(&cfg);
    if projects.is_empty() {
        println!("No projects found. Configure roots in ~/.config/tmx/config.toml");
        println!("Example: roots = [\"~/dev\"]");
        return Ok(());
    }

    let selected = ui::run_project_selector(projects)?;
    let Some(project) = selected else {
        return Ok(());
    };
    ui::open_project(&project)
}

fn run_agents(json: bool) -> Result<()> {
    if json {
        let mut proc = agents::proc::ProcSnapshot::new();
        proc.refresh();
        let snapshot = agents::collector::collect(&proc);
        let stdout = std::io::stdout();
        let mut handle = stdout.lock();
        serde_json::to_writer_pretty(&mut handle, &snapshot).context("serialise snapshot")?;
        writeln!(handle).ok();
        return Ok(());
    }
    agents::run()
}

fn run_cleanup() -> Result<()> {
    let killed = tmux::cleanup_sessions().context("cleanup failed")?;
    if killed.is_empty() {
        println!("No unattached sessions to clean up.");
    } else {
        println!("Killed {} session(s): {}", killed.len(), killed.join(", "));
    }
    Ok(())
}

fn run_list(json: bool) -> Result<()> {
    // In JSON mode we always emit a (possibly empty) array — even when tmux
    // isn't running. Consumers parse a single shape regardless of state.
    if json {
        let sessions = tmux::list_sessions().unwrap_or_default();
        let stdout = std::io::stdout();
        let mut handle = stdout.lock();
        serde_json::to_writer_pretty(&mut handle, &sessions).context("serialise sessions")?;
        writeln!(handle).ok();
        return Ok(());
    }

    let sessions = match tmux::list_sessions() {
        Ok(s) => s,
        Err(_) => {
            println!("No tmux server running.");
            return Ok(());
        }
    };
    if sessions.is_empty() {
        println!("No active sessions.");
        return Ok(());
    }
    for s in sessions {
        let attached = if s.attached { " (attached)" } else { "" };
        println!("  {} — {} window(s){}", s.name, s.windows, attached);
    }
    Ok(())
}

fn run_switch(name: Option<&str>) -> Result<()> {
    if let Some(name) = name {
        if !tmux::session_exists(name) {
            tmux::create_session(name, "").context("failed to create session")?;
        }
        return tmux::switch_session(name).context("failed to switch session");
    }

    let sessions = match tmux::list_sessions() {
        Ok(s) if !s.is_empty() => s,
        _ => {
            println!("No active tmux sessions.");
            return Ok(());
        }
    };

    let Some(selected) = ui::run_session_switcher(sessions)? else {
        return Ok(());
    };
    tmux::switch_session(&selected.name).context("failed to switch session")
}

fn run_worktree_create(branch: &str, keep_current: bool, from: &str) -> Result<()> {
    let cfg = Config::load();
    let res = worktree::create(
        worktree::Options {
            branch: branch.to_string(),
            from: from.to_string(),
            start_in: String::new(),
        },
        &cfg,
    )?;

    eprintln!("Created worktree: {}", res.worktree_path.display());
    if !res.script_ran.is_empty() {
        eprintln!("Ran post-create command: {}", res.script_ran);
    }

    if keep_current {
        // Print the path on stdout so callers can `cd "$(tmx worktree create … --keep-current)"`.
        println!("{}", res.worktree_path.display());
        return Ok(());
    }

    let session_name = tmux::safe_session_name(&res.repo_name, branch);
    if !tmux::session_exists(&session_name) {
        tmux::create_session(&session_name, &res.worktree_path.to_string_lossy())
            .context("create tmux session")?;
    }
    tmux::switch_session(&session_name).context("switch tmux session")
}

fn run_worktree_list(target: Option<&str>, plain: bool, json: bool) -> Result<()> {
    let cwd = std::env::current_dir().context("resolve cwd")?;
    let entries = worktree::list_entries(&cwd)?;

    // `--json` always emits a JSON array, even with a target (1-element)
    // and even when the repo has only its main worktree (single entry).
    // Consumers can rely on the shape without branching on count.
    if json {
        let payload: Vec<&worktree::WorktreeEntry> = if let Some(t) = target {
            vec![worktree::resolve_target_any(&entries, t)?]
        } else {
            entries.iter().collect()
        };
        let stdout = std::io::stdout();
        let mut handle = stdout.lock();
        serde_json::to_writer_pretty(&mut handle, &payload).context("serialise worktrees")?;
        writeln!(handle).ok();
        return Ok(());
    }

    if plain {
        for e in &entries {
            let branch = e
                .branch
                .as_deref()
                .map(worktree::short_branch)
                .unwrap_or("(detached)");
            let mut flags: Vec<&str> = Vec::new();
            if e.is_main {
                flags.push("main");
            }
            if e.locked {
                flags.push("locked");
            }
            if e.prunable {
                flags.push("prunable");
            }
            let suffix = if flags.is_empty() {
                String::new()
            } else {
                format!("  [{}]", flags.join(","))
            };
            println!("{}\t{}{}", e.path.display(), branch, suffix);
        }
        return Ok(());
    }

    if let Some(t) = target {
        // `list` is non-destructive, so the main worktree is a valid target.
        let entry = worktree::resolve_target_any(&entries, t)?;
        println!("{}", entry.path.display());
        return Ok(());
    }

    if entries.is_empty() {
        return Ok(());
    }

    let Some(selected) = ui::run_worktree_picker(entries)? else {
        return Ok(());
    };
    println!("{}", selected.path.display());
    Ok(())
}

fn run_worktree_rm(target: Option<&str>, force: bool) -> Result<()> {
    let cwd = std::env::current_dir().context("resolve cwd")?;
    let entries = worktree::list_entries(&cwd)?;

    let entry: worktree::WorktreeEntry = match target {
        Some(t) => worktree::resolve_target(&entries, t)?.clone(),
        None => {
            let removable: Vec<worktree::WorktreeEntry> =
                entries.iter().filter(|e| !e.is_main).cloned().collect();
            if removable.is_empty() {
                println!("No removable worktrees.");
                return Ok(());
            }
            let Some(selected) = ui::run_worktree_picker(removable)? else {
                return Ok(());
            };
            selected
        }
    };

    rm_preflight_and_remove(&entry, force, &cwd)
}

fn rm_preflight_and_remove(entry: &worktree::WorktreeEntry, force: bool, cwd: &Path) -> Result<()> {
    // Step 1: locked preflight.
    if worktree::remove_decision(entry) == RemoveDecision::LockedRefuse {
        bail!(
            "worktree is locked: {}\nrun `git worktree unlock {}` first.",
            entry.path.display(),
            entry.path.display()
        );
    }

    // Step 2: missing-target shortcut. Skip cwd / tmux checks and hand to git.
    let target_canon = entry.path.canonicalize().ok();
    if target_canon.is_none() {
        return worktree::remove(&entry.path, force);
    }
    let target_canon = target_canon.unwrap();

    // Step 3: self-cwd guard.
    let cwd_canon = cwd.canonicalize().context("canonicalize cwd")?;
    if is_inside(&cwd_canon, &target_canon) {
        bail!(
            "refusing to remove worktree containing the current working directory.\ncd out of {} first, then re-run.",
            entry.path.display()
        );
    }

    // Step 4: self-session guard + conflict gate.
    let in_tmux = std::env::var_os("TMUX").is_some();
    let current_session = if in_tmux {
        match tmux::current_session_id() {
            Some(id) => Some(id),
            None => bail!("cannot determine current tmux session id; refusing to proceed"),
        }
    } else {
        None
    };

    let attached: Vec<worktree::AttachedSession> =
        match worktree::sessions_attached_to(&target_canon) {
            Ok(v) => v,
            Err(e) => {
                if in_tmux {
                    bail!(
                        "tmux query failed while inside a tmux session; refusing to proceed: {e}"
                    );
                } else {
                    Vec::new()
                }
            }
        };

    if let Some(cur) = current_session.as_deref()
        && attached.iter().any(|s| s.id == cur)
    {
        bail!(
            "refusing to remove worktree containing the current tmux session.\nswitch to a different session first, then re-run."
        );
    }

    if !attached.is_empty() {
        if !force {
            let names: Vec<String> = attached.iter().map(|s| s.name.clone()).collect();
            bail!(
                "worktree {} is in use by tmux session(s): {}\npass --force to kill them and proceed",
                entry.path.display(),
                names.join(", ")
            );
        }
        for s in &attached {
            tmux::kill_session_id(&s.id)
                .with_context(|| format!("kill-session {} ({})", s.id, s.name))?;
            eprintln!("killed tmux session: {} ({})", s.name, s.id);
        }
    }

    worktree::remove(&entry.path, force)
}

fn is_inside(child: &Path, parent: &Path) -> bool {
    if child == parent {
        return true;
    }
    let c = child.to_string_lossy();
    let p = parent.to_string_lossy();
    let p = p.trim_end_matches('/');
    if let Some(rest) = c.strip_prefix(p)
        && rest.starts_with('/')
    {
        return true;
    }
    false
}

fn run_shell_init(shell: &str) -> Result<()> {
    match shell_init::emit(shell) {
        Ok(text) => {
            print!("{text}");
            Ok(())
        }
        Err(e) => bail!("{e}"),
    }
}