par-term 0.48.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! Trigger action dispatch for WindowState.
//!
//! This module handles polling trigger action results from the core library
//! and executing frontend-handled actions: RunCommand, PlaySound, and SendText.
//!
//! ## Sub-modules
//!
//! - `mark_line` — MarkLine result deduplication and application
//! - `sound` — Audio playback for PlaySound trigger actions
//!
//! ## Security
//!
//! Triggers fire on terminal output pattern matches, which means an attacker
//! controlling terminal output (e.g., `cat malicious_file`) could trigger
//! arbitrary command execution. To mitigate this:
//!
//! 1. **`prompt_before_run` flag** (default: `true`): When set, dangerous
//!    actions (`RunCommand`, `SendText`) are queued in `TriggerState::pending_trigger_actions`
//!    and presented to the user via a confirmation dialog before execution. Users must
//!    explicitly approve (once or always) each action. Setting `prompt_before_run: false`
//!    bypasses the dialog and executes immediately.
//!
//! 2. **Command denylist**: Even when `prompt_before_run` is `false`,
//!    `RunCommand` actions are checked against a denylist of dangerous
//!    patterns (rm -rf, curl|bash, eval, etc.).
//!
//! 3. **Rate limiting**: Dangerous actions from output triggers are rate-limited
//!    to prevent malicious output flooding from rapid-fire execution.
//!
//! 4. **Process management**: RunCommand spawns are tracked and limited to prevent
//!    resource exhaustion. Output is redirected to null to prevent terminal corruption.

mod mark_line;
mod sound;

use std::collections::HashMap;
use std::process::Stdio;
use std::time::Instant;

use par_term_config::{check_command_allowlist, check_command_denylist};

/// Maximum number of concurrent trigger-spawned processes allowed.
/// This prevents resource exhaustion from rapid-fire triggers.
const MAX_TRIGGER_PROCESSES: usize = 10;

/// Maximum age (in seconds) for tracked processes before cleanup.
/// Processes older than this are assumed to have completed.
const PROCESS_CLEANUP_AGE_SECS: u64 = 300; // 5 minutes

use par_term_emu_core_rust::terminal::ActionResult;

use crate::config::automation::TriggerActionConfig;

use super::window_state::WindowState;

/// (grid_row, label, color) tuple for a pending MarkLine action.
/// Shared between `mod.rs` (where it's constructed) and `mark_line.rs` (where it's consumed).
type MarkLineEntry = (usize, Option<String>, Option<(u8, u8, u8)>);

/// Expand a leading `~/` to the user's home directory.
fn expand_tilde(path: &str) -> String {
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(home) = dirs::home_dir()
    {
        return home.join(rest).to_string_lossy().to_string();
    }
    path.to_string()
}

/// Shared context for dispatching a single trigger action.
///
/// Groups the per-frame data that every action handler needs so we can
/// pass it as a single argument instead of threading four separate
/// `HashMap` references through every helper.
struct DispatchContext<'a> {
    trigger_prompt_before_run: &'a HashMap<u64, bool>,
    approved_this_frame: &'a std::collections::HashSet<u64>,
    trigger_names: &'a HashMap<u64, String>,
    trigger_split_percent: &'a HashMap<u64, u8>,
    /// SEC-002: Per-trigger command allowlists. When non-empty for a trigger_id,
    /// only commands matching the allowlist are permitted.
    trigger_allowed_commands: &'a HashMap<u64, Vec<String>>,
}

impl WindowState {
    /// Check for trigger action results and dispatch them.
    ///
    /// Called each frame after check_bell(). Polls the core library for
    /// ActionResult events and executes the appropriate frontend action.
    ///
    /// Security restrictions are enforced for dangerous actions:
    /// - `prompt_before_run` flag queues RunCommand/SendText for dialog confirmation
    /// - Command denylist blocks obviously dangerous RunCommand patterns
    /// - Rate limiting prevents rapid-fire dangerous action execution
    pub(crate) fn check_trigger_actions(&mut self) {
        let tab = if let Some(t) = self.tab_manager.active_tab() {
            t
        } else {
            return;
        };

        // Poll action results and custom session variables from the core
        // terminal — from EVERY terminal of the active tab. Mux mirror panes
        // have no PTY reader thread; the daemon-output seam scans them and
        // queues their results on the pane terminal, so polling only
        // `tab.terminal` (the hidden shell in a mux tab) never drains them.
        // Each source keeps its own scrollback_len: the mark-line dispatch
        // math converts grid rows to absolute scrollback lines using the
        // scrollback of the terminal that produced the result.
        // try_lock: intentional — trigger polling in about_to_wait (sync event loop).
        // On miss: that source is not processed this frame; it will be on the next poll.
        let mut polls: Vec<(Vec<ActionResult>, usize)> = Vec::new();
        let mut custom_vars: HashMap<String, String> = HashMap::new();
        if let Ok(term) = tab.terminal.try_read() {
            custom_vars.extend(term.custom_session_variables());
            polls.push((term.poll_action_results(), term.scrollback_len()));
        }
        if let Some(pm) = tab.pane_manager() {
            for pane in pm.all_panes() {
                // Pane 1 of a non-mux tab shares tab.terminal's Arc — polling
                // it again drains an already-empty queue (poll is destructive),
                // so the overlap is harmless.
                if let Ok(term) = pane.terminal.try_read() {
                    custom_vars.extend(term.custom_session_variables());
                    polls.push((term.poll_action_results(), term.scrollback_len()));
                }
            }
        }

        // Sync custom session variables from core (set by SetVariable triggers)
        // to the frontend badge state. Values are trimmed because the core
        // captures the full terminal row which may include trailing padding.
        if !custom_vars.is_empty() {
            let mut changed = false;
            let mut vars = self.badge_state.variables_mut();
            for (name, value) in &custom_vars {
                let trimmed = value.trim();
                if vars.custom.get(name).map(|v| v.as_str()) != Some(trimmed) {
                    log::debug!(
                        "Trigger SetVariable synced to badge: {}='{}'",
                        name,
                        trimmed
                    );
                    vars.custom.insert(name.clone(), trimmed.to_string());
                    changed = true;
                }
            }
            drop(vars);
            if changed {
                self.badge_state.mark_dirty();
            }
        }

        // Drain dialog-approved actions from previous frame (dialog ran last frame).
        // Pre-populate approved_this_frame with their IDs so they bypass the prompt check.
        let mut approved_this_frame: std::collections::HashSet<u64> =
            std::collections::HashSet::new();
        if !self.trigger_state.approved_pending_actions.is_empty() {
            let mut pre_approved: Vec<ActionResult> =
                std::mem::take(&mut self.trigger_state.approved_pending_actions);
            for action in &pre_approved {
                let tid = match action {
                    ActionResult::RunCommand { trigger_id, .. }
                    | ActionResult::SendText { trigger_id, .. }
                    | ActionResult::SplitPane { trigger_id, .. } => Some(*trigger_id),
                    _ => None,
                };
                if let Some(id) = tid {
                    approved_this_frame.insert(id);
                }
            }
            // Prepend pre-approved to this frame's results so they execute
            // now. The tab terminal is source 0; with no contended-and-lost
            // tab poll there is always a source to prepend into.
            match polls.first_mut() {
                Some((results, _)) => {
                    pre_approved.append(results);
                    *results = pre_approved;
                }
                None => polls.push((pre_approved, 0)),
            }
        }

        if polls.iter().all(|(results, _)| results.is_empty()) {
            return;
        }

        // Snapshot trigger_prompt_before_run flags so we can check them without
        // re-borrowing the tab inside the action loop.
        let trigger_prompt_before_run: std::collections::HashMap<u64, bool> =
            tab.scripting.trigger_prompt_before_run.clone();

        // Snapshot trigger names for use in dialog descriptions.
        // Uses the TerminalManager::trigger_names() helper which internally locks
        // the core terminal synchronously (safe: called from the sync event loop).
        let trigger_names: std::collections::HashMap<u64, String> =
            if let Ok(term) = tab.terminal.try_read() {
                term.trigger_names()
            } else {
                std::collections::HashMap::new()
            };

        // Build trigger_split_percent map: trigger_id → split_percent from config.
        // Correlates the trigger name (from core) with the TriggerActionConfig.
        let trigger_split_percent: std::collections::HashMap<u64, u8> = trigger_names
            .iter()
            .filter_map(|(&id, name)| {
                self.config
                    .load()
                    .automation
                    .triggers
                    .iter()
                    .find(|t| &t.name == name)
                    .and_then(|t| {
                        t.actions.iter().find_map(|a| {
                            if let TriggerActionConfig::SplitPane { split_percent, .. } = a {
                                Some((id, *split_percent))
                            } else {
                                None
                            }
                        })
                    })
            })
            .collect();

        // SEC-002: Build per-trigger allowed_commands map from config.
        // When a trigger defines allowed_commands, only those binaries may be
        // executed via RunCommand actions for that trigger.
        let trigger_allowed_commands: std::collections::HashMap<u64, Vec<String>> = trigger_names
            .iter()
            .filter_map(|(&id, name)| {
                self.config
                    .load()
                    .automation
                    .triggers
                    .iter()
                    .find(|t| &t.name == name)
                    .and_then(|t| {
                        if t.allowed_commands.is_empty() {
                            None
                        } else {
                            Some((id, t.allowed_commands.clone()))
                        }
                    })
            })
            .collect();

        let ctx = DispatchContext {
            trigger_prompt_before_run: &trigger_prompt_before_run,
            approved_this_frame: &approved_this_frame,
            trigger_names: &trigger_names,
            trigger_split_percent: &trigger_split_percent,
            trigger_allowed_commands: &trigger_allowed_commands,
        };

        // Dispatch each source's results with that source's scrollback:
        // MarkLine rows are relative to the terminal that produced them, and
        // the batch dedup clusters rescans of the same physical line (once
        // per output chunk) into one mark per line, per source.
        for (action_results, source_scrollback_len) in polls {
            if action_results.is_empty() {
                continue;
            }
            let mut pending_marks: HashMap<u64, Vec<MarkLineEntry>> = HashMap::new();
            for action in action_results {
                self.dispatch_trigger_action(action, &ctx, &mut pending_marks);
            }
            if !pending_marks.is_empty() {
                self.apply_mark_line_results(pending_marks, source_scrollback_len);
            }
        }

        // Periodically clean up stale rate limiter entries (every ~60 seconds of entries)
        if let Some(tab) = self.tab_manager.active_tab_mut() {
            tab.scripting.trigger_rate_limiter.cleanup(60);
        }
    }

    /// Dispatch a single trigger action result to the appropriate handler.
    fn dispatch_trigger_action(
        &mut self,
        action: ActionResult,
        ctx: &DispatchContext<'_>,
        pending_marks: &mut HashMap<u64, Vec<MarkLineEntry>>,
    ) {
        match action {
            ActionResult::RunCommand {
                trigger_id,
                command,
                args,
            } => {
                let command = expand_tilde(&command);
                let args: Vec<String> = args.iter().map(|a| expand_tilde(a)).collect();
                self.handle_run_command_action(trigger_id, command, args, ctx);
            }
            ActionResult::PlaySound {
                trigger_id,
                sound_id,
                volume,
            } => {
                let sound_id = expand_tilde(&sound_id);
                log::info!(
                    "Trigger {} firing PlaySound: '{}' at volume {}",
                    trigger_id,
                    sound_id,
                    volume
                );
                if sound_id == "bell" || sound_id.is_empty() {
                    if let Some(tab) = self.tab_manager.active_tab()
                        && let Some(audio_bell) = tab.active_bell().audio
                    {
                        audio_bell.play(volume);
                    }
                } else {
                    Self::play_sound_file(&sound_id, volume);
                }
            }
            ActionResult::SendText {
                trigger_id,
                text,
                delay_ms,
            } => {
                self.handle_send_text_action(trigger_id, text, delay_ms, ctx);
            }
            ActionResult::Notify {
                trigger_id,
                title,
                message,
            } => {
                log::info!(
                    "Trigger {} firing Notify: '{}' - '{}'",
                    trigger_id,
                    title,
                    message
                );
                // Trigger notifications always deliver (bypass focus suppression)
                // since the user explicitly configured them
                self.deliver_notification_force(&title, &message);
            }
            ActionResult::SplitPane {
                trigger_id,
                direction,
                command,
                focus_new_pane,
                target,
                source_pane_id,
            } => {
                self.handle_split_pane_action(
                    trigger_id,
                    direction,
                    command,
                    focus_new_pane,
                    target,
                    source_pane_id,
                    ctx,
                );
            }
            ActionResult::MarkLine {
                trigger_id,
                row,
                label,
                color,
            } => {
                self.handle_mark_line_action(trigger_id, row, label, color, pending_marks);
            }
        }
    }

    /// Handle a RunCommand trigger action, including security checks and process spawn.
    fn handle_run_command_action(
        &mut self,
        trigger_id: u64,
        command: String,
        args: Vec<String>,
        ctx: &DispatchContext<'_>,
    ) {
        let prompt = ctx
            .trigger_prompt_before_run
            .get(&trigger_id)
            .copied()
            .unwrap_or(true);

        // SEC-001: If prompt_before_run is false but i_accept_the_risk is not set,
        // block execution and log an audit-level warning.
        if !prompt && !ctx.approved_this_frame.contains(&trigger_id) {
            let trigger_name = ctx
                .trigger_names
                .get(&trigger_id)
                .cloned()
                .unwrap_or_else(|| format!("trigger #{}", trigger_id));
            if self
                .config
                .load()
                .unaccepted_risk_trigger_names
                .contains(&trigger_name)
            {
                log::warn!(
                    "Trigger '{}' (id={}) RunCommand BLOCKED: \
                     `prompt_before_run: false` requires `i_accept_the_risk: true` \
                     to execute dangerous actions without confirmation. \
                     Add `i_accept_the_risk: true` to this trigger or set \
                     `prompt_before_run: true`.",
                    trigger_name,
                    trigger_id,
                );
                crate::debug_error!(
                    "TRIGGER",
                    "AUDIT RunCommand BLOCKED trigger_id={} trigger_name={} \
                     reason=missing_i_accept_the_risk",
                    trigger_id,
                    trigger_name,
                );
                return;
            }
            // SEC-001: Log audit warning for every prompt_before_run:false execution.
            log::warn!(
                "SECURITY: Trigger '{}' (id={}) executing RunCommand without \
                 confirmation (prompt_before_run: false). \
                 command='{}' args={:?}",
                trigger_name,
                trigger_id,
                command,
                args,
            );
            crate::debug_info!(
                "TRIGGER",
                "AUDIT RunCommand no-prompt trigger_id={} trigger_name={} \
                 command={} args={:?}",
                trigger_id,
                trigger_name,
                command,
                args,
            );
        }

        if prompt
            && !self
                .trigger_state
                .always_allow_trigger_ids
                .contains(&trigger_id)
            && !ctx.approved_this_frame.contains(&trigger_id)
        {
            let trigger_name = ctx
                .trigger_names
                .get(&trigger_id)
                .cloned()
                .unwrap_or_else(|| format!("trigger #{}", trigger_id));
            let description = format!("Run command: {} {}", command, args.join(" "))
                .trim()
                .to_string();
            self.trigger_state.pending_trigger_actions.push(
                crate::app::window_state::PendingTriggerAction {
                    trigger_id,
                    trigger_name,
                    action: ActionResult::RunCommand {
                        trigger_id,
                        command,
                        args,
                    },
                    description,
                    // An output trigger fires on the active tab's own output.
                    target: None,
                },
            );
            return;
        }

        // SEC-002: Security check: command allowlist (when configured for this trigger).
        // If the trigger has an allowed_commands list, the command must be on it.
        // When no allowlist is set, this check passes and falls through to the
        // denylist below.
        if let Some(allowed) = ctx.trigger_allowed_commands.get(&trigger_id)
            && let Err(reason) = check_command_allowlist(&command, allowed)
        {
            log::error!(
                "Trigger {} RunCommand DENIED by allowlist: {}",
                trigger_id,
                reason,
            );
            return;
        }

        // Security check: command denylist (always applied, even for approved actions)
        if let Some(denied_pattern) = check_command_denylist(&command, &args) {
            log::error!(
                "Trigger {} RunCommand DENIED: '{}' matches denylist pattern '{}'",
                trigger_id,
                command,
                denied_pattern,
            );
            return;
        }

        // Security check: rate limiting (skip for dialog-approved actions this frame)
        if !ctx.approved_this_frame.contains(&trigger_id)
            && let Some(tab) = self.tab_manager.active_tab_mut()
            && !tab
                .scripting
                .trigger_rate_limiter
                .check_and_update(trigger_id)
        {
            log::warn!(
                "Trigger {} RunCommand RATE-LIMITED: '{}' (too frequent)",
                trigger_id,
                command,
            );
            return;
        }

        log::info!(
            "Trigger {} firing RunCommand: {} {:?}",
            trigger_id,
            command,
            args
        );

        // Clean up old process entries (assume completed after timeout)
        let now = Instant::now();
        self.trigger_state
            .trigger_spawned_processes
            .retain(|_pid, spawn_time| {
                now.duration_since(*spawn_time).as_secs() < PROCESS_CLEANUP_AGE_SECS
            });

        // Check process limit to prevent resource exhaustion
        if self.trigger_state.trigger_spawned_processes.len() >= MAX_TRIGGER_PROCESSES {
            log::warn!(
                "Trigger {} RunCommand DENIED: max concurrent processes ({}) reached",
                trigger_id,
                MAX_TRIGGER_PROCESSES
            );
            return;
        }

        // Spawn process with stdout/stderr redirected to null to prevent
        // terminal corruption from inherited file descriptors
        match std::process::Command::new(&command)
            .args(&args)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
        {
            Ok(child) => {
                let pid = child.id();
                log::debug!("RunCommand spawned successfully (PID={})", pid);
                // Security audit trail: record every successful trigger-spawned
                // process at INFO level so it appears in the debug log even
                // without DEBUG_LEVEL set.  This allows post-incident review of
                // which commands were executed via triggers.
                crate::debug_info!(
                    "TRIGGER",
                    "AUDIT RunCommand trigger_id={} pid={} command={} args={:?}",
                    trigger_id,
                    pid,
                    command,
                    args
                );
                // Track the spawned process for resource management
                self.trigger_state
                    .trigger_spawned_processes
                    .insert(pid, Instant::now());
            }
            Err(e) => {
                log::error!("RunCommand failed to spawn '{}': {}", command, e);
                crate::debug_error!(
                    "TRIGGER",
                    "AUDIT RunCommand FAILED trigger_id={} command={} error={}",
                    trigger_id,
                    command,
                    e
                );
            }
        }
    }

    /// Handle a SendText trigger action, including security checks and optional delay.
    fn handle_send_text_action(
        &mut self,
        trigger_id: u64,
        text: String,
        delay_ms: u64,
        ctx: &DispatchContext<'_>,
    ) {
        // Security check: prompt_before_run — if the trigger requires confirmation
        // and has not been pre-approved this session (always_allow) or this frame,
        // enqueue the action for dialog presentation and skip direct execution.
        let prompt = ctx
            .trigger_prompt_before_run
            .get(&trigger_id)
            .copied()
            .unwrap_or(true);
        if prompt
            && !self
                .trigger_state
                .always_allow_trigger_ids
                .contains(&trigger_id)
            && !ctx.approved_this_frame.contains(&trigger_id)
        {
            let trigger_name = ctx
                .trigger_names
                .get(&trigger_id)
                .cloned()
                .unwrap_or_else(|| format!("trigger #{}", trigger_id));
            let description = format!("Send text: '{}'", text);
            self.trigger_state.pending_trigger_actions.push(
                crate::app::window_state::PendingTriggerAction {
                    trigger_id,
                    trigger_name,
                    action: ActionResult::SendText {
                        trigger_id,
                        text,
                        delay_ms,
                    },
                    description,
                    target: None,
                },
            );
            return;
        }

        // Security check: rate limiting (skip for dialog-approved actions this frame)
        if !ctx.approved_this_frame.contains(&trigger_id)
            && let Some(tab) = self.tab_manager.active_tab_mut()
            && !tab
                .scripting
                .trigger_rate_limiter
                .check_and_update(trigger_id)
        {
            log::warn!(
                "Trigger {} SendText RATE-LIMITED: '{}' (too frequent)",
                trigger_id,
                text,
            );
            return;
        }

        log::info!(
            "Trigger {} firing SendText: '{}' (delay={}ms)",
            trigger_id,
            text,
            delay_ms
        );
        // Security audit trail: record every SendText execution so
        // post-incident analysis can reconstruct what text was injected
        // into the terminal via trigger automation.
        crate::debug_info!(
            "TRIGGER",
            "AUDIT SendText trigger_id={} delay_ms={} text={:?}",
            trigger_id,
            delay_ms,
            text
        );
        if let Some(tab) = self.tab_manager.active_tab() {
            // A mux tab's `tab.terminal` is a hidden login shell — route
            // daemon panes first. The transport is boxed and cannot cross
            // into the delayed thread below, so a daemon target sends now
            // rather than after `delay_ms`; a local target is unaffected.
            if self.route_mux_tab_write(tab, text.as_bytes()) {
                return;
            }
            if delay_ms == 0 {
                // try_lock: intentional — trigger SendText in sync event loop.
                // On miss: the triggered text is not sent this frame. Low risk:
                // triggers fire on repeated output patterns and will retry.
                if let Ok(term) = tab.terminal.try_read()
                    && let Err(e) = term.write(text.as_bytes())
                {
                    log::error!("SendText write failed: {}", e);
                }
            } else {
                let terminal = std::sync::Arc::clone(&tab.terminal);
                let text_owned = text;
                std::thread::spawn(move || {
                    std::thread::sleep(std::time::Duration::from_millis(delay_ms));
                    // try_lock: intentional — delayed SendText from spawned thread.
                    // On miss: the delayed text is not sent. Acceptable; trigger
                    // automation has inherent timing flexibility.
                    if let Ok(term) = terminal.try_read()
                        && let Err(e) = term.write(text_owned.as_bytes())
                    {
                        log::error!("Delayed SendText write failed: {}", e);
                    }
                });
            }
        }
    }

    /// Handle a SplitPane trigger action, including security checks and pane creation.
    #[allow(clippy::too_many_arguments)] // Each parameter maps to a distinct trigger config field; grouping would obscure the 1:1 correspondence
    fn handle_split_pane_action(
        &mut self,
        trigger_id: u64,
        direction: par_term_emu_core_rust::terminal::TriggerSplitDirection,
        command: Option<par_term_emu_core_rust::terminal::TriggerSplitCommand>,
        focus_new_pane: bool,
        target: par_term_emu_core_rust::terminal::TriggerSplitTarget,
        source_pane_id: Option<u64>,
        ctx: &DispatchContext<'_>,
    ) {
        // Security check: prompt_before_run — queue action for dialog if not pre-approved
        let prompt = ctx
            .trigger_prompt_before_run
            .get(&trigger_id)
            .copied()
            .unwrap_or(true);
        if prompt
            && !self
                .trigger_state
                .always_allow_trigger_ids
                .contains(&trigger_id)
            && !ctx.approved_this_frame.contains(&trigger_id)
        {
            let trigger_name = ctx
                .trigger_names
                .get(&trigger_id)
                .cloned()
                .unwrap_or_else(|| format!("trigger #{}", trigger_id));
            let dir_str = match direction {
                par_term_emu_core_rust::terminal::TriggerSplitDirection::Horizontal => "horizontal",
                par_term_emu_core_rust::terminal::TriggerSplitDirection::Vertical => "vertical",
            };
            let description = format!("Split pane ({}) and run command", dir_str);
            self.trigger_state.pending_trigger_actions.push(
                crate::app::window_state::PendingTriggerAction {
                    trigger_id,
                    trigger_name,
                    action: ActionResult::SplitPane {
                        trigger_id,
                        direction,
                        command,
                        focus_new_pane,
                        target,
                        source_pane_id,
                    },
                    description,
                    // Not the `TriggerSplitTarget` above: this one is the tab
                    // the action resolves against, and a split is aimed at the
                    // active tab.
                    target: None,
                },
            );
            return;
        }

        // Security check: rate limiting
        if let Some(tab) = self.tab_manager.active_tab_mut()
            && !tab
                .scripting
                .trigger_rate_limiter
                .check_and_update(trigger_id)
        {
            log::warn!(
                "Trigger {} SplitPane RATE-LIMITED (too frequent)",
                trigger_id,
            );
            return;
        }

        let pane_direction = match direction {
            par_term_emu_core_rust::terminal::TriggerSplitDirection::Horizontal => {
                crate::pane::SplitDirection::Horizontal
            }
            par_term_emu_core_rust::terminal::TriggerSplitDirection::Vertical => {
                crate::pane::SplitDirection::Vertical
            }
        };

        crate::debug_info!(
            "TRIGGER",
            "AUDIT SplitPane trigger_id={} direction={:?} focus_new={}",
            trigger_id,
            pane_direction,
            focus_new_pane
        );

        let pct = ctx
            .trigger_split_percent
            .get(&trigger_id)
            .copied()
            .unwrap_or(66);

        // A mux tab's panes are daemon mirrors: split daemon-side and type
        // the command into the new daemon pane. A native split here would
        // create a local pane the mux router starves.
        #[cfg(feature = "mux")]
        {
            let command_line = match &command {
                Some(par_term_emu_core_rust::terminal::TriggerSplitCommand::SendText {
                    text,
                    ..
                }) => Some(text.clone()),
                Some(par_term_emu_core_rust::terminal::TriggerSplitCommand::InitialCommand {
                    command: cmd_name,
                    args,
                }) => {
                    // The daemon wire has no initial-process form; typing
                    // the command line is the launch mechanism (the same
                    // fallback the local path uses below).
                    Some(if args.is_empty() {
                        cmd_name.clone()
                    } else {
                        format!("{cmd_name} {}", args.join(" "))
                    })
                }
                None => None,
            };
            if self.split_pane_with_command_via_mux(
                matches!(
                    direction,
                    par_term_emu_core_rust::terminal::TriggerSplitDirection::Vertical
                ),
                command_line.as_deref(),
            ) {
                return;
            }
        }

        let new_pane_id = self.split_pane_direction(pane_direction, focus_new_pane, None, pct);

        // After split, optionally send a command to the new pane.
        if let (Some(pane_id), Some(cmd)) = (new_pane_id, command) {
            let (text, delay_ms) = match cmd {
                par_term_emu_core_rust::terminal::TriggerSplitCommand::SendText {
                    text,
                    delay_ms,
                } => (format!("{}\n", text), delay_ms),
                par_term_emu_core_rust::terminal::TriggerSplitCommand::InitialCommand {
                    command: cmd_name,
                    args,
                } => {
                    // InitialCommand is not yet supported for trigger-created panes.
                    // Fall back to sending command as text to the new shell.
                    log::warn!(
                        "Trigger {} SplitPane InitialCommand not fully supported; \
                         sending as text",
                        trigger_id
                    );
                    let full = if args.is_empty() {
                        format!("{}\n", cmd_name)
                    } else {
                        format!("{} {}\n", cmd_name, args.join(" "))
                    };
                    (full, 200)
                }
            };

            // Send text to the new pane's terminal with optional delay.
            if let Some(tab) = self.tab_manager.active_tab()
                && let Some(pm) = tab.pane_manager()
                && let Some(pane) = pm.get_pane(pane_id)
            {
                let terminal = std::sync::Arc::clone(&pane.terminal);
                std::thread::spawn(move || {
                    if delay_ms > 0 {
                        std::thread::sleep(std::time::Duration::from_millis(delay_ms));
                    }
                    if let Ok(term) = terminal.try_read()
                        && let Err(e) = term.write(text.as_bytes())
                    {
                        log::error!(
                            "SplitPane SendText write failed for pane {}: {}",
                            pane_id,
                            e
                        );
                    }
                });
            }
        }
    }

    /// Handle a MarkLine trigger action.
    ///
    /// MarkLine events are batched in `pending_marks` for deduplication.
    fn handle_mark_line_action(
        &mut self,
        trigger_id: u64,
        row: usize,
        label: Option<String>,
        color: Option<(u8, u8, u8)>,
        pending_marks: &mut HashMap<u64, Vec<MarkLineEntry>>,
    ) {
        pending_marks
            .entry(trigger_id)
            .or_default()
            .push((row, label, color));
    }
}

#[cfg(all(test, feature = "mux"))]
mod write_routing_tests {
    use super::*;
    use crate::app::tmux_handler::pane_write::tests::mux_state_with_recorder;
    use crate::config::Config;
    use std::collections::{HashMap, HashSet};

    /// The SendText write goes to the daemon pane behind the focused
    /// mirror, never to the mux tab's hidden login shell. Proven red
    /// against the tab-terminal write before the routing swap.
    #[test]
    fn trigger_send_text_routes_to_the_daemon_pane() {
        let (mut ws, sent, tab_id, pane) =
            mux_state_with_recorder("trigger-send-text", Config::default());
        let _ = (tab_id, pane);

        let prompt_off: HashMap<u64, bool> = HashMap::from([(7, false)]);
        let approved = HashSet::new();
        let names: HashMap<u64, String> = HashMap::new();
        let percents: HashMap<u64, u8> = HashMap::new();
        let allowed: HashMap<u64, Vec<String>> = HashMap::new();
        let ctx = DispatchContext {
            trigger_prompt_before_run: &prompt_off,
            approved_this_frame: &approved,
            trigger_names: &names,
            trigger_split_percent: &percents,
            trigger_allowed_commands: &allowed,
        };

        ws.handle_send_text_action(7, "trigger-needle".to_string(), 0, &ctx);

        let hex: String = b"trigger-needle"
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<Vec<_>>()
            .join(" ");
        assert_eq!(
            *sent.lock().unwrap(),
            vec![format!("send-keys -t %0 -H {hex}")],
            "trigger SendText must reach the daemon pane, not the hidden shell"
        );
    }

    /// A SplitPane trigger in a mux tab must split daemon-side and type
    /// its command into the new daemon pane — a native split would create
    /// a local pane the mux router starves.
    #[test]
    fn trigger_split_pane_splits_daemon_side_and_types_the_command() {
        use crate::app::tmux_handler::pane_write::tests::SplitReplyingTransport;
        use par_term_emu_core_rust::terminal::{
            TriggerSplitCommand, TriggerSplitDirection, TriggerSplitTarget,
        };

        let (mut ws, _plain, tab_id, pane) =
            mux_state_with_recorder("trigger-split-mux", Config::default());
        let (transport, sent) = SplitReplyingTransport::new(1);
        ws.tmux_state.transport = Some(Box::new(transport));

        let prompt_off: HashMap<u64, bool> = HashMap::from([(7, false)]);
        let approved = HashSet::new();
        let names: HashMap<u64, String> = HashMap::new();
        let percents: HashMap<u64, u8> = HashMap::new();
        let allowed: HashMap<u64, Vec<String>> = HashMap::new();
        let ctx = DispatchContext {
            trigger_prompt_before_run: &prompt_off,
            approved_this_frame: &approved,
            trigger_names: &names,
            trigger_split_percent: &percents,
            trigger_allowed_commands: &allowed,
        };

        ws.handle_split_pane_action(
            7,
            TriggerSplitDirection::Vertical,
            Some(TriggerSplitCommand::SendText {
                text: "echo trigger-split".to_string(),
                delay_ms: 0,
            }),
            true,
            TriggerSplitTarget::Active,
            None,
            &ctx,
        );

        let commands: Vec<String> = sent
            .lock()
            .unwrap()
            .iter()
            .filter(|c| !c.starts_with("set-environment"))
            .cloned()
            .collect();
        assert_eq!(
            commands,
            vec![
                "split-window -h -t %0".to_string(),
                format!(
                    "send-keys -t %1 -l {}",
                    par_term_mux::quote_env_value("echo trigger-split")
                ),
                "send-keys -t %1 Enter".to_string(),
            ],
            "the split and the command must both land daemon-side"
        );
        assert_eq!(
            ws.tab_manager
                .get_tab(tab_id)
                .and_then(|tab| tab.pane_manager().map(|pm| pm.all_panes().len())),
            Some(1),
            "no native pane may be created inside the mux tab"
        );
        assert_eq!(
            ws.tmux_state.mux_focused_pane,
            Some(1),
            "the new daemon pane must be focused"
        );
        let _ = pane;
    }
}