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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
use crate::command::args::{MultiArgs, PromptArgs, RescueArgs, SetupFlags};
use crate::{claude, command, config, git, nerdfont};
use anyhow::{Context, Result};
use clap::error::{ContextKind, ContextValue, ErrorKind};
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{Shell, generate};
#[derive(Clone, Debug)]
struct WorktreeBranchParser;
impl WorktreeBranchParser {
fn new() -> Self {
Self
}
fn get_branches(&self) -> Vec<String> {
// Don't attempt completions if not in a git repo.
if !git::is_git_repo().unwrap_or(false) {
return Vec::new();
}
let worktrees = match git::list_worktrees() {
Ok(wt) => wt,
// Fail silently on completion; don't disrupt the user's shell.
Err(_) => return Vec::new(),
};
let main_branch = git::get_default_branch().ok();
worktrees
.into_iter()
.map(|(_, branch)| branch)
// Filter out the main branch, as it's not a candidate for merging/removing.
.filter(|branch| main_branch.as_deref() != Some(branch.as_str()))
// Filter out detached HEAD states.
.filter(|branch| branch != "(detached)")
.collect()
}
}
impl clap::builder::TypedValueParser for WorktreeBranchParser {
type Value = String;
fn parse_ref(
&self,
cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
// Use the default string parser for validation.
clap::builder::StringValueParser::new().parse_ref(cmd, None, value)
}
fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
// Return None to avoid running git operations during completion script generation.
// Dynamic completions are handled by the _complete-branches subcommand,
// which is called by the shell only when the user presses TAB.
None
}
}
/// Parser for worktree handles (directory names), used for open/path/remove commands.
#[derive(Clone, Debug)]
struct WorktreeHandleParser;
impl WorktreeHandleParser {
fn new() -> Self {
Self
}
fn get_handles() -> Vec<String> {
// Don't attempt completions if not in a git repo.
if !git::is_git_repo().unwrap_or(false) {
return Vec::new();
}
let worktrees = match git::list_worktrees() {
Ok(wt) => wt,
// Fail silently on completion; don't disrupt the user's shell.
Err(_) => return Vec::new(),
};
let main_worktree_root = git::get_main_worktree_root().ok();
worktrees
.into_iter()
.filter_map(|(path, _)| {
// Filter out the main worktree
if main_worktree_root.as_ref() == Some(&path) {
return None;
}
// Extract directory name as the handle
path.file_name()
.map(|name| name.to_string_lossy().to_string())
})
.collect()
}
}
impl clap::builder::TypedValueParser for WorktreeHandleParser {
type Value = String;
fn parse_ref(
&self,
cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
// Use the default string parser for validation.
clap::builder::StringValueParser::new().parse_ref(cmd, None, value)
}
fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
// Return None to avoid running git operations during completion script generation.
// Dynamic completions are handled by the _complete-handles subcommand,
// which is called by the shell only when the user presses TAB.
None
}
}
/// Parser for agent targets, used for send/capture/status/wait/run commands.
///
/// Includes local worktree handles plus active agents from other projects.
/// Cross-project agents appear as `project:handle` when their name would be ambiguous.
#[derive(Clone, Debug)]
struct AgentTargetParser;
impl AgentTargetParser {
fn new() -> Self {
Self
}
fn get_targets() -> Vec<String> {
// Start with local worktree handles
let mut targets = WorktreeHandleParser::get_handles();
// Also include the main worktree handle (agents can run there too)
if git::is_git_repo().unwrap_or(false)
&& let Ok(main_root) = git::get_main_worktree_root()
&& let Some(name) = main_root.file_name()
{
let handle = name.to_string_lossy().to_string();
if !targets.contains(&handle) {
targets.push(handle);
}
}
// Append global agent handles from reconciled state
let mux = crate::multiplexer::create_backend(crate::multiplexer::detect_backend());
if let Ok(store) = crate::state::StateStore::new()
&& let Ok(agents) = store.load_reconciled_agents(mux.as_ref())
{
for agent in &agents {
let root = crate::workflow::find_worktree_root(&agent.path)
.unwrap_or_else(|| agent.path.clone());
if let Some(name) = root.file_name() {
let handle = name.to_string_lossy().to_string();
if !targets.contains(&handle) {
targets.push(handle.clone());
}
// Also add qualified project:handle for disambiguation
if let Some(parent) = root.parent()
&& let Some(proj) = parent.file_name()
{
let qualified = format!("{}:{}", proj.to_string_lossy(), handle);
if !targets.contains(&qualified) {
targets.push(qualified);
}
}
}
}
}
targets.sort();
targets.dedup();
targets
}
}
impl clap::builder::TypedValueParser for AgentTargetParser {
type Value = String;
fn parse_ref(
&self,
cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
clap::builder::StringValueParser::new().parse_ref(cmd, None, value)
}
fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
// Dynamic completions handled by _complete-agent-targets subcommand
None
}
}
#[derive(Clone, Debug)]
struct GitBranchParser;
impl GitBranchParser {
fn new() -> Self {
Self
}
fn get_branches() -> Vec<String> {
// Don't attempt completions if not in a git repo.
if !git::is_git_repo().unwrap_or(false) {
return Vec::new();
}
// Fail silently on completion; don't disrupt the user's shell.
git::list_checkout_branches().unwrap_or_default()
}
}
impl clap::builder::TypedValueParser for GitBranchParser {
type Value = String;
fn parse_ref(
&self,
cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
// Use the default string parser for validation.
clap::builder::StringValueParser::new().parse_ref(cmd, None, value)
}
fn possible_values(
&self,
) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
// Return None to avoid running git operations during completion script generation.
// Dynamic completions are handled by the _complete-git-branches subcommand,
// which is called by the shell only when the user presses TAB.
None
}
}
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(name = "workmux")]
#[command(about = "An opinionated workflow tool that orchestrates git worktrees and tmux")]
#[command(help_template = "\
{about}
{usage-heading} {usage}
Worktree lifecycle:
add Create a new worktree and tmux window
remove Remove a worktree, tmux window, and branch without merging [rm]
merge Merge a branch, then clean up the worktree and tmux window
open Open a tmux window for an existing worktree
close Close a worktree's tmux window (keeps the worktree and branch)
resurrect Restore worktree windows after a tmux or computer crash
Monitoring:
dashboard Show a TUI dashboard of all active workmux agents
sidebar Toggle a live agent status sidebar in tmux
list List all worktrees [ls]
path Get the filesystem path of a worktree
status Query agent status for worktrees
Setup and configuration:
init Generate example .workmux.yaml configuration file
setup Set up agent status tracking hooks and install skills
config Manage global configuration
sandbox Manage sandbox settings
sync-files Re-apply file operations (copy/symlink) to worktrees
claude Claude Code integration commands
Agent interaction:
send Send a prompt or instruction to a running agent
capture Capture terminal output from a running agent
wait Wait for agents to reach a target status
run Run a command in a worktree's window
Help and updates:
docs Show detailed documentation (renders README.md)
changelog Show the changelog (what's new in each version)
update Update workmux to the latest version
completions Generate shell completions
help Print help for a command
Options:
-h, --help Print help
-V, --version Print version
Run 'workmux docs' for detailed documentation.
")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Create a new worktree and tmux window
Add {
/// Name of the branch (creates if it doesn't exist) or remote ref (e.g., origin/feature).
/// When used with --pr, this becomes the custom local branch name.
#[arg(required_unless_present_any = ["pr", "auto_name"], value_parser = GitBranchParser::new())]
branch_name: Option<String>,
/// Pull request number to checkout
#[arg(long, conflicts_with_all = ["base", "auto_name"])]
pr: Option<u32>,
/// Generate branch name from prompt using LLM
#[arg(short = 'A', long = "auto-name", conflicts_with = "pr")]
auto_name: bool,
/// Base branch/commit/tag to branch from (overrides config base_branch, defaults to current branch)
#[arg(long)]
base: Option<String>,
/// Explicit name for the worktree directory and tmux window (overrides worktree_naming strategy and worktree_prefix)
#[arg(long)]
name: Option<String>,
#[command(flatten)]
prompt: PromptArgs,
#[command(flatten)]
setup: SetupFlags,
#[command(flatten)]
rescue: RescueArgs,
#[command(flatten)]
multi: MultiArgs,
/// Use a named pane layout from config instead of default panes
#[arg(short = 'l', long, conflicts_with = "agent")]
layout: Option<String>,
/// Fork the last conversation from the current worktree into the new one.
/// Specify a session ID to fork a specific conversation, or omit for most recent.
#[arg(long, num_args = 0..=1, default_missing_value = "", require_equals = true)]
fork: Option<String>,
/// Block until the created tmux window is closed
#[arg(short = 'W', long)]
wait: bool,
/// Create the window in its own tmux session (useful for session-per-project workflows)
#[arg(short = 's', long)]
session: bool,
},
/// Open a tmux window for an existing worktree
Open {
/// Worktree name(s) (directory name, visible in tmux window). Optional with --new.
#[arg(value_parser = WorktreeHandleParser::new(), required_unless_present = "new")]
names: Vec<String>,
/// Re-run post-create hooks (e.g., pnpm install)
#[arg(long)]
run_hooks: bool,
/// Re-apply file operations (copy/symlink)
#[arg(long)]
force_files: bool,
/// Force opening in a new window (creates suffix like -2, -3) instead of switching to existing
#[arg(long, short = 'n', conflicts_with = "session")]
new: bool,
/// Open in session mode (overrides stored mode for this worktree)
#[arg(short = 's', long)]
session: bool,
/// Resume the agent's most recent conversation in this worktree
#[arg(short = 'c', long = "continue")]
continue_session: bool,
#[command(flatten)]
prompt: PromptArgs,
},
/// Close a worktree's tmux window (keeps the worktree and branch)
Close {
/// Worktree name (defaults to current directory if omitted)
#[arg(value_parser = WorktreeHandleParser::new())]
name: Option<String>,
},
/// Restore worktree windows after a tmux or computer crash
///
/// Uses persisted agent state files to detect which worktrees had active
/// agents before the crash.
Resurrect {
/// Show what would be restored without doing it
#[arg(long)]
dry_run: bool,
},
/// Merge a branch, then clean up the worktree and tmux window
Merge {
/// Worktree name or branch (defaults to current directory)
#[arg(value_parser = WorktreeHandleParser::new())]
name: Option<String>,
/// The target branch to merge into (defaults to main_branch from config)
#[arg(long, value_parser = GitBranchParser::new())]
into: Option<String>,
/// Ignore uncommitted and staged changes
#[arg(long)]
ignore_uncommitted: bool,
/// Rebase the branch onto the main branch before merging (fast-forward)
#[arg(long, group = "merge_strategy")]
rebase: bool,
/// Squash all commits from the branch into a single commit on the main branch
#[arg(long, group = "merge_strategy")]
squash: bool,
/// Keep the worktree, window, and branch after merging (skip cleanup)
#[arg(short = 'k', long)]
keep: bool,
/// Skip running pre-merge hooks
#[arg(short = 'n', long)]
no_verify: bool,
/// Skip running all hooks (pre-merge and pre-remove)
#[arg(long)]
no_hooks: bool,
/// Show a system notification on successful merge
#[arg(long)]
notification: bool,
},
/// Remove a worktree, tmux window, and branch without merging
#[command(visible_alias = "rm")]
Remove {
/// Worktree names (defaults to current directory name if empty)
#[arg(value_parser = WorktreeHandleParser::new(), conflicts_with_all = ["gone", "all"], num_args = 0..)]
names: Vec<String>,
/// Remove worktrees whose upstream remote branch has been deleted (e.g., after PR merge)
#[arg(long, conflicts_with = "all")]
gone: bool,
/// Remove all worktrees (except the main worktree)
#[arg(long)]
all: bool,
/// Skip confirmation and ignore uncommitted changes
#[arg(short, long)]
force: bool,
/// Keep the local branch (only remove worktree and tmux window)
#[arg(short = 'k', long)]
keep_branch: bool,
},
/// List all worktrees
#[command(visible_alias = "ls")]
List {
/// Show PR status for each worktree (requires gh CLI)
#[arg(long)]
pr: bool,
/// Output as JSON
#[arg(long)]
json: bool,
/// Filter by worktree name or branch (supports multiple)
#[arg(value_parser = WorktreeBranchParser::new())]
filter: Vec<String>,
},
/// Get the filesystem path of a worktree
Path {
/// Worktree name (directory name)
#[arg(value_parser = WorktreeHandleParser::new())]
name: String,
},
/// Send a prompt or instruction to a running agent
Send {
/// Worktree name (supports cross-project with project:handle syntax)
#[arg(value_parser = AgentTargetParser::new())]
name: String,
/// Text to send (reads from --file or stdin if omitted)
#[arg(conflicts_with = "file")]
text: Option<String>,
/// Read prompt from file
#[arg(short, long, conflicts_with = "text")]
file: Option<String>,
},
/// Capture terminal output from a running agent
Capture {
/// Worktree name (supports cross-project with project:handle syntax)
#[arg(value_parser = AgentTargetParser::new())]
name: String,
/// Number of lines to capture
#[arg(short = 'n', long, default_value = "200")]
lines: u16,
},
/// Query agent status for worktrees
Status {
/// Worktree names (supports cross-project with project:handle syntax)
#[arg(value_parser = AgentTargetParser::new())]
worktrees: Vec<String>,
/// Output as JSON
#[arg(long)]
json: bool,
/// Include git info (staged/unstaged changes, unmerged commits)
#[arg(long)]
git: bool,
},
/// Wait for agents to reach a target status
Wait {
/// Worktree names (supports cross-project with project:handle syntax)
#[arg(required = true, value_parser = AgentTargetParser::new())]
worktrees: Vec<String>,
/// Target status to wait for
#[arg(long, default_value = "done")]
status: String,
/// Maximum wait time in seconds
#[arg(long)]
timeout: Option<u64>,
/// Return when ANY worktree reaches target (default: wait for ALL)
#[arg(long)]
any: bool,
},
/// Run a command in a worktree's window
Run {
/// Worktree name (supports cross-project with project:handle syntax)
#[arg(value_parser = AgentTargetParser::new())]
name: String,
/// Command to run (everything after --)
#[arg(last = true, required = true)]
command: Vec<String>,
/// Run in background without waiting (default: wait and stream output)
#[arg(short = 'b', long)]
background: bool,
/// Keep run artifacts after completion (for debugging)
#[arg(long)]
keep: bool,
/// Maximum wait time in seconds
#[arg(long)]
timeout: Option<u64>,
},
/// Re-apply file operations (copy/symlink) to worktrees
#[command(name = "sync-files")]
SyncFiles {
/// Sync all worktrees instead of just the current one
#[arg(long)]
all: bool,
},
/// Generate example .workmux.yaml configuration file
Init,
/// Set up agent status tracking hooks and install skills
Setup {
/// Only set up status tracking hooks
#[arg(long)]
hooks: bool,
/// Only install skills
#[arg(long)]
skills: bool,
},
/// Show detailed documentation (renders README.md)
Docs,
/// Show the changelog (what's new in each version)
Changelog,
/// Update workmux to the latest version
Update,
/// Toggle a live agent status sidebar in tmux
Sidebar {
/// Scope sidebar to current tmux session only
#[arg(short = 's', long)]
session: bool,
#[command(subcommand)]
action: Option<SidebarAction>,
},
/// Run the sidebar TUI (internal use)
#[command(hide = true, name = "_sidebar-run")]
SidebarRun,
/// Sync sidebar into a window (internal use, called by tmux hooks)
#[command(hide = true, name = "_sidebar-sync")]
SidebarSync {
/// Target window ID (from tmux hook context)
#[arg(long)]
window: Option<String>,
},
/// Reflow sidebar layout after window resize (internal use, called by tmux hooks)
#[command(hide = true, name = "_sidebar-reflow")]
SidebarReflow {
/// Target window ID
#[arg(long)]
window: Option<String>,
},
/// Run the sidebar daemon (internal use)
#[command(hide = true, name = "_sidebar-daemon")]
SidebarDaemon,
/// Show a TUI dashboard of all active workmux agents across all sessions
Dashboard {
/// Preview pane size as percentage (10-90). Larger = more preview, less table.
#[arg(long, short = 'P', value_parser = clap::value_parser!(u8).range(10..=90))]
preview_size: Option<u8>,
/// Open diff view directly for the current worktree
#[arg(long, short = 'd')]
diff: bool,
/// Filter to only show agents in the current session
#[arg(short = 's', long)]
session: bool,
/// Open directly on the specified tab
#[arg(long, short = 't', value_enum)]
tab: Option<command::dashboard::DashboardTab>,
},
/// Manage global configuration
Config(command::config::ConfigArgs),
/// Claude Code integration commands
Claude {
#[command(subcommand)]
command: ClaudeCommands,
},
/// Manage sandbox settings
Sandbox(command::sandbox::SandboxArgs),
/// Set agent status for the current tmux window (used by hooks)
#[command(hide = true)]
SetWindowStatus {
#[arg(value_enum)]
command: command::set_window_status::SetWindowStatusCommand,
},
/// Set the base branch for the current worktree (used after rebasing)
#[command(hide = true, name = "set-base")]
SetBase {
/// The new base branch
#[arg(value_parser = GitBranchParser::new())]
base: String,
},
/// Execute a run spec (internal use)
#[command(hide = true, name = "_exec")]
Exec {
/// Absolute path to run directory
#[arg(long)]
run_dir: std::path::PathBuf,
},
/// Switch to the agent that most recently completed or is waiting for input
#[command(hide = true, name = "last-done")]
LastDone,
/// Switch to the last visited agent (toggle between two)
#[command(hide = true, name = "last-agent")]
LastAgent,
/// Execute a command on the host (used by guest shims)
#[command(hide = true, name = "host-exec")]
HostExec {
/// Command name and arguments
#[arg(trailing_var_arg = true, allow_hyphen_values = true, required = true)]
args: Vec<String>,
},
/// Read clipboard from host (used by sandbox clipboard shims)
#[command(hide = true, name = "clipboard-read")]
ClipboardRead {
/// MIME type to read
mime: String,
},
/// Generate shell completions
Completions {
/// The shell to generate completions for
#[arg(value_enum)]
shell: Shell,
},
/// Output worktree branch names for shell completion (internal use)
#[command(hide = true, name = "_complete-branches")]
CompleteBranches,
/// Output worktree handles for shell completion (internal use)
#[command(hide = true, name = "_complete-handles")]
CompleteHandles,
/// Output git branches for shell completion (internal use)
#[command(hide = true, name = "_complete-git-branches")]
CompleteGitBranches,
/// Output agent targets for shell completion (internal use)
///
/// Includes local worktree handles plus active agents from other projects.
#[command(hide = true, name = "_complete-agent-targets")]
CompleteAgentTargets,
/// Background update check (internal use)
#[command(hide = true, name = "_check-update")]
CheckUpdate,
}
#[derive(Subcommand, Debug)]
pub enum SidebarAction {
/// Switch to the next agent in sidebar order
Next,
/// Switch to the previous agent in sidebar order
Prev,
/// Jump to the Nth agent in sidebar order (1-indexed)
Jump {
/// Agent number (1-9)
#[arg(value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
index: u64,
},
}
#[derive(Subcommand)]
enum ClaudeCommands {
/// Remove stale entries from ~/.claude.json for deleted worktrees
Prune,
}
/// Check if the command should show the nerdfont setup prompt.
/// Only commands that display icons should trigger the prompt.
fn should_prompt_nerdfont(cmd: &Commands) -> bool {
matches!(
cmd,
Commands::Add { .. } | Commands::Init | Commands::Dashboard { .. } | Commands::List { .. }
)
}
/// Check if the command should show the status tracking setup wizard.
/// Excludes `Setup` to avoid double-prompting (the setup command handles its own flow).
/// Excludes `Dashboard` because the wizard prompt interferes with the TUI.
fn should_prompt_status_setup(cmd: &Commands) -> bool {
matches!(
cmd,
Commands::Add { .. } | Commands::Init | Commands::List { .. }
)
}
/// Check if the command should trigger a background update check.
fn should_check_update(cmd: &Commands) -> bool {
matches!(cmd, Commands::Add { .. })
}
// --- Public Entry Point ---
pub fn run() -> Result<()> {
let cli = match Cli::try_parse() {
Ok(cli) => cli,
Err(mut e) => {
// Filter hidden (underscore-prefixed) commands from "similar subcommands" suggestions.
// Workaround for https://github.com/clap-rs/clap/issues/4853
if e.kind() == ErrorKind::InvalidSubcommand {
let visible = e
.get(ContextKind::SuggestedSubcommand)
.and_then(|v| match v {
ContextValue::Strings(suggestions) => {
let filtered: Vec<String> = suggestions
.iter()
.filter(|s| !s.starts_with('_'))
.cloned()
.collect();
Some(filtered)
}
_ => None,
});
if let Some(visible) = visible {
e.insert(
ContextKind::SuggestedSubcommand,
ContextValue::Strings(visible),
);
}
}
e.exit()
}
};
// Always initialize nerdfont setting for prefix consistency across commands.
// Only prompt interactively for commands that display icons.
// If config fails to load, skip the nerdfont wizard -- it will be shown on
// the next successful run and the real error surfaces when the command loads
// config with `?`.
let (cfg, config_ok) = match config::Config::load(None) {
Ok(cfg) => (cfg, true),
Err(_) => (config::Config::default(), false),
};
let has_pua = nerdfont::config_has_pua(&cfg);
let nerdfont_enabled = if cfg.nerdfont.is_some() || has_pua {
// Already configured or PUA detected
cfg.nerdfont.unwrap_or(has_pua)
} else if config_ok && should_prompt_nerdfont(&cli.command) {
// Prompt user (returns None in non-interactive mode)
nerdfont::check_and_prompt(&cfg)?.unwrap_or(false)
} else {
false
};
nerdfont::init(Some(nerdfont_enabled), has_pua);
// Check agent status tracking setup after nerdfont.
// Uses a separate gate to avoid double-prompting when running `workmux setup`.
if config_ok
&& should_prompt_status_setup(&cli.command)
&& let Err(e) = crate::agent_setup::prompt_wizard()
{
tracing::debug!(?e, "status setup wizard failed");
}
// Background update check: reads local cache, optionally shows a notice,
// and spawns a background process to refresh the cache if stale.
if should_check_update(&cli.command) {
command::update::check_and_notify(&cfg);
}
match cli.command {
Commands::Add {
branch_name,
pr,
auto_name,
base,
name,
prompt,
setup,
rescue,
multi,
layout,
fork,
wait,
session,
} => command::add::run(
branch_name.as_deref(),
pr,
auto_name,
base.as_deref(),
name,
prompt,
setup,
rescue,
multi,
layout,
fork,
wait,
session,
),
Commands::Open {
names,
run_hooks,
force_files,
new,
session,
continue_session,
prompt,
} => command::open::run(
&names,
run_hooks,
force_files,
new,
session,
continue_session,
prompt,
),
Commands::Close { name } => command::close::run(name.as_deref()),
Commands::Resurrect { dry_run } => command::resurrect::run(dry_run),
Commands::Merge {
name,
into,
ignore_uncommitted,
rebase,
squash,
keep,
no_verify,
no_hooks,
notification,
} => command::merge::run(
name.as_deref(),
into.as_deref(),
ignore_uncommitted,
rebase,
squash,
keep,
no_verify,
no_hooks,
notification,
),
Commands::Remove {
names,
gone,
all,
force,
keep_branch,
} => command::remove::run(names, gone, all, force, keep_branch),
Commands::List { pr, json, filter } => command::list::run(pr, json, &filter),
Commands::Path { name } => command::path::run(&name),
Commands::Send { name, text, file } => {
command::send::run(&name, text.as_deref(), file.as_deref())
}
Commands::Capture { name, lines } => command::capture::run(&name, lines),
Commands::Status {
worktrees,
json,
git,
} => command::status::run(&worktrees, json, git),
Commands::Wait {
worktrees,
status,
timeout,
any,
} => command::wait::run(&worktrees, &status, timeout, any),
Commands::Run {
name,
command,
background,
keep,
timeout,
} => command::run::run(&name, command, background, keep, timeout),
Commands::Exec { run_dir } => command::exec::run(&run_dir),
Commands::SyncFiles { all } => command::sync_files::run(all),
Commands::Init => crate::config::Config::init(),
Commands::Setup { hooks, skills } => command::setup::run(hooks, skills),
Commands::Docs => command::docs::run(),
Commands::Changelog => command::changelog::run(),
Commands::Update => command::update::run(),
Commands::Sidebar { session, action } => match action {
Some(SidebarAction::Next) => {
command::sidebar::navigate(command::sidebar::NavAction::Next)
}
Some(SidebarAction::Prev) => {
command::sidebar::navigate(command::sidebar::NavAction::Prev)
}
Some(SidebarAction::Jump { index }) => {
command::sidebar::navigate(command::sidebar::NavAction::Jump(index as usize))
}
None => {
if session {
command::sidebar::toggle_session()
} else {
command::sidebar::toggle()
}
}
},
Commands::SidebarRun => command::sidebar::run_sidebar(),
Commands::SidebarSync { window } => command::sidebar::sync(window.as_deref()),
Commands::SidebarReflow { window } => command::sidebar::reflow(window.as_deref()),
Commands::SidebarDaemon => command::sidebar::run_daemon(),
Commands::Dashboard {
preview_size,
diff,
session,
tab,
} => command::dashboard::run(preview_size, diff, session, tab),
Commands::Config(args) => command::config::run(args),
Commands::Claude { command } => match command {
ClaudeCommands::Prune => prune_claude_config(),
},
Commands::Sandbox(args) => command::sandbox::run(args),
Commands::SetWindowStatus { command } => command::set_window_status::run(command),
Commands::SetBase { base } => command::set_base::run(&base),
Commands::LastDone => command::last_done::run(),
Commands::LastAgent => command::last_agent::run(),
Commands::HostExec { args } => {
let (command, cmd_args) = args
.split_first()
.ok_or_else(|| anyhow::anyhow!("host-exec requires a command name"))?;
let code = command::host_exec::run(command, cmd_args)?;
std::process::exit(code);
}
Commands::ClipboardRead { mime } => {
let code = command::clipboard_read::run(&mime)?;
std::process::exit(code);
}
Commands::Completions { shell } => {
generate_completions(shell);
Ok(())
}
Commands::CompleteBranches => {
for branch in WorktreeBranchParser::new().get_branches() {
println!("{branch}");
}
Ok(())
}
Commands::CompleteHandles => {
for handle in WorktreeHandleParser::get_handles() {
println!("{handle}");
}
Ok(())
}
Commands::CompleteGitBranches => {
for branch in GitBranchParser::get_branches() {
println!("{branch}");
}
Ok(())
}
Commands::CompleteAgentTargets => {
for target in AgentTargetParser::get_targets() {
println!("{target}");
}
Ok(())
}
Commands::CheckUpdate => command::update::run_background_check(),
}
}
fn prune_claude_config() -> Result<()> {
claude::prune_stale_entries().context("Failed to prune Claude configuration")?;
Ok(())
}
fn generate_completions(shell: Shell) {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
// Generate base completions
let mut buf = Vec::new();
generate(shell, &mut cmd, &name, &mut buf);
let base_script = String::from_utf8_lossy(&buf);
// Append dynamic branch completion for each shell
// Note: PowerShell and Elvish are not supported because clap_complete generates
// anonymous completers that can't be wrapped without breaking standard completions.
match shell {
Shell::Zsh => {
let base = prepare_zsh_base(&base_script, &name);
println!("{base}");
print_zsh_dynamic_completion();
}
_ => {
print!("{base_script}");
match shell {
Shell::Bash => print_bash_dynamic_completion(),
Shell::Fish => print_fish_dynamic_completion(),
_ => {}
}
}
}
}
/// Rename the clap-generated zsh completion function so the dynamic wrapper
/// (in `zsh_dynamic.zsh`) can take the primary `_workmux` name.
///
/// The dynamic wrapper needs to BE `_workmux` — the function zsh autoloads
/// from fpath. It delegates flag completion to `_workmux_base` (the renamed
/// clap output) and handles positional args with dynamic helpers.
///
/// The `replace("_{name}", "_{name}_base")` is precise: `_{name}` (with the
/// leading underscore) only appears as zsh function identifiers in clap's
/// output. Bare `{name}` in `#compdef`, `_describe` strings, `curcontext`,
/// and state names is unaffected.
fn prepare_zsh_base(script: &str, name: &str) -> String {
let fn_prefix = format!("_{name}");
let base_fn_prefix = format!("_{name}_base");
let script = script.replace(&fn_prefix, &base_fn_prefix);
// Strip the autoload/eval detection block clap appends at the end.
// After renaming it registers _workmux_base, which conflicts with our
// dynamic wrapper's own registration.
let funcstack_block = format!(
"\nif [ \"$funcstack[1]\" = \"{base_fn_prefix}\" ]; then\n \
{base_fn_prefix} \"$@\"\nelse\n \
compdef {base_fn_prefix} {name}\nfi\n"
);
match script.strip_suffix(&funcstack_block) {
Some(stripped) => stripped.to_string(),
None => script,
}
}
fn print_zsh_dynamic_completion() {
print!("{}", include_str!("scripts/completions/zsh_dynamic.zsh"));
}
fn print_bash_dynamic_completion() {
print!("{}", include_str!("scripts/completions/bash_dynamic.bash"));
}
fn print_fish_dynamic_completion() {
print!("{}", include_str!("scripts/completions/fish_dynamic.fish"));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prepare_zsh_base_renames_function_identifiers() {
let input = concat!(
"#compdef workmux\n",
"_workmux() {\n",
" \":: :_workmux_commands\"\n",
"}\n",
"(( $+functions[_workmux_commands] )) ||\n",
"_workmux_commands() {\n",
" _describe -t commands 'workmux commands' commands\n",
"}\n",
"\nif [ \"$funcstack[1]\" = \"_workmux\" ]; then\n",
" _workmux \"$@\"\n",
"else\n",
" compdef _workmux workmux\n",
"fi\n",
);
let result = prepare_zsh_base(input, "workmux");
// Function identifiers are renamed
assert!(result.contains("_workmux_base()"));
assert!(result.contains("_workmux_base_commands"));
assert!(!result.contains("_workmux()"));
// Bare "workmux" in #compdef and _describe strings is preserved
assert!(result.contains("#compdef workmux"));
assert!(result.contains("'workmux commands'"));
// funcstack block is stripped
assert!(!result.contains("funcstack"));
assert!(!result.contains("compdef _workmux_base"));
}
#[test]
fn prepare_zsh_base_preserves_state_and_curcontext() {
let input = concat!(
"#compdef workmux\n",
"_workmux() {\n",
" \"*::: :->workmux\"\n",
" curcontext=\"workmux-command-$line[1]:\"\n",
"}\n",
"\nif [ \"$funcstack[1]\" = \"_workmux\" ]; then\n",
" _workmux \"$@\"\n",
"else\n",
" compdef _workmux workmux\n",
"fi\n",
);
let result = prepare_zsh_base(input, "workmux");
// State names and curcontext use bare "workmux" (no underscore), unchanged
assert!(result.contains("->workmux"));
assert!(result.contains("workmux-command-"));
}
#[test]
fn prepare_zsh_base_tolerates_missing_funcstack_block() {
let input = "_workmux() {\n echo hello\n}\n";
let result = prepare_zsh_base(input, "workmux");
assert!(result.contains("_workmux_base()"));
assert!(!result.contains("_workmux()"));
}
#[test]
fn prepare_zsh_base_works_with_real_clap_output() {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
let mut buf = Vec::new();
generate(Shell::Zsh, &mut cmd, &name, &mut buf);
let base_script = String::from_utf8_lossy(&buf);
let result = prepare_zsh_base(&base_script, &name);
// Main function is renamed
assert!(result.contains("_workmux_base()"));
assert!(!result.contains("\n_workmux()"));
// Helpers are renamed
assert!(result.contains("_workmux_base_commands"));
// #compdef header preserved
assert!(result.starts_with("#compdef workmux\n"));
// _describe strings preserved
assert!(result.contains("'workmux commands'"));
// funcstack block stripped
assert!(!result.contains("funcstack"));
}
/// Helper: produce the full `workmux completions zsh` output
/// (base post-processed by prepare_zsh_base + dynamic wrapper).
fn generate_full_zsh_completions() -> String {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
let mut buf = Vec::new();
generate(Shell::Zsh, &mut cmd, &name, &mut buf);
let base_script = String::from_utf8_lossy(&buf);
let base = prepare_zsh_base(&base_script, &name);
let dynamic = include_str!("scripts/completions/zsh_dynamic.zsh");
format!("{base}\n{dynamic}")
}
#[test]
fn zsh_full_output_has_no_stale_workmux_functions() {
let output = generate_full_zsh_completions();
// The only _workmux() definition should be the dynamic wrapper.
// There must be no clap-generated _workmux() left (it was renamed).
let workmux_fn_count = output.matches("\n_workmux()").count();
assert_eq!(
workmux_fn_count, 1,
"Expected exactly one _workmux() definition (the dynamic wrapper)"
);
// The wrapper must call _workmux_base, not itself
let wrapper_section: &str = output
.split("\n_workmux()")
.nth(1)
.expect("_workmux() not found");
assert!(
wrapper_section.contains("_workmux_base"),
"Dynamic wrapper must delegate to _workmux_base"
);
}
#[test]
fn zsh_full_output_no_file_fallback_for_handle_commands() {
let output = generate_full_zsh_completions();
// The dynamic wrapper's case branches for handle commands should
// call _workmux_handles, not _workmux_base (which has _default).
// Extract the case block from the wrapper.
let wrapper_start = output.find("\n_workmux()").expect("_workmux() not found");
let wrapper = &output[wrapper_start..];
// The handle commands should appear in the case pattern
for cmd in ["open", "remove", "close", "merge"] {
assert!(wrapper.contains(cmd), "Wrapper should handle {cmd}");
}
assert!(
wrapper.contains("_workmux_handles"),
"Wrapper should call _workmux_handles for handle commands"
);
assert!(
wrapper.contains("_workmux_git_branches"),
"Wrapper should call _workmux_git_branches for add"
);
}
#[test]
fn zsh_full_output_autoload_and_eval_compatible() {
let output = generate_full_zsh_completions();
// Must start with #compdef for fpath autoloading
assert!(
output.starts_with("#compdef workmux\n"),
"Must start with #compdef for fpath autoloading"
);
// Must have funcstack detection for autoload/eval compatibility
assert!(
output.contains(r#""$funcstack[1]" = "_workmux""#),
"Must have funcstack check for autoload detection"
);
// Must have compdef registration for eval case
assert!(
output.contains("compdef _workmux workmux"),
"Must register _workmux via compdef for eval case"
);
// Must NOT have compdef for _workmux_base (that was stripped)
assert!(
!output.contains("compdef _workmux_base"),
"Must not register _workmux_base directly"
);
}
#[test]
fn bash_output_unaffected_by_zsh_postprocessing() {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
let mut buf = Vec::new();
generate(Shell::Bash, &mut cmd, &name, &mut buf);
let base_script = String::from_utf8_lossy(&buf);
let dynamic = include_str!("scripts/completions/bash_dynamic.bash");
let output = format!("{base_script}{dynamic}");
// Bash uses _workmux directly (no _base rename)
assert!(output.contains("_workmux()"));
assert!(!output.contains("_workmux_base"));
// Dynamic wrapper registered
assert!(output.contains("complete -F _workmux_dynamic"));
}
#[test]
fn fish_output_unaffected_by_zsh_postprocessing() {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
let mut buf = Vec::new();
generate(Shell::Fish, &mut cmd, &name, &mut buf);
let base_script = String::from_utf8_lossy(&buf);
let dynamic = include_str!("scripts/completions/fish_dynamic.fish");
let output = format!("{base_script}{dynamic}");
// Fish uses workmux directly (no _base rename)
assert!(output.contains("__fish_workmux"));
assert!(!output.contains("workmux_base"));
// Dynamic completions registered
assert!(output.contains("__workmux_handles"));
assert!(output.contains("__workmux_git_branches"));
}
}