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
//! Tab constructors: `Tab::new`, `Tab::new_from_profile`, and `Tab::new_internal`.
//!
//! Split from `tab/mod.rs` to keep that file under 500 lines. The `Tab` struct
//! definition and `Drop` impl remain in `mod.rs`; all constructor logic lives here.
use super::{Tab, TabInitParams};
use crate::config::Config;
use crate::pane::{Pane, PaneManager};
use crate::profile::Profile;
use crate::session_logger::{SessionLogger, create_shared_logger};
use crate::tab::activity_state::TabActivityMonitor;
use crate::tab::initial_text::build_initial_text_payload;
use crate::tab::profile_state::TabProfileState;
use crate::tab::scripting_state::TabScriptingState;
use crate::tab::setup::{
apply_login_shell_flag, build_shell_env, create_base_terminal, get_shell_command,
};
use crate::tab::tmux_state::TabTmuxState;
use crate::terminal::TerminalManager;
use par_term_config::TabId;
use par_term_terminal::conversion::to_core_restart_policy;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU8};
use tokio::runtime::Runtime;
use tokio::sync::RwLock;
impl Tab {
/// Shared constructor body called by both `Tab::new()` and `Tab::new_from_profile()`.
///
/// Both public constructors:
/// 1. Create and configure a `TerminalManager` (divergent: shell command, env, login_shell)
/// 2. Call this method to handle the identical steps:
/// - Coprocess auto-start loop
/// - Script auto-start loop
/// - Session logging setup
/// - `Arc<RwLock<>>` wrapping
/// - Initial text scheduling (only when `params.runtime` is `Some`)
/// - `Tab` struct construction with all shared default fields
///
/// # Arguments
/// * `params` — Constructor-specific values (title, working_directory, etc.)
/// * `terminal` — Fully configured `TerminalManager` with PTY already spawned
/// * `config` — Global config (used for coprocesses, scripts, and session logging)
/// * `session_title` — Human-readable title written to the session log file header
pub(super) fn new_internal(
params: TabInitParams,
terminal: TerminalManager,
config: &Config,
session_title: String,
) -> anyhow::Result<Self> {
// Sync triggers from config into the core TriggerRegistry
let trigger_security = terminal.sync_triggers(&config.triggers);
// Auto-start configured coprocesses via the PtySession's built-in manager
let mut coprocess_ids = Vec::with_capacity(config.coprocesses.len());
for coproc_config in &config.coprocesses {
if coproc_config.auto_start {
let core_config = par_term_emu_core_rust::coprocess::CoprocessConfig {
command: coproc_config.command.clone(),
args: coproc_config.args.clone(),
cwd: None,
env: crate::terminal::coprocess_env(),
copy_terminal_output: coproc_config.copy_terminal_output,
restart_policy: to_core_restart_policy(coproc_config.restart_policy),
restart_delay_ms: coproc_config.restart_delay_ms,
};
match terminal.start_coprocess(core_config) {
Ok(id) => {
log::info!(
"Auto-started coprocess '{}' (id={})",
coproc_config.name,
id
);
coprocess_ids.push(Some(id));
}
Err(e) => {
log::warn!(
"Failed to auto-start coprocess '{}': {}",
coproc_config.name,
e
);
coprocess_ids.push(None);
}
}
} else {
coprocess_ids.push(None);
}
}
// Auto-start configured scripts. Runs while `terminal` is still owned
// here, so the observer registration needs no lock (the `Arc<RwLock<_>>`
// wrap happens further down).
let mut scripting = TabScriptingState {
coprocess_ids,
trigger_prompt_before_run: trigger_security,
..TabScriptingState::default()
};
for (index, script_config) in config.scripts.iter().enumerate() {
if !script_config.should_auto_start() {
continue;
}
match scripting.start_script_at(&terminal, index, script_config) {
Ok(id) => {
log::info!("Auto-started script '{}' (id={})", script_config.name, id);
crate::debug_info!(
"SCRIPT",
"auto-start: '{}' index={} id={}",
script_config.name,
index,
id
);
}
Err(e) => {
log::warn!(
"Failed to auto-start script '{}': {}",
script_config.name,
e
);
crate::debug_error!(
"SCRIPT",
"auto-start FAILED for '{}' index={}: {}",
script_config.name,
index,
e
);
}
}
}
// Create shared session logger
let session_logger = create_shared_logger();
// Set up session logging if enabled
if config.auto_log_sessions {
let logs_dir = config.logs_dir();
// SEC-010: Ensure the logs directory exists with owner-only permissions
// (0o700) so session logs are not world-listable.
if let Err(e) = std::fs::create_dir_all(&logs_dir) {
log::warn!("Failed to create logs directory {:?}: {}", logs_dir, e);
} else {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(&logs_dir, std::fs::Permissions::from_mode(0o700));
}
}
let title_with_ts = Some(format!(
"{} - {}",
session_title,
chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
));
match SessionLogger::new(
config.session_log_format,
&logs_dir,
(config.cols, config.rows),
title_with_ts,
) {
Ok(mut logger) => {
logger.set_redact_passwords(config.session_log_redact_passwords);
if let Err(e) = logger.start() {
log::warn!("Failed to start session logging: {}", e);
} else {
log::info!("Session logging started: {:?}", logger.output_path());
// Set up output callback to record PTY output
let logger_clone = Arc::clone(&session_logger);
terminal.set_output_callback(move |data: &[u8]| {
if let Some(ref mut logger) = *logger_clone.lock() {
logger.record_output(data);
}
});
*session_logger.lock() = Some(logger);
}
}
Err(e) => {
log::warn!("Failed to create session logger: {}", e);
}
}
}
let terminal = Arc::new(RwLock::new(terminal));
// Send initial text after optional delay (only when a runtime is provided)
if let Some(runtime) = params.runtime
&& let Some(payload) =
build_initial_text_payload(&config.initial_text, config.initial_text_send_newline)
{
let delay_ms = config.initial_text_delay_ms;
let terminal_clone = Arc::clone(&terminal);
runtime.spawn(async move {
if delay_ms > 0 {
tokio::time::sleep(tokio::time::Duration::from_millis(delay_ms)).await;
}
let term = terminal_clone.read().await;
if let Err(err) = term.write(&payload) {
log::warn!("Failed to send initial text: {}", err);
}
});
}
// Always create a PaneManager with one primary pane that wraps `tab.terminal`
// (R-32). This eliminates the fallback scroll_state/mouse/bell/cache fields
// that were used when pane_manager was None (single-pane mode).
let is_active = Arc::new(AtomicBool::new(false));
let pane_manager = PaneManager::new_with_existing_terminal(
Arc::clone(&terminal),
params.working_directory.clone(),
Arc::clone(&is_active),
);
Ok(Self {
id: params.id,
terminal,
pane_manager: Some(pane_manager),
title: params.title,
refresh_task: None,
working_directory: params.working_directory,
custom_color: None,
has_default_title: params.has_default_title,
user_named: params.user_named,
activity: TabActivityMonitor::default(),
session_logger,
tmux: TabTmuxState::default(),
detected_hostname: None,
detected_cwd: None,
custom_icon: None,
profile: TabProfileState::default(),
scripting,
was_alt_screen: false,
is_active,
shutdown_fast: false,
is_hidden: false,
cached_modify_other_keys_mode: AtomicU8::new(0),
cached_application_cursor: AtomicBool::new(false),
cached_alt_screen_active: AtomicBool::new(false),
cached_has_tmux_child: AtomicBool::new(false),
})
}
/// Create a new tab with a terminal session
///
/// # Arguments
/// * `id` - Unique tab identifier
/// * `tab_number` - Display number for the tab (1-indexed)
/// * `config` - Terminal configuration
/// * `runtime` - Tokio runtime for async operations
/// * `working_directory` - Optional working directory to start in
/// * `grid_size` - Optional (cols, rows) override. When provided, uses these
/// dimensions instead of config.cols/rows. This ensures the shell starts
/// with the correct dimensions when the renderer has already calculated
/// the grid size accounting for tab bar height.
pub fn new(
id: TabId,
tab_number: usize,
config: &Config,
runtime: Arc<Runtime>,
working_directory: Option<String>,
grid_size: Option<(usize, usize)>,
) -> anyhow::Result<Self> {
// Create and configure terminal
let (mut terminal, _, _) = create_base_terminal(config, grid_size)?;
// Determine working directory:
// 1. If explicitly provided (e.g., from tab_inherit_cwd), use that
// 2. Otherwise, use the configured startup directory based on mode
let effective_startup_dir = config.get_effective_startup_directory();
let work_dir = working_directory
.as_deref()
.or(effective_startup_dir.as_deref());
// Get shell command and apply login shell flag
let (shell_cmd, mut shell_args) = get_shell_command(config);
apply_login_shell_flag(&mut shell_args, config);
let shell_args_deref = shell_args.as_deref();
let shell_env = build_shell_env(config.shell_env.as_ref());
terminal.spawn_custom_shell_with_dir(
&shell_cmd,
shell_args_deref,
work_dir,
shell_env.as_ref(),
)?;
// Generate initial title based on current tab count, not unique ID
let title = format!("Tab {}", tab_number);
Self::new_internal(
TabInitParams {
id,
title,
has_default_title: true,
user_named: false,
working_directory: working_directory.or_else(|| config.working_directory.clone()),
runtime: Some(runtime),
},
terminal,
config,
format!("Tab {}", tab_number),
)
}
/// Create a new tab from a profile configuration
///
/// The profile can override:
/// - Working directory
/// - Command and arguments (instead of default shell)
/// - Tab name
///
/// If a profile specifies a command, it always runs from the profile's working
/// directory (or config default if unset).
///
/// # Arguments
/// * `id` - Unique tab identifier
/// * `config` - Terminal configuration
/// * `_runtime` - Tokio runtime (unused: profile tabs don't send initial text)
/// * `profile` - Profile configuration to use
/// * `grid_size` - Optional (cols, rows) override for initial terminal size
///
/// # Unique logic vs `Tab::new()`
/// This constructor's divergent logic (not shared with `Tab::new()` via `new_internal`):
/// - SSH command detection (`profile.ssh_command_args()`)
/// - Per-profile `login_shell` override (takes precedence over `config.login_shell`)
/// - Per-profile `SHELL` env-var injection when `profile.shell` is set
/// - Title derived from `profile.tab_name` → `profile.name` (not "Tab N")
/// - Profile tabs do NOT send `config.initial_text` on startup
pub fn new_from_profile(
id: TabId,
config: &Config,
_runtime: Arc<Runtime>,
profile: &Profile,
grid_size: Option<(usize, usize)>,
) -> anyhow::Result<Self> {
// Create and configure terminal
let (mut terminal, _, _) = create_base_terminal(config, grid_size)?;
// Determine working directory: profile overrides config startup directory
let effective_startup_dir = config.get_effective_startup_directory();
let work_dir = profile
.working_directory
.as_deref()
.or(effective_startup_dir.as_deref());
// Determine command and args with priority:
// 0. profile.ssh_host → build ssh command with user/port/identity args
// 1. profile.command → use as-is (non-shell commands like tmux, ssh)
// 2. profile.shell → use as shell, apply login_shell logic
// 3. neither → fall back to global config shell / $SHELL
let is_ssh_profile = profile.ssh_host.is_some();
let (shell_cmd, mut shell_args) = if let Some(ssh_args) = profile.ssh_command_args() {
("ssh".to_string(), Some(ssh_args))
} else if let Some(ref cmd) = profile.command {
(cmd.clone(), profile.command_args.clone())
} else if let Some(ref shell) = profile.shell {
(shell.clone(), None)
} else {
get_shell_command(config)
};
// Apply login shell flag when using a shell (not a custom command or SSH profile).
// Per-profile login_shell overrides global config.login_shell.
if profile.command.is_none() && !is_ssh_profile {
let use_login_shell = profile.login_shell.unwrap_or(config.login_shell);
if use_login_shell {
let args = shell_args.get_or_insert_with(Vec::new);
#[cfg(not(target_os = "windows"))]
if !args.iter().any(|a| a == "-l" || a == "--login") {
args.insert(0, "-l".to_string());
}
}
}
let shell_args_deref = shell_args.as_deref();
let mut shell_env = build_shell_env(config.shell_env.as_ref());
// When a profile specifies a shell, set the SHELL env var so child
// processes (and $SHELL) reflect the selected shell, not the login shell.
if profile.command.is_none()
&& let Some(ref shell_path) = profile.shell
&& let Some(ref mut env) = shell_env
{
env.insert("SHELL".to_string(), shell_path.clone());
}
terminal.spawn_custom_shell_with_dir(
&shell_cmd,
shell_args_deref,
work_dir,
shell_env.as_ref(),
)?;
// Generate title: use profile tab_name or profile name
let title = profile
.tab_name
.clone()
.unwrap_or_else(|| profile.name.clone());
let working_directory = profile
.working_directory
.clone()
.or_else(|| config.working_directory.clone());
// Session log title uses profile name (Tab::new uses "Tab N")
let session_title = profile.name.clone();
Self::new_internal(
TabInitParams {
id,
title,
has_default_title: false, // Profile-created tabs have explicit names
user_named: profile.tab_name.is_some(),
working_directory,
runtime: None, // Profile tabs don't send initial_text
},
terminal,
config,
session_title,
)
}
/// Create a new tab wrapping an existing `Pane` (e.g., from a promote operation).
///
/// The pane's PTY, scroll state, and session logger are preserved.
/// No new shell is spawned — the pane's terminal keeps running.
/// The tab shares the pane's `Arc<RwLock<TerminalManager>>` as its primary terminal.
pub fn new_from_pane(
id: TabId,
pane: Pane,
_config: &Config,
_runtime: Arc<Runtime>,
tab_number: usize,
) -> Self {
// Clone the pane's terminal Arc as the tab's primary terminal
let terminal = Arc::clone(&pane.terminal);
let is_active = Arc::clone(&pane.is_active);
let session_logger = Arc::clone(&pane.session_logger);
// Create a PaneManager with this pane as the single root
let pane_manager = PaneManager::new_with_pane(pane);
let title = format!("Tab {}", tab_number);
Self {
id,
terminal,
pane_manager: Some(pane_manager),
title,
refresh_task: None,
working_directory: None,
custom_color: None,
has_default_title: true,
user_named: false,
activity: TabActivityMonitor::default(),
session_logger,
tmux: TabTmuxState::default(),
detected_hostname: None,
detected_cwd: None,
custom_icon: None,
profile: TabProfileState::default(),
scripting: TabScriptingState::default(),
was_alt_screen: false,
is_active,
shutdown_fast: false,
is_hidden: false,
cached_modify_other_keys_mode: AtomicU8::new(0),
cached_application_cursor: AtomicBool::new(false),
cached_alt_screen_active: AtomicBool::new(false),
cached_has_tmux_child: AtomicBool::new(false),
}
}
}
/// Minimal stub for use in unit tests (no PTY, no runtime).
#[cfg(test)]
impl Tab {
pub(crate) fn new_stub(id: TabId, tab_number: usize) -> Self {
use crate::session_logger::create_shared_logger;
// Create a dummy TerminalManager without spawning a shell
let terminal =
TerminalManager::new_with_scrollback(80, 24, 100).expect("stub terminal creation");
let terminal = Arc::new(RwLock::new(terminal));
let is_active = Arc::new(AtomicBool::new(false));
let pane_manager = PaneManager::new_with_existing_terminal(
Arc::clone(&terminal),
None,
Arc::clone(&is_active),
);
Self {
id,
terminal,
pane_manager: Some(pane_manager),
title: format!("Tab {}", tab_number),
refresh_task: None,
working_directory: None,
custom_color: None,
has_default_title: true,
user_named: false,
activity: TabActivityMonitor::default(),
session_logger: create_shared_logger(),
tmux: TabTmuxState::default(),
detected_hostname: None,
detected_cwd: None,
custom_icon: None,
profile: TabProfileState::default(),
scripting: TabScriptingState::default(),
was_alt_screen: false,
is_active,
shutdown_fast: false,
is_hidden: false,
cached_modify_other_keys_mode: AtomicU8::new(0),
cached_application_cursor: AtomicBool::new(false),
cached_alt_screen_active: AtomicBool::new(false),
cached_has_tmux_child: AtomicBool::new(false),
}
}
}
/// Regression tests for script auto-start (issue #220).
///
/// `auto_start` was documented as spawning a script at tab creation but was
/// never wired up — only the Settings UI start button could launch a script.
/// These drive the real `new_internal` auto-start loop against a terminal that
/// has no shell spawned, so they run without a PTY on every supported platform.
#[cfg(test)]
mod auto_start_tests {
use super::*;
use par_term_config::ScriptConfig;
/// A command that stays alive reading stdin, so `is_running` is stable for
/// the duration of the test. `findstr` is the Windows analogue of `cat`:
/// given a pattern and no file argument it reads stdin until EOF.
///
/// Invoked directly rather than through `cmd.exe /c`: the shell would treat
/// `^` as its escape character (`findstr ^` fails with "Bad command line"),
/// and wrapping in a shell would make the real reader a grandchild that
/// `Child::kill` does not reap.
#[cfg(unix)]
const LONG_LIVED: (&str, &[&str]) = ("/bin/cat", &[]);
#[cfg(windows)]
const LONG_LIVED: (&str, &[&str]) = ("findstr.exe", &["x"]);
/// Script config pointing at a long-lived process so `is_running` is stable.
fn cat_script(name: &str, enabled: bool, auto_start: bool) -> ScriptConfig {
let (path, args) = LONG_LIVED;
ScriptConfig {
name: name.to_string(),
enabled,
script_path: path.to_string(),
args: args.iter().map(|s| s.to_string()).collect(),
auto_start,
restart_policy: Default::default(),
restart_delay_ms: 0,
subscriptions: Vec::new(),
env_vars: Default::default(),
allow_write_text: false,
allow_run_command: false,
allow_change_config: false,
write_text_rate_limit: 0,
run_command_rate_limit: 0,
}
}
fn tab_with_scripts(scripts: Vec<ScriptConfig>) -> Tab {
let config = Config {
scripts,
..Config::default()
};
let terminal =
TerminalManager::new_with_scrollback(80, 24, 100).expect("terminal creation");
Tab::new_internal(
TabInitParams {
id: 1,
title: "Tab 1".to_string(),
has_default_title: true,
user_named: false,
working_directory: None,
runtime: None,
},
terminal,
&config,
"Tab 1".to_string(),
)
.expect("tab creation")
}
#[test]
fn auto_start_script_is_running_after_tab_creation() {
let mut tab = tab_with_scripts(vec![cat_script("auto", true, true)]);
let id = tab
.scripting
.script_ids
.first()
.copied()
.flatten()
.expect("auto_start script must be spawned at tab creation");
assert!(
tab.scripting.script_manager.is_running(id),
"auto-started script process must be alive"
);
assert!(
matches!(tab.scripting.script_forwarders.first(), Some(Some(_))),
"auto-started script must have an event forwarder registered"
);
assert!(
matches!(tab.scripting.script_observer_ids.first(), Some(Some(_))),
"auto-started script must be registered as a terminal observer"
);
}
#[test]
fn script_without_auto_start_is_not_spawned() {
let tab = tab_with_scripts(vec![cat_script("manual", true, false)]);
assert!(
tab.scripting
.script_ids
.first()
.copied()
.flatten()
.is_none(),
"auto_start: false must stay manual-start only"
);
}
#[test]
fn disabled_script_is_not_spawned() {
let tab = tab_with_scripts(vec![cat_script("disabled", false, true)]);
assert!(
tab.scripting
.script_ids
.first()
.copied()
.flatten()
.is_none(),
"enabled: false must veto auto_start: true"
);
}
#[test]
fn tracking_state_stays_aligned_with_config_indices() {
// Per-tab script tracking is indexed by position in `config.scripts`,
// so skipped entries must leave holes rather than shifting later ones.
let mut tab = tab_with_scripts(vec![
cat_script("manual", true, false),
cat_script("auto", true, true),
]);
assert!(
tab.scripting
.script_ids
.first()
.copied()
.flatten()
.is_none(),
"index 0 is manual-start and must stay empty"
);
let id = tab
.scripting
.script_ids
.get(1)
.copied()
.flatten()
.expect("index 1 has auto_start: true and must be spawned");
assert!(tab.scripting.script_manager.is_running(id));
}
#[test]
fn no_scripts_configured_leaves_tracking_empty() {
let tab = tab_with_scripts(Vec::new());
assert!(tab.scripting.script_ids.is_empty());
assert!(tab.scripting.script_forwarders.is_empty());
}
/// Restarting an index must tear down the previous script first.
///
/// A script that exits on its own leaves its observer registered — only an
/// explicit stop removes it — so a naive restart would overwrite the
/// tracking slot and orphan the old forwarder on the terminal, where it
/// keeps accumulating events into a buffer nobody drains.
#[test]
fn restarting_an_index_does_not_orphan_the_previous_observer() {
let config = cat_script("auto", true, true);
let mut tab = tab_with_scripts(vec![config.clone()]);
let first_id = tab
.scripting
.script_ids
.first()
.copied()
.flatten()
.expect("initial auto-start");
let first_observer = tab.scripting.script_observer_ids[0].expect("initial observer");
// Restart the same index, as the Settings UI does after a script exits.
let second_id = {
let term = tab.terminal.blocking_read();
tab.scripting
.start_script_at(&term, 0, &config)
.expect("restart")
};
assert_ne!(first_id, second_id, "restart must spawn a new process");
assert!(
!tab.scripting.script_manager.is_running(first_id),
"the superseded script process must be stopped"
);
// `remove_observer` reports whether the id was still registered, so a
// second removal returning `true` means the restart leaked it.
let still_registered = {
let term = tab.terminal.blocking_read();
term.remove_observer(first_observer)
};
assert!(
!still_registered,
"restart must unregister the superseded observer, not orphan it"
);
}
/// Stopping a script must leave no observer behind either.
#[test]
fn clearing_an_index_unregisters_its_observer() {
let mut tab = tab_with_scripts(vec![cat_script("auto", true, true)]);
let observer = tab.scripting.script_observer_ids[0].expect("initial observer");
{
let term = tab.terminal.blocking_read();
tab.scripting.clear_script_at(&term, 0);
}
let still_registered = {
let term = tab.terminal.blocking_read();
term.remove_observer(observer)
};
assert!(
!still_registered,
"stop must unregister the script's observer"
);
assert!(
tab.scripting
.script_ids
.first()
.copied()
.flatten()
.is_none()
);
assert!(matches!(
tab.scripting.script_forwarders.first(),
Some(None)
));
}
}