workmux 0.1.170

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
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
//! Backend-agnostic utility functions for multiplexer operations.
//!
//! These helpers are shared between tmux, WezTerm, and any future backends.

use std::borrow::Cow;
use std::path::Path;

/// Helper function to add prefix to window name.
///
/// Used by all backends to construct full window names from prefix and base name.
pub fn prefixed(prefix: &str, window_name: &str) -> String {
    format!("{}{}", prefix, window_name)
}

/// Check if a shell is POSIX-compatible (supports `$(...)` syntax).
///
/// Used to determine whether agent commands need to be wrapped in `sh -c '...'`
/// for shells like nushell or fish that don't support POSIX command substitution.
pub fn is_posix_shell(shell: &str) -> bool {
    let shell_name = Path::new(shell)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("sh");
    matches!(shell_name, "bash" | "zsh" | "sh" | "dash" | "ksh" | "ash")
}

/// Rewrites an agent command to inject a prompt file's contents.
///
/// When a prompt file is provided (via --prompt-file or --prompt-editor), this function
/// modifies the agent command to automatically pass the prompt content. For example,
/// "claude" becomes "claude -- \"$(cat PROMPT.md)\"" for POSIX shells, or wrapped in
/// `sh -c '...'` for non-POSIX shells like nushell.
///
/// Only rewrites commands that match the configured agent. For instance, if the config
/// specifies "gemini" as the agent, a "claude" command won't be rewritten.
///
/// Agent-specific prompt injection is handled via `AgentProfile::prompt_argument()`.
///
/// For non-POSIX shells (nushell, fish, pwsh), the command is wrapped in `sh -c '...'`
/// to ensure the `$(cat ...)` command substitution works correctly.
///
/// The returned command is prefixed with a space to prevent it from being saved to
/// shell history (most shells ignore commands starting with a space).
///
/// Returns None if the command shouldn't be rewritten (empty, doesn't match configured agent, etc.)
pub fn rewrite_agent_command(
    command: &str,
    prompt_file: &Path,
    working_dir: &Path,
    effective_agent: Option<&str>,
    shell: &str,
    type_override: Option<&str>,
) -> Option<String> {
    let agent_command = effective_agent?;
    let trimmed_command = command.trim();
    if trimmed_command.is_empty() {
        return None;
    }

    let (pane_token, pane_rest) = crate::config::split_first_token(trimmed_command)?;
    let (config_token, _) = crate::config::split_first_token(agent_command)?;

    let resolved_pane_path = crate::config::resolve_executable_path(pane_token)
        .unwrap_or_else(|| pane_token.to_string());
    let resolved_config_path = crate::config::resolve_executable_path(config_token)
        .unwrap_or_else(|| config_token.to_string());

    let pane_stem = Path::new(&resolved_pane_path).file_stem();
    let config_stem = Path::new(&resolved_config_path).file_stem();

    if pane_stem != config_stem {
        return None;
    }

    let relative = prompt_file.strip_prefix(working_dir).unwrap_or(prompt_file);
    let prompt_path = relative.to_string_lossy();
    let rest = pane_rest.trim_start();

    // Build the inner command step-by-step to ensure correct order:
    // [executable] [default_subcommand?] [user_args] [prompt_argument]
    let profile = super::agent::resolve_profile_with_type(effective_agent, type_override);
    let mut inner_cmd = pane_token.to_string();

    // Insert default subcommand (e.g., "chat" for kiro-cli) if the user
    // hasn't already included it in their config args.
    if let Some(subcmd) = profile.default_subcommand()
        && needs_default_subcommand(rest, subcmd)
    {
        inner_cmd.push(' ');
        inner_cmd.push_str(subcmd);
    }

    // Add user-provided arguments from config (must come before the prompt)
    if !rest.is_empty() {
        inner_cmd.push(' ');
        inner_cmd.push_str(rest);
    }

    // Add the prompt argument
    inner_cmd.push(' ');
    inner_cmd.push_str(&profile.prompt_argument(&prompt_path));

    // For POSIX shells (bash, zsh, sh, etc.), use the command directly.
    // For non-POSIX shells (nushell, fish, pwsh), wrap in sh -c '...' to ensure
    // $(cat ...) command substitution works.
    // Prefix with space to prevent shell history entry.
    if is_posix_shell(shell) {
        Some(format!(" {}", inner_cmd))
    } else {
        Some(format!(" {}", wrap_for_non_posix_shell(&inner_cmd)))
    }
}

/// Resolve a pane's command: handle `<agent>` placeholder, auto-detect known
/// agents, and adjust for prompt injection.
///
/// Returns the final command to send to the pane, or None if no command should be sent.
/// This consolidates the duplicated command resolution logic from both backends' setup_panes.
/// Result of resolving a pane command.
pub struct ResolvedCommand {
    /// The command string to send to the pane.
    pub command: String,
    /// Whether the command was rewritten to inject a prompt (needs auto-status).
    pub prompt_injected: bool,
    /// The effective agent for this pane (may differ from window-level agent for auto-detected agents).
    pub effective_agent: Option<String>,
}

pub fn resolve_pane_command(
    pane_command: Option<&str>,
    run_commands: bool,
    prompt_file_path: Option<&Path>,
    working_dir: &Path,
    effective_agent: Option<&str>,
    shell: &str,
    type_override: Option<&str>,
) -> Option<ResolvedCommand> {
    let raw_command = pane_command?;

    let (command, pane_effective_agent) = if raw_command == "<agent>" {
        // Bare <agent> - use window-level effective agent
        let agent = effective_agent?;
        (agent, effective_agent)
    } else if super::agent::is_known_agent(raw_command) {
        // Known agent command (e.g., "codex --flags") - use itself as effective
        // agent so prompt injection works even when it's not the configured agent
        (raw_command, Some(raw_command))
    } else {
        // Regular command - use window-level effective agent for prompt injection matching
        (raw_command, effective_agent)
    };

    if !run_commands {
        return None;
    }

    let result = adjust_command(
        command,
        prompt_file_path,
        working_dir,
        pane_effective_agent,
        shell,
        type_override,
    );
    let prompt_injected = matches!(result, Cow::Owned(_));
    Some(ResolvedCommand {
        command: result.into_owned(),
        prompt_injected,
        effective_agent: pane_effective_agent.map(|s| s.to_string()),
    })
}

/// Adjust a command for execution, potentially rewriting it to inject prompts.
///
/// This is a convenience wrapper around `rewrite_agent_command` that returns
/// the original command as a borrowed reference if no rewriting is needed.
pub fn adjust_command<'a>(
    command: &'a str,
    prompt_file_path: Option<&Path>,
    working_dir: &Path,
    effective_agent: Option<&str>,
    shell: &str,
    type_override: Option<&str>,
) -> Cow<'a, str> {
    if let Some(prompt_path) = prompt_file_path
        && let Some(rewritten) = rewrite_agent_command(
            command,
            prompt_path,
            working_dir,
            effective_agent,
            shell,
            type_override,
        )
    {
        return Cow::Owned(rewritten);
    }

    // Even without a prompt, insert the default subcommand if needed
    // (e.g., "kiro-cli" -> "kiro-cli chat"). Only applies when the
    // command itself is the agent (stem must match).
    let profile = super::agent::resolve_profile_with_type(effective_agent, type_override);
    if let Some(subcmd) = profile.default_subcommand()
        && let Some((token, rest_with_leading)) = crate::config::split_first_token(command)
    {
        let resolved =
            crate::config::resolve_executable_path(token).unwrap_or_else(|| token.to_string());
        let stem = Path::new(&resolved)
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("");
        if stem == profile.name() {
            let rest = rest_with_leading.trim_start();
            if needs_default_subcommand(rest, subcmd) {
                return if rest.is_empty() {
                    Cow::Owned(format!("{} {}", token, subcmd))
                } else {
                    Cow::Owned(format!("{} {} {}", token, subcmd, rest))
                };
            }
        }
    }

    Cow::Borrowed(command)
}

/// Check whether a default subcommand needs to be inserted.
///
/// Returns `true` when the user's args don't already start with the
/// subcommand (e.g., "chat"). Flags like `--verbose` are not subcommands,
/// so the default is still inserted before them.
fn needs_default_subcommand(rest: &str, subcmd: &str) -> bool {
    match rest.split_whitespace().next() {
        None => true,                                  // no args at all
        Some(first) if first == subcmd => false,       // already has it
        Some(first) if first.starts_with('-') => true, // flag, not a subcommand
        Some(_) => false,                              // some other subcommand
    }
}

/// Escape a string for embedding inside a double-quoted shell context.
///
/// Escapes: backslash, double quote, dollar sign, backtick.
/// Does NOT add surrounding quotes - caller controls the quoting.
///
/// Example: `$HOME` -> `\$HOME`
pub fn escape_for_double_quotes(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('$', "\\$")
        .replace('`', "\\`")
}

/// Escape a command to be safely embedded inside `sh -c "..."`.
///
/// This handles the two-step nesting complexity:
/// 1. Inner single-quoted context (for paths/args inside the command)
/// 2. Outer double-quoted context (for the sh -c wrapper)
///
/// Use when you need to pass a value that will be single-quoted inside
/// a double-quoted sh -c command.
///
/// Example: `/bin/user's shell` inside `sh -c "exec '/bin/user's shell'"`:
/// - Step 1: `'\''` escaping -> `/bin/user'\''s shell`
/// - Step 2: double-quote escaping -> `/bin/user'\''s shell` (no change here)
pub fn escape_for_sh_c_inner_single_quote(s: &str) -> String {
    let single_escaped = s.replace('\'', "'\\''");
    escape_for_double_quotes(&single_escaped)
}

/// Wrap a command in `sh -c '...'` for execution in non-POSIX shells.
///
/// Used when the default shell (nushell, fish, etc.) doesn't support
/// POSIX command substitution like `$(...)`.
pub fn wrap_for_non_posix_shell(command: &str) -> String {
    let escaped = command.replace('\'', "'\\''");
    format!("sh -c '{}'", escaped)
}

/// Inject a permissions flag into an agent command string.
///
/// Inserts the flag after the real agent executable, looking past `env`
/// wrappers and `VAR=value` assignments.
/// For commands like ` claude -- "$(cat PROMPT.md)"`, produces
/// ` claude --dangerously-skip-permissions -- "$(cat PROMPT.md)"`.
///
/// For non-POSIX wrapped commands like ` sh -c 'claude -- ...'`, the flag
/// is inserted inside the inner command.
pub fn inject_skip_permissions_flag(command: &str, flag: &str) -> String {
    // Handle the leading space (history prevention prefix)
    let trimmed = command.trim_start();
    let leading_spaces = &command[..command.len() - trimmed.len()];

    // Handle sh -c wrapper (non-POSIX shells)
    if trimmed.starts_with("sh -c '") && trimmed.ends_with('\'') {
        let inner = &trimmed[7..trimmed.len() - 1];
        let inner_unescaped = inner.replace("'\\''", "'");
        let injected = inject_flag_after_agent_executable(&inner_unescaped, flag);
        let re_escaped = injected.replace('\'', "'\\''");
        return format!("{}sh -c '{}'", leading_spaces, re_escaped);
    }

    format!(
        "{}{}",
        leading_spaces,
        inject_flag_after_agent_executable(trimmed, flag)
    )
}

/// Insert a flag after the real agent executable in a command,
/// handling `env` wrappers and `VAR=value` assignments.
fn inject_flag_after_agent_executable(command: &str, flag: &str) -> String {
    let exe_token = super::agent::find_executable_token(command);
    if exe_token.is_empty() {
        return format!("{} {}", command, flag);
    }

    // Use pointer arithmetic to find the token's position in the original string
    let exe_start = exe_token.as_ptr() as usize - command.as_ptr() as usize;
    let exe_end = exe_start + exe_token.len();

    let before = &command[..exe_end];
    let after = &command[exe_end..];

    if after.is_empty() {
        format!("{} {}", before, flag)
    } else {
        format!("{} {}{}", before, flag, after)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    // --- prefixed tests ---

    #[test]
    fn test_prefixed() {
        assert_eq!(prefixed("wm-", "feature"), "wm-feature");
        assert_eq!(prefixed("", "feature"), "feature");
        assert_eq!(prefixed("prefix-", ""), "prefix-");
    }

    // --- is_posix_shell tests ---

    #[test]
    fn test_is_posix_shell_bash() {
        assert!(is_posix_shell("/bin/bash"));
        assert!(is_posix_shell("/usr/bin/bash"));
    }

    #[test]
    fn test_is_posix_shell_zsh() {
        assert!(is_posix_shell("/bin/zsh"));
        assert!(is_posix_shell("/usr/local/bin/zsh"));
    }

    #[test]
    fn test_is_posix_shell_sh() {
        assert!(is_posix_shell("/bin/sh"));
    }

    #[test]
    fn test_is_posix_shell_nushell() {
        assert!(!is_posix_shell("/opt/homebrew/bin/nu"));
        assert!(!is_posix_shell("/usr/bin/nu"));
    }

    #[test]
    fn test_is_posix_shell_fish() {
        assert!(!is_posix_shell("/usr/bin/fish"));
        assert!(!is_posix_shell("/opt/homebrew/bin/fish"));
    }

    // --- rewrite_agent_command tests for POSIX shells ---

    #[test]
    fn test_rewrite_claude_command_posix() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        let result = rewrite_agent_command(
            "claude",
            &prompt_file,
            &working_dir,
            Some("claude"),
            "/bin/zsh",
            None,
        );
        // POSIX shell: no wrapper, prefixed with space to prevent history
        assert_eq!(result, Some(" claude -- \"$(cat PROMPT.md)\"".to_string()));
    }

    #[test]
    fn test_rewrite_gemini_command_posix() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        let result = rewrite_agent_command(
            "gemini",
            &prompt_file,
            &working_dir,
            Some("gemini"),
            "/bin/bash",
            None,
        );
        assert_eq!(result, Some(" gemini -i \"$(cat PROMPT.md)\"".to_string()));
    }

    #[test]
    fn test_rewrite_opencode_command_posix() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        let result = rewrite_agent_command(
            "opencode",
            &prompt_file,
            &working_dir,
            Some("opencode"),
            "/bin/zsh",
            None,
        );
        assert_eq!(
            result,
            Some(" opencode --prompt \"$(cat PROMPT.md)\"".to_string())
        );
    }

    #[test]
    fn test_rewrite_kiro_bare_command_posix() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        // agent: kiro-cli (bare, no "chat" subcommand)
        let result = rewrite_agent_command(
            "kiro-cli",
            &prompt_file,
            &working_dir,
            Some("kiro-cli"),
            "/bin/zsh",
            None,
        );
        assert_eq!(
            result,
            Some(" kiro-cli chat \"$(cat PROMPT.md)\"".to_string())
        );
    }

    #[test]
    fn test_rewrite_kiro_with_chat_subcommand() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        // agent: "kiro-cli chat" (user already includes chat)
        let result = rewrite_agent_command(
            "kiro-cli chat",
            &prompt_file,
            &working_dir,
            Some("kiro-cli chat"),
            "/bin/zsh",
            None,
        );
        assert_eq!(
            result,
            Some(" kiro-cli chat \"$(cat PROMPT.md)\"".to_string())
        );
    }

    #[test]
    fn test_rewrite_kiro_with_chat_and_flags() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        // agent: "kiro-cli chat --model sonnet"
        let result = rewrite_agent_command(
            "kiro-cli chat --model sonnet",
            &prompt_file,
            &working_dir,
            Some("kiro-cli chat --model sonnet"),
            "/bin/zsh",
            None,
        );
        assert_eq!(
            result,
            Some(" kiro-cli chat --model sonnet \"$(cat PROMPT.md)\"".to_string())
        );
    }

    #[test]
    fn test_rewrite_command_with_args_posix() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        let result = rewrite_agent_command(
            "claude --verbose",
            &prompt_file,
            &working_dir,
            Some("claude"),
            "/bin/bash",
            None,
        );
        assert_eq!(
            result,
            Some(" claude --verbose -- \"$(cat PROMPT.md)\"".to_string())
        );
    }

    // --- rewrite_agent_command tests for non-POSIX shells ---

    #[test]
    fn test_rewrite_claude_command_nushell() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        let result = rewrite_agent_command(
            "claude",
            &prompt_file,
            &working_dir,
            Some("claude"),
            "/opt/homebrew/bin/nu",
            None,
        );
        // Non-POSIX shell: wrap in sh -c, prefixed with space
        assert_eq!(
            result,
            Some(" sh -c 'claude -- \"$(cat PROMPT.md)\"'".to_string())
        );
    }

    #[test]
    fn test_rewrite_mismatched_agent() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        // Command is for claude but agent is gemini
        let result = rewrite_agent_command(
            "claude",
            &prompt_file,
            &working_dir,
            Some("gemini"),
            "/bin/zsh",
            None,
        );
        assert_eq!(result, None);
    }

    #[test]
    fn test_rewrite_empty_command() {
        let prompt_file = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");

        let result = rewrite_agent_command(
            "",
            &prompt_file,
            &working_dir,
            Some("claude"),
            "/bin/zsh",
            None,
        );
        assert_eq!(result, None);
    }

    // --- escape_for_double_quotes tests ---

    #[test]
    fn test_escape_for_double_quotes_simple() {
        assert_eq!(escape_for_double_quotes("hello"), "hello");
        assert_eq!(escape_for_double_quotes("foo bar"), "foo bar");
    }

    #[test]
    fn test_escape_for_double_quotes_special_chars() {
        assert_eq!(escape_for_double_quotes("$HOME"), "\\$HOME");
        assert_eq!(escape_for_double_quotes("a\"b"), "a\\\"b");
        assert_eq!(escape_for_double_quotes("$(cmd)"), "\\$(cmd)");
        assert_eq!(escape_for_double_quotes("`cmd`"), "\\`cmd\\`");
    }

    #[test]
    fn test_escape_for_double_quotes_backslash() {
        assert_eq!(escape_for_double_quotes("a\\b"), "a\\\\b");
        assert_eq!(escape_for_double_quotes("\\$HOME"), "\\\\\\$HOME");
    }

    #[test]
    fn test_escape_for_double_quotes_combined() {
        // Test multiple special chars together
        assert_eq!(
            escape_for_double_quotes("echo \"$HOME\" `pwd`"),
            "echo \\\"\\$HOME\\\" \\`pwd\\`"
        );
    }

    // --- escape_for_sh_c_inner_single_quote tests ---

    #[test]
    fn test_escape_for_sh_c_inner_single_quote_simple() {
        assert_eq!(escape_for_sh_c_inner_single_quote("/bin/bash"), "/bin/bash");
    }

    #[test]
    fn test_escape_for_sh_c_inner_single_quote_with_single_quote() {
        // Shell path with single quote
        // Step 1: ' -> '\'' (single quote escaping)
        // Step 2: backslash in '\'' gets doubled for double-quote context -> '\\''
        assert_eq!(
            escape_for_sh_c_inner_single_quote("/bin/user's shell"),
            "/bin/user'\\\\''s shell"
        );
    }

    #[test]
    fn test_escape_for_sh_c_inner_single_quote_with_dollar() {
        // Dollar sign needs double-quote escaping
        assert_eq!(
            escape_for_sh_c_inner_single_quote("/path/$dir/shell"),
            "/path/\\$dir/shell"
        );
    }

    #[test]
    fn test_escape_for_sh_c_inner_single_quote_combined() {
        // Both single quote and dollar sign
        // Single quote becomes '\'' then backslash is doubled -> '\\''
        // Dollar sign becomes \$ (escaped for double quotes)
        assert_eq!(
            escape_for_sh_c_inner_single_quote("it's $HOME"),
            "it'\\\\''s \\$HOME"
        );
    }

    // --- wrap_for_non_posix_shell tests ---

    #[test]
    fn test_wrap_for_non_posix_shell_simple() {
        assert_eq!(wrap_for_non_posix_shell("echo hello"), "sh -c 'echo hello'");
    }

    #[test]
    fn test_wrap_for_non_posix_shell_with_single_quote() {
        assert_eq!(
            wrap_for_non_posix_shell("echo 'quoted'"),
            "sh -c 'echo '\\''quoted'\\'''"
        );
    }

    #[test]
    fn test_wrap_for_non_posix_shell_with_dollar() {
        // Dollar sign doesn't need escaping in single quotes
        assert_eq!(wrap_for_non_posix_shell("echo $HOME"), "sh -c 'echo $HOME'");
    }

    #[test]
    fn test_wrap_for_non_posix_shell_complex() {
        assert_eq!(
            wrap_for_non_posix_shell("claude -- \"$(cat PROMPT.md)\""),
            "sh -c 'claude -- \"$(cat PROMPT.md)\"'"
        );
    }

    // --- inject_skip_permissions_flag tests ---

    #[test]
    fn test_inject_skip_permissions_with_prompt() {
        let result = inject_skip_permissions_flag(
            " claude -- \"$(cat PROMPT.md)\"",
            "--dangerously-skip-permissions",
        );
        assert_eq!(
            result,
            " claude --dangerously-skip-permissions -- \"$(cat PROMPT.md)\""
        );
    }

    #[test]
    fn test_inject_skip_permissions_with_existing_args() {
        let result = inject_skip_permissions_flag(
            " claude --verbose -- \"$(cat PROMPT.md)\"",
            "--dangerously-skip-permissions",
        );
        assert_eq!(
            result,
            " claude --dangerously-skip-permissions --verbose -- \"$(cat PROMPT.md)\""
        );
    }

    #[test]
    fn test_inject_skip_permissions_bare_command() {
        let result = inject_skip_permissions_flag("claude", "--dangerously-skip-permissions");
        assert_eq!(result, "claude --dangerously-skip-permissions");
    }

    #[test]
    fn test_inject_skip_permissions_non_posix_shell() {
        let result = inject_skip_permissions_flag(
            " sh -c 'claude -- \"$(cat PROMPT.md)\"'",
            "--dangerously-skip-permissions",
        );
        assert_eq!(
            result,
            " sh -c 'claude --dangerously-skip-permissions -- \"$(cat PROMPT.md)\"'"
        );
    }

    #[test]
    fn test_inject_skip_permissions_env_wrapped() {
        let result = inject_skip_permissions_flag(
            " env -u FOO claude -- \"$(cat PROMPT.md)\"",
            "--dangerously-skip-permissions",
        );
        assert_eq!(
            result,
            " env -u FOO claude --dangerously-skip-permissions -- \"$(cat PROMPT.md)\""
        );
    }

    #[test]
    fn test_inject_skip_permissions_env_with_assignments() {
        let result =
            inject_skip_permissions_flag("env FOO=bar claude", "--dangerously-skip-permissions");
        assert_eq!(result, "env FOO=bar claude --dangerously-skip-permissions");
    }

    // --- resolve_pane_command tests ---

    #[test]
    fn test_resolve_pane_command_none_when_no_command() {
        let result =
            resolve_pane_command(None, true, None, Path::new("/tmp"), None, "/bin/zsh", None);
        assert!(result.is_none());
    }

    #[test]
    fn test_resolve_pane_command_none_when_run_commands_false() {
        let result = resolve_pane_command(
            Some("echo hello"),
            false,
            None,
            Path::new("/tmp"),
            None,
            "/bin/zsh",
            None,
        );
        assert!(result.is_none());
    }

    #[test]
    fn test_resolve_pane_command_returns_command_as_is() {
        let result = resolve_pane_command(
            Some("vim"),
            true,
            None,
            Path::new("/tmp"),
            None,
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "vim");
        assert!(!resolved.prompt_injected);
    }

    #[test]
    fn test_resolve_pane_command_agent_placeholder_with_agent() {
        let result = resolve_pane_command(
            Some("<agent>"),
            true,
            None,
            Path::new("/tmp"),
            Some("claude"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "claude");
        assert!(!resolved.prompt_injected);
    }

    #[test]
    fn test_resolve_pane_command_agent_placeholder_without_agent() {
        let result = resolve_pane_command(
            Some("<agent>"),
            true,
            None,
            Path::new("/tmp"),
            None,
            "/bin/zsh",
            None,
        );
        assert!(result.is_none());
    }

    #[test]
    fn test_resolve_pane_command_with_prompt_injection() {
        let prompt = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");
        let result = resolve_pane_command(
            Some("claude"),
            true,
            Some(&prompt),
            &working_dir,
            Some("claude"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert!(resolved.prompt_injected);
        assert!(resolved.command.contains("PROMPT.md"));
    }

    #[test]
    fn test_resolve_pane_command_no_injection_for_mismatched_agent() {
        let prompt = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");
        let result = resolve_pane_command(
            Some("vim"),
            true,
            Some(&prompt),
            &working_dir,
            Some("claude"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert!(!resolved.prompt_injected);
        assert_eq!(resolved.command, "vim");
    }

    #[test]
    fn test_resolve_pane_command_bare_agent_effective_agent_field() {
        let result = resolve_pane_command(
            Some("<agent>"),
            true,
            None,
            Path::new("/tmp"),
            Some("claude"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "claude");
        assert_eq!(resolved.effective_agent.as_deref(), Some("claude"));
    }

    #[test]
    fn test_resolve_pane_command_regular_command_effective_agent_field() {
        let result = resolve_pane_command(
            Some("vim"),
            true,
            None,
            Path::new("/tmp"),
            Some("claude"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "vim");
        // Regular commands still carry the window-level agent
        assert_eq!(resolved.effective_agent.as_deref(), Some("claude"));
    }

    // --- auto-detection of known agent commands ---

    #[test]
    fn test_resolve_pane_command_known_agent_auto_detected() {
        // "codex --flags" is a known agent, should auto-detect even when
        // the window-level agent is different
        let result = resolve_pane_command(
            Some("codex --yolo"),
            true,
            None,
            Path::new("/tmp"),
            Some("claude"), // window-level agent is claude
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "codex --yolo");
        // effective_agent should be the command itself, not the window-level agent
        assert_eq!(resolved.effective_agent.as_deref(), Some("codex --yolo"));
    }

    #[test]
    fn test_resolve_pane_command_known_agent_prompt_injection() {
        let prompt = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");
        let result = resolve_pane_command(
            Some("codex"),
            true,
            Some(&prompt),
            &working_dir,
            Some("claude"), // window-level is claude, pane is codex
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert!(resolved.prompt_injected);
        assert!(resolved.command.contains("PROMPT.md"));
        assert_eq!(resolved.effective_agent.as_deref(), Some("codex"));
    }

    #[test]
    fn test_resolve_pane_command_known_agent_no_window_agent() {
        // Known agent should work even without any window-level agent
        let prompt = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");
        let result = resolve_pane_command(
            Some("gemini"),
            true,
            Some(&prompt),
            &working_dir,
            None, // no window-level agent at all
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert!(resolved.prompt_injected);
        // Should use gemini's profile (-i flag)
        assert!(resolved.command.contains("-i"));
        assert_eq!(resolved.effective_agent.as_deref(), Some("gemini"));
    }

    // --- kiro-cli default subcommand tests ---

    #[test]
    fn test_resolve_pane_command_kiro_bare_inserts_chat() {
        // agent: kiro-cli, no prompt -> should become "kiro-cli chat"
        let result = resolve_pane_command(
            Some("<agent>"),
            true,
            None,
            Path::new("/tmp"),
            Some("kiro-cli"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "kiro-cli chat");
    }

    #[test]
    fn test_resolve_pane_command_kiro_with_chat_no_duplicate() {
        // agent: "kiro-cli chat", no prompt -> stays "kiro-cli chat"
        let result = resolve_pane_command(
            Some("<agent>"),
            true,
            None,
            Path::new("/tmp"),
            Some("kiro-cli chat"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "kiro-cli chat");
    }

    #[test]
    fn test_resolve_pane_command_kiro_no_chat_on_vim() {
        // agent: kiro-cli but pane command is vim -> no chat inserted
        let result = resolve_pane_command(
            Some("vim"),
            true,
            None,
            Path::new("/tmp"),
            Some("kiro-cli"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "vim");
    }

    #[test]
    fn test_resolve_pane_command_kiro_with_prompt() {
        // agent: kiro-cli, with prompt -> "kiro-cli chat "$(cat PROMPT.md)""
        let prompt = PathBuf::from("/tmp/worktree/PROMPT.md");
        let working_dir = PathBuf::from("/tmp/worktree");
        let result = resolve_pane_command(
            Some("<agent>"),
            true,
            Some(&prompt),
            &working_dir,
            Some("kiro-cli"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert!(resolved.prompt_injected);
        assert_eq!(resolved.command, " kiro-cli chat \"$(cat PROMPT.md)\"");
    }

    #[test]
    fn test_resolve_pane_command_kiro_with_flags_inserts_chat() {
        // agent: "kiro-cli --verbose" -> should become "kiro-cli chat --verbose"
        let result = resolve_pane_command(
            Some("<agent>"),
            true,
            None,
            Path::new("/tmp"),
            Some("kiro-cli --verbose"),
            "/bin/zsh",
            None,
        );
        let resolved = result.unwrap();
        assert_eq!(resolved.command, "kiro-cli chat --verbose");
    }

    // --- needs_default_subcommand tests ---

    #[test]
    fn test_needs_default_subcommand_empty() {
        assert!(needs_default_subcommand("", "chat"));
    }

    #[test]
    fn test_needs_default_subcommand_already_present() {
        assert!(!needs_default_subcommand("chat", "chat"));
        assert!(!needs_default_subcommand("chat --model foo", "chat"));
    }

    #[test]
    fn test_needs_default_subcommand_flag() {
        assert!(needs_default_subcommand("--verbose", "chat"));
        assert!(needs_default_subcommand("-v", "chat"));
    }

    #[test]
    fn test_needs_default_subcommand_other_subcommand() {
        assert!(!needs_default_subcommand("login", "chat"));
        assert!(!needs_default_subcommand("agent list", "chat"));
    }
}