dscode-terminal 0.1.0

Terminal manager and PTY lifecycle for DSCode
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Sender};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use tracing::{debug, error, info, instrument};

use crate::TerminalEventSender;

// ── Public types ────────────────────────────────────────────────────────────

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TerminalInfo {
    pub id: String,
    pub name: String,
    pub shell: String,
    pub cwd: String,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalProfile {
    pub id: String,
    pub name: String,
    pub shell: String,
    pub args: Vec<String>,
    pub env: HashMap<String, String>,
    pub cwd: Option<String>,
    pub icon: Option<String>,
    pub color: Option<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalOptions {
    pub name: Option<String>,
    pub shell_path: Option<String>,
    pub shell_args: Vec<String>,
    pub cwd: Option<String>,
    pub env: HashMap<String, String>,
    pub profile_id: Option<String>,
}

/// STATE MACHINE: TerminalInstance
///
/// Tracks the lifecycle of a PTY-backed terminal instance.
///
/// State Diagram:
///
///   Created ──────► Running ──────► ShuttingDown ──────► Closed
///                      │                                    ▲
///                      │ (process exit,                     │
///                      │  read error)                       │
///                      └────────────────────────────────────┘
///
/// Transitions:
///   Created      -> Running      (start signal sent via start_sender channel)
///   Running      -> ShuttingDown (shutdown_signal flag set to true)
///   Running      -> Closed       (PTY process exits, reader thread detects EOF)
///   ShuttingDown -> Closed       (reader thread sees shutdown flag, exits loop)
///
/// Concurrency Invariant:
///   Terminal I/O uses std::sync::Mutex (not tokio) because PTY operations
///   are synchronous. The reader thread runs on a dedicated OS thread (not
///   tokio task). ShutdownSignal uses AtomicBool for lock-free cross-thread
///   signaling. State transitions should be synchronized through the
///   TerminalManager's terminals Mutex.
///
/// Interruption Table:
/// ┌──────────────┬──────────────────────────────────────────────────────────┐
/// │ State        │ What happens on crash/error                             │
/// ├──────────────┼──────────────────────────────────────────────────────────┤
/// │ Created      │ PTY allocated but reader waiting for start signal.      │
/// │              │ If app crashes: PTY master handle dropped, slave exits.  │
/// │              │ start_sender channel dropped, reader thread unblocks     │
/// │              │ and exits (recv() returns Err).                          │
/// ├──────────────┼──────────────────────────────────────────────────────────┤
/// │ Running      │ Reader thread actively reading PTY output.              │
/// │              │ If app crashes: PTY handles dropped, OS cleans up.      │
/// │              │ If shell process exits: reader gets EOF, -> Closed.     │
/// │              │ If reader thread panics: JoinHandle::join returns Err.  │
/// │              │ Writer can still try to write (will get error).         │
/// ├──────────────┼──────────────────────────────────────────────────────────┤
/// │ ShuttingDown │ Shutdown flag set. Reader thread checking flag each     │
/// │              │ iteration. May take up to one read timeout to notice.   │
/// │              │ If reader hangs on blocking read: may not shut down     │
/// │              │ gracefully. Consider: close PTY master to force EOF.    │
/// ├──────────────┼──────────────────────────────────────────────────────────┤
/// │ Closed       │ Reader thread joined. PTY resources released.           │
/// │              │ Terminal entry removed from TerminalManager map.        │
/// └──────────────┴──────────────────────────────────────────────────────────┘
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TerminalState {
    Created,
    Running,
    ShuttingDown,
    Closed,
}

// ── Internal helpers ───────────────────────────────────────────────────────

/// Shutdown signal for terminal reader thread.
struct ShutdownSignal {
    flag: Arc<AtomicBool>,
}

impl ShutdownSignal {
    fn new() -> Self {
        Self {
            flag: Arc::new(AtomicBool::new(false)),
        }
    }

    fn signal(&self) {
        self.flag.store(true, Ordering::SeqCst);
    }

    #[allow(dead_code)]
    fn is_shutdown(&self) -> bool {
        self.flag.load(Ordering::SeqCst)
    }

    fn clone_flag(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.flag)
    }
}

pub struct TerminalInstance {
    pub(crate) info: TerminalInfo,
    pub(crate) state: TerminalState,
    writer: Box<dyn Write + Send>,
    master: Arc<Mutex<Box<dyn MasterPty + Send>>>,
    start_sender: Option<Sender<()>>,
    shutdown_signal: ShutdownSignal,
    reader_handle: Option<JoinHandle<()>>,
}

// ── Arc-wrapped event sender ───────────────────────────────────────────────

/// Wrapper that allows an [`TerminalEventSender`] to be cheaply cloned
/// (via `Arc`) so it can be moved into the reader thread.
pub(crate) struct SharedEventSender {
    inner: Arc<dyn TerminalEventSender>,
}

impl SharedEventSender {
    pub(crate) fn new(sender: Box<dyn TerminalEventSender>) -> Self {
        Self {
            inner: Arc::from(sender),
        }
    }

    pub(crate) fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl TerminalEventSender for SharedEventSender {
    fn send_output(&self, terminal_id: &str, data: &str) {
        self.inner.send_output(terminal_id, data);
    }

    fn send_close(&self, terminal_id: &str) {
        self.inner.send_close(terminal_id);
    }
}

// ── Terminal manager ───────────────────────────────────────────────────────

pub struct TerminalManager {
    terminals: Arc<Mutex<HashMap<String, TerminalInstance>>>,
    profiles: Arc<Mutex<HashMap<String, TerminalProfile>>>,
    next_id: Arc<Mutex<u32>>,
    event_sender: SharedEventSender,
}

impl TerminalManager {
    pub fn new(event_sender: Box<dyn TerminalEventSender>) -> Self {
        Self {
            terminals: Arc::new(Mutex::new(HashMap::new())),
            profiles: Arc::new(Mutex::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(1)),
            event_sender: SharedEventSender::new(event_sender),
        }
    }

    // ===== Profile Management =====

    pub fn register_profile(&self, profile: TerminalProfile) -> Result<String, String> {
        let mut profiles = self.profiles.lock().unwrap_or_else(|e| {
            error!("profiles lock poisoned: {e}");
            e.into_inner()
        });
        let profile_id = profile.id.clone();

        if profiles.contains_key(&profile_id) {
            return Err(format!("Profile '{}' already exists", profile_id));
        }

        profiles.insert(profile_id.clone(), profile);
        Ok(profile_id)
    }

    pub fn unregister_profile(&self, profile_id: &str) -> Result<(), String> {
        let mut profiles = self.profiles.lock().unwrap_or_else(|e| {
            error!("profiles lock poisoned: {e}");
            e.into_inner()
        });
        profiles
            .remove(profile_id)
            .ok_or_else(|| format!("Profile '{}' not found", profile_id))?;
        Ok(())
    }

    pub fn get_profile(&self, profile_id: &str) -> Result<TerminalProfile, String> {
        let profiles = self.profiles.lock().unwrap_or_else(|e| {
            error!("profiles lock poisoned: {e}");
            e.into_inner()
        });
        profiles
            .get(profile_id)
            .cloned()
            .ok_or_else(|| format!("Profile '{}' not found", profile_id))
    }

    pub fn list_profiles(&self) -> Vec<TerminalProfile> {
        let profiles = self.profiles.lock().unwrap_or_else(|e| {
            error!("profiles lock poisoned: {e}");
            e.into_inner()
        });
        profiles.values().cloned().collect()
    }

    // ===== Terminal Creation =====

    pub fn create_terminal_with_options(
        &self,
        options: TerminalOptions,
    ) -> Result<String, String> {
        // Resolve profile if specified
        let (shell_cmd, shell_args, mut env_vars, profile_cwd) =
            if let Some(profile_id) = &options.profile_id {
                let profile = self.get_profile(profile_id)?;
                (profile.shell, profile.args, profile.env, profile.cwd)
            } else {
                let shell = options.shell_path.clone().unwrap_or_else(|| {
                    std::env::var("SHELL").unwrap_or_else(|_| {
                        if cfg!(target_os = "windows") {
                            "powershell.exe".to_string()
                        } else {
                            "/bin/bash".to_string()
                        }
                    })
                });
                (shell, options.shell_args.clone(), HashMap::new(), None)
            };

        // Merge environment variables (options override profile)
        for (key, value) in options.env {
            env_vars.insert(key, value);
        }

        // Determine working directory (options > profile > current)
        let working_dir = options.cwd.or(profile_cwd).unwrap_or_else(|| {
            std::env::current_dir()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_else(|_| "/".to_string())
        });

        // Get next terminal ID
        let id = {
            let mut next = self.next_id.lock().unwrap_or_else(|e| {
                error!("next_id lock poisoned: {e}");
                e.into_inner()
            });
            let current = *next;
            *next += 1;
            format!("terminal-{}", current)
        };

        // Create PTY system and open pair with initial size
        let pair = native_pty_system()
            .openpty(PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            })
            .map_err(|e| format!("Failed to create PTY: {}", e))?;

        let portable_pty::PtyPair { master, slave } = pair;

        // Create command with args and env
        let mut cmd = CommandBuilder::new(&shell_cmd);
        cmd.cwd(&working_dir);

        // Add shell arguments
        for arg in shell_args {
            cmd.arg(&arg);
        }

        // Add environment variables
        for (key, value) in env_vars {
            cmd.env(&key, &value);
        }

        // Spawn the shell
        let _child = slave
            .spawn_command(cmd)
            .map_err(|e| format!("Failed to spawn shell: {}", e))?;

        // Prepare IO handles
        let mut reader = master
            .try_clone_reader()
            .map_err(|e| format!("Failed to clone reader: {}", e))?;
        let writer = master
            .take_writer()
            .map_err(|e| format!("Failed to get writer: {}", e))?;
        let master = Arc::new(Mutex::new(master));

        // Create terminal info
        let terminal_name = options.name.unwrap_or_else(|| format!("Terminal {}", id));
        let info = TerminalInfo {
            id: id.clone(),
            name: terminal_name,
            shell: shell_cmd,
            cwd: working_dir,
        };

        // Create channel for start signal
        let (start_tx, start_rx) = mpsc::channel();

        // Create shutdown signal
        let shutdown_signal = ShutdownSignal::new();
        let shutdown_flag = shutdown_signal.clone_flag();

        // Clone the event sender for the reader thread
        let sender = self.event_sender.clone();

        // Start reading from PTY in a background thread
        let terminal_id = id.clone();
        let reader_handle = thread::spawn(move || {
            // Wait for ready signal from frontend
            if start_rx.recv().is_err() {
                error!("Failed to receive start signal for {}", terminal_id);
                return;
            }

            let mut buf = [0u8; 8192];
            loop {
                // Check shutdown signal
                if shutdown_flag.load(Ordering::SeqCst) {
                    info!("Shutdown signal received for {}", terminal_id);
                    break;
                }

                match reader.read(&mut buf) {
                    Ok(0) => {
                        // EOF - terminal closed
                        info!("Terminal {} closed (EOF)", terminal_id);
                        sender.send_close(&terminal_id);
                        break;
                    }
                    Ok(n) => {
                        // Send data to consumer
                        let data = String::from_utf8_lossy(&buf[0..n]).to_string();
                        sender.send_output(&terminal_id, &data);
                    }
                    Err(e) => {
                        // Check if this is a normal shutdown
                        if shutdown_flag.load(Ordering::SeqCst) {
                            debug!("Terminal {} shutdown complete", terminal_id);
                        } else {
                            error!("Error reading from PTY: {}", e);
                        }
                        break;
                    }
                }
            }
        });

        // Store terminal instance
        let terminal_instance = TerminalInstance {
            info: info.clone(),
            state: TerminalState::Created,
            writer,
            master: Arc::clone(&master),
            start_sender: Some(start_tx),
            shutdown_signal,
            reader_handle: Some(reader_handle),
        };

        {
            let mut terminals = self.terminals.lock().unwrap_or_else(|e| {
                error!("terminals lock poisoned: {e}");
                e.into_inner()
            });
            terminals.insert(id.clone(), terminal_instance);
        }

        Ok(id)
    }

    #[instrument(skip(self))]
    pub fn create_terminal(
        &self,
        name: Option<String>,
        shell: Option<String>,
        cwd: Option<String>,
    ) -> Result<String, String> {
        let options = TerminalOptions {
            name,
            shell_path: shell,
            shell_args: vec![],
            cwd,
            env: HashMap::new(),
            profile_id: None,
        };
        self.create_terminal_with_options(options)
    }

    pub fn write_to_terminal(&self, id: &str, data: &str) -> Result<(), String> {
        let mut terminals = self.terminals.lock().unwrap_or_else(|e| {
            error!("terminals lock poisoned: {e}");
            panic!("terminals lock is unrecoverable")
        });
        let terminal = terminals
            .get_mut(id)
            .ok_or_else(|| format!("Terminal {} not found", id))?;

        terminal
            .writer
            .write_all(data.as_bytes())
            .map_err(|e| format!("Failed to write to terminal: {}", e))?;

        terminal
            .writer
            .flush()
            .map_err(|e| format!("Failed to flush terminal: {}", e))?;

        Ok(())
    }

    pub fn resize_terminal(&self, id: &str, cols: u16, rows: u16) -> Result<(), String> {
        let mut terminals = self.terminals.lock().unwrap_or_else(|e| {
            error!("terminals lock poisoned: {e}");
            panic!("terminals lock is unrecoverable")
        });
        let terminal = terminals
            .get_mut(id)
            .ok_or_else(|| format!("Terminal {} not found", id))?;

        let master = terminal.master.lock().unwrap_or_else(|e| {
            error!("pty master lock poisoned: {e}");
            e.into_inner()
        });
        master
            .resize(PtySize {
                rows,
                cols,
                pixel_width: 0,
                pixel_height: 0,
            })
            .map_err(|e| format!("Failed to resize terminal: {}", e))
    }

    #[instrument(skip(self))]
    pub fn close_terminal(&self, id: &str) -> Result<(), String> {
        let mut terminals = self.terminals.lock().unwrap_or_else(|e| {
            error!("terminals lock poisoned: {e}");
            panic!("terminals lock is unrecoverable")
        });
        if let Some(mut terminal) = terminals.remove(id) {
            // Signal the reader thread to stop
            terminal.state = TerminalState::ShuttingDown;
            terminal.shutdown_signal.signal();

            // Drop the master to close the PTY (this will cause read to return EOF/error)
            drop(terminal.master);

            // Wait for the reader thread to finish (with timeout)
            if let Some(handle) = terminal.reader_handle.take() {
                // Don't block indefinitely - the drop of master should cause the read to return
                let _ = handle.join();
            }

            terminal.state = TerminalState::Closed;
            info!("Terminal {} closed and cleaned up", id);
            Ok(())
        } else {
            Err(format!("Terminal {} not found", id))
        }
    }

    pub fn list_terminals(&self) -> Vec<TerminalInfo> {
        let terminals = self.terminals.lock().unwrap_or_else(|e| {
            tracing::warn!("Terminals lock poisoned, recovering: {}", e);
            e.into_inner()
        });
        terminals.values().map(|t| t.info.clone()).collect()
    }

    pub fn start_reading(&self, id: &str) -> Result<(), String> {
        let mut terminals = self.terminals.lock().unwrap_or_else(|e| {
            tracing::warn!("Terminals lock poisoned, recovering: {}", e);
            e.into_inner()
        });
        let terminal = terminals
            .get_mut(id)
            .ok_or_else(|| format!("Terminal {} not found", id))?;

        if let Some(sender) = terminal.start_sender.take() {
            sender
                .send(())
                .map_err(|e| format!("Failed to send start signal: {}", e))?;
            terminal.state = TerminalState::Running;
        }

        Ok(())
    }

    /// Close all terminals (for shutdown)
    pub fn close_all(&self) {
        let mut terminals = self.terminals.lock().unwrap_or_else(|e| {
            tracing::warn!("Terminals lock poisoned, recovering: {}", e);
            e.into_inner()
        });
        let ids: Vec<String> = terminals.keys().cloned().collect();

        for id in ids {
            if let Some(mut terminal) = terminals.remove(&id) {
                terminal.state = TerminalState::ShuttingDown;
                terminal.shutdown_signal.signal();
                drop(terminal.master);
                if let Some(handle) = terminal.reader_handle.take() {
                    let _ = handle.join();
                }
                terminal.state = TerminalState::Closed;
            }
        }

        info!("All terminals closed");
    }
}

impl Drop for TerminalManager {
    fn drop(&mut self) {
        self.close_all();
    }
}

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

    /// A simple event sender that records events for testing.
    struct TestEventSender {
        outputs: std::sync::Mutex<Vec<(String, String)>>,
        closes: std::sync::Mutex<Vec<String>>,
    }

    impl TestEventSender {
        fn new() -> Self {
            Self {
                outputs: std::sync::Mutex::new(Vec::new()),
                closes: std::sync::Mutex::new(Vec::new()),
            }
        }
    }

    impl TerminalEventSender for TestEventSender {
        fn send_output(&self, terminal_id: &str, data: &str) {
            self.outputs
                .lock()
                .unwrap()
                .push((terminal_id.to_string(), data.to_string()));
        }

        fn send_close(&self, terminal_id: &str) {
            self.closes.lock().unwrap().push(terminal_id.to_string());
        }
    }

    fn make_manager() -> TerminalManager {
        TerminalManager::new(Box::new(TestEventSender::new()))
    }

    #[test]
    fn test_terminal_manager_creation() {
        let manager = make_manager();
        assert!(manager.list_terminals().is_empty());
        assert!(manager.list_profiles().is_empty());
    }

    #[test]
    fn test_list_terminals_on_empty_manager() {
        let manager = make_manager();
        let terminals = manager.list_terminals();
        assert!(terminals.is_empty(), "list_terminals on empty manager should return empty vec");
    }

    #[test]
    fn test_close_nonexistent_terminal() {
        let manager = make_manager();
        let result = manager.close_terminal("nonexistent-id");
        assert!(result.is_err(), "Closing a nonexistent terminal should fail");
        assert!(result.unwrap_err().contains("not found"));
    }

    #[test]
    fn test_profile_registration() {
        let manager = make_manager();

        let profile = TerminalProfile {
            id: "test-profile".to_string(),
            name: "Test Shell".to_string(),
            shell: "/bin/bash".to_string(),
            args: vec!["-l".to_string()],
            env: HashMap::new(),
            cwd: None,
            icon: None,
            color: None,
        };

        let result = manager.register_profile(profile.clone());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "test-profile");

        // Should fail if profile already exists
        let result2 = manager.register_profile(profile);
        assert!(result2.is_err());
    }

    #[test]
    fn test_profile_unregistration() {
        let manager = make_manager();

        let profile = TerminalProfile {
            id: "test-profile".to_string(),
            name: "Test Shell".to_string(),
            shell: "/bin/bash".to_string(),
            args: vec![],
            env: HashMap::new(),
            cwd: None,
            icon: None,
            color: None,
        };

        manager.register_profile(profile).unwrap();
        assert!(manager.get_profile("test-profile").is_ok());

        manager.unregister_profile("test-profile").unwrap();
        assert!(manager.get_profile("test-profile").is_err());
    }

    #[test]
    fn test_list_profiles() {
        let manager = make_manager();

        let profile1 = TerminalProfile {
            id: "profile1".to_string(),
            name: "Profile 1".to_string(),
            shell: "/bin/bash".to_string(),
            args: vec![],
            env: HashMap::new(),
            cwd: None,
            icon: None,
            color: None,
        };

        let profile2 = TerminalProfile {
            id: "profile2".to_string(),
            name: "Profile 2".to_string(),
            shell: "/bin/zsh".to_string(),
            args: vec![],
            env: HashMap::new(),
            cwd: None,
            icon: None,
            color: None,
        };

        manager.register_profile(profile1).unwrap();
        manager.register_profile(profile2).unwrap();

        let profiles = manager.list_profiles();
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_shutdown_signal() {
        let signal = ShutdownSignal::new();
        assert!(!signal.is_shutdown());

        signal.signal();
        assert!(signal.is_shutdown());

        // Clone flag should also show shutdown
        let flag = signal.clone_flag();
        assert!(flag.load(std::sync::atomic::Ordering::SeqCst));
    }

    #[test]
    fn test_terminal_info_clone() {
        let info = TerminalInfo {
            id: "test-terminal".to_string(),
            name: "Test Terminal".to_string(),
            shell: "/bin/bash".to_string(),
            cwd: "/home/user".to_string(),
        };

        let cloned = info.clone();
        assert_eq!(cloned.id, info.id);
        assert_eq!(cloned.name, info.name);
        assert_eq!(cloned.shell, info.shell);
        assert_eq!(cloned.cwd, info.cwd);
    }

    #[test]
    fn test_terminal_options_default() {
        let options = TerminalOptions {
            name: None,
            shell_path: None,
            shell_args: vec![],
            cwd: None,
            env: HashMap::new(),
            profile_id: None,
        };

        assert!(options.name.is_none());
        assert!(options.shell_path.is_none());
        assert!(options.shell_args.is_empty());
    }

    // ── Serde round-trip tests ──────────────────────────────────────────────────

    #[test]
    fn test_terminal_info_serde_roundtrip() {
        let info = TerminalInfo {
            id: "terminal-1".to_string(),
            name: "My Terminal".to_string(),
            shell: "/bin/zsh".to_string(),
            cwd: "/home/user/projects".to_string(),
        };
        let json = serde_json::to_string(&info).unwrap();
        let deserialized: TerminalInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.id, info.id);
        assert_eq!(deserialized.name, info.name);
        assert_eq!(deserialized.shell, info.shell);
        assert_eq!(deserialized.cwd, info.cwd);
    }

    #[test]
    fn test_terminal_profile_serde_roundtrip() {
        let mut env = HashMap::new();
        env.insert("TERM".to_string(), "xterm-256color".to_string());
        env.insert("LANG".to_string(), "en_US.UTF-8".to_string());

        let profile = TerminalProfile {
            id: "zsh-profile".to_string(),
            name: "ZSH".to_string(),
            shell: "/bin/zsh".to_string(),
            args: vec!["-l".to_string(), "-i".to_string()],
            env: env.clone(),
            cwd: Some("/home/user".to_string()),
            icon: Some("terminal".to_string()),
            color: Some("green".to_string()),
        };
        let json = serde_json::to_string(&profile).unwrap();
        let deserialized: TerminalProfile = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.id, profile.id);
        assert_eq!(deserialized.name, profile.name);
        assert_eq!(deserialized.shell, profile.shell);
        assert_eq!(deserialized.args, profile.args);
        assert_eq!(deserialized.env, profile.env);
        assert_eq!(deserialized.cwd, profile.cwd);
        assert_eq!(deserialized.icon, profile.icon);
        assert_eq!(deserialized.color, profile.color);
    }

    #[test]
    fn test_terminal_profile_serde_camel_case() {
        let mut env = HashMap::new();
        env.insert("KEY".to_string(), "val".to_string());
        let profile = TerminalProfile {
            id: "p1".to_string(),
            name: "P1".to_string(),
            shell: "/bin/bash".to_string(),
            args: vec![],
            env,
            cwd: Some("/tmp".to_string()),
            icon: Some("terminal".to_string()),
            color: None,
        };
        let json = serde_json::to_string(&profile).unwrap();
        // With #[serde(rename_all = "camelCase")], field names should be camelCase in JSON
        // "args" stays "args", "env" stays "env", "cwd" stays "cwd",
        // but verify the JSON is valid and round-trips correctly
        let deserialized: TerminalProfile = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.id, profile.id);
        assert_eq!(deserialized.name, profile.name);
        assert_eq!(deserialized.shell, profile.shell);
        assert_eq!(deserialized.args, profile.args);
        assert_eq!(deserialized.env, profile.env);
        assert_eq!(deserialized.cwd, profile.cwd);
        assert_eq!(deserialized.icon, profile.icon);
        assert_eq!(deserialized.color, profile.color);
    }

    #[test]
    fn test_terminal_options_serde_roundtrip() {
        let mut env = HashMap::new();
        env.insert("FOO".to_string(), "bar".to_string());

        let options = TerminalOptions {
            name: Some("My Term".to_string()),
            shell_path: Some("/bin/fish".to_string()),
            shell_args: vec!["-l".to_string()],
            cwd: Some("/home/user".to_string()),
            env: env.clone(),
            profile_id: Some("fish-profile".to_string()),
        };
        let json = serde_json::to_string(&options).unwrap();
        let deserialized: TerminalOptions = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.name, options.name);
        assert_eq!(deserialized.shell_path, options.shell_path);
        assert_eq!(deserialized.shell_args, options.shell_args);
        assert_eq!(deserialized.cwd, options.cwd);
        assert_eq!(deserialized.env, options.env);
        assert_eq!(deserialized.profile_id, options.profile_id);
    }

    #[test]
    fn test_terminal_options_serde_camel_case() {
        let options = TerminalOptions {
            name: None,
            shell_path: Some("/bin/bash".to_string()),
            shell_args: vec![],
            cwd: None,
            env: HashMap::new(),
            profile_id: Some("default".to_string()),
        };
        let json = serde_json::to_string(&options).unwrap();
        assert!(json.contains("shellPath"), "expected camelCase 'shellPath' in JSON: {}", json);
        assert!(json.contains("shellArgs"), "expected camelCase 'shellArgs' in JSON: {}", json);
        assert!(json.contains("profileId"), "expected camelCase 'profileId' in JSON: {}", json);
    }

    // ── TerminalProfile defaults ────────────────────────────────────────────────

    #[test]
    fn test_terminal_profile_default_values() {
        let profile = TerminalProfile {
            id: "default".to_string(),
            name: "Default".to_string(),
            shell: "/bin/bash".to_string(),
            args: vec![],
            env: HashMap::new(),
            cwd: None,
            icon: None,
            color: None,
        };
        assert_eq!(profile.id, "default");
        assert_eq!(profile.name, "Default");
        assert_eq!(profile.shell, "/bin/bash");
        assert!(profile.args.is_empty());
        assert!(profile.env.is_empty());
        assert!(profile.cwd.is_none());
        assert!(profile.icon.is_none());
        assert!(profile.color.is_none());
    }

    // ── TerminalState variants ─────────────────────────────────────────────────

    #[test]
    fn test_terminal_state_variants() {
        assert_eq!(TerminalState::Created, TerminalState::Created);
        assert_eq!(TerminalState::Running, TerminalState::Running);
        assert_eq!(TerminalState::ShuttingDown, TerminalState::ShuttingDown);
        assert_eq!(TerminalState::Closed, TerminalState::Closed);

        // All variants should be distinct
        assert_ne!(TerminalState::Created, TerminalState::Running);
        assert_ne!(TerminalState::Running, TerminalState::ShuttingDown);
        assert_ne!(TerminalState::ShuttingDown, TerminalState::Closed);
        assert_ne!(TerminalState::Created, TerminalState::Closed);
    }

    #[test]
    fn test_terminal_state_copy_equality() {
        let state1 = TerminalState::Running;
        let state2 = state1; // Copy, not move
        assert_eq!(state1, state2);
    }

    // ── TerminalEventSender trait mock ──────────────────────────────────────────

    #[test]
    fn test_mock_event_sender() {
        let sender = TestEventSender::new();
        // Verify the mock implementation works through the trait
        let sender_ref: &dyn TerminalEventSender = &sender;
        sender_ref.send_output("term-1", "hello world");
        sender_ref.send_close("term-1");

        assert_eq!(sender.outputs.lock().unwrap().len(), 1);
        assert_eq!(sender.outputs.lock().unwrap()[0], ("term-1".to_string(), "hello world".to_string()));
        assert_eq!(sender.closes.lock().unwrap().len(), 1);
        assert_eq!(sender.closes.lock().unwrap()[0], "term-1".to_string());
    }

    #[test]
    fn test_event_sender_multiple_outputs() {
        let sender = TestEventSender::new();
        sender.send_output("t1", "line1");
        sender.send_output("t1", "line2");
        sender.send_output("t2", "other");
        sender.send_close("t1");

        assert_eq!(sender.outputs.lock().unwrap().len(), 3);
        assert_eq!(sender.closes.lock().unwrap().len(), 1);
    }

    #[test]
    fn test_event_sender_boxed_dyn() {
        // Verify the trait object can be boxed (as required by TerminalManager::new)
        let sender: Box<dyn TerminalEventSender> = Box::new(TestEventSender::new());
        sender.send_output("t1", "data");
        sender.send_close("t1");
    }
}