Skip to main content

glass_dev/development/
process.rs

1use super::{DevelopmentError, DevelopmentResult, MAX_PROCESS_OUTPUT_BYTES};
2use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system};
3use serde::{Deserialize, Serialize};
4use std::time::Instant;
5use std::{
6    collections::{BTreeMap, VecDeque},
7    ffi::OsString,
8    io::{Read, Write},
9    path::PathBuf,
10    sync::{Arc, Mutex, mpsc},
11    thread,
12    time::{Duration, SystemTime, UNIX_EPOCH},
13};
14
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
16#[serde(rename_all = "camelCase")]
17pub enum ProcessState {
18    Running,
19    Exited { code: Option<u32> },
20    Stopped,
21    Failed,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
25#[serde(rename_all = "camelCase")]
26pub enum ProcessHealth {
27    Starting,
28    Healthy,
29    Exited,
30    Stopped,
31    Failed,
32}
33
34impl ProcessHealth {
35    /// Human-readable label for terminal and TUI surfaces.
36    pub fn label(&self) -> &'static str {
37        match self {
38            Self::Starting => "starting",
39            Self::Healthy => "healthy",
40            Self::Exited => "exited",
41            Self::Stopped => "stopped",
42            Self::Failed => "failed",
43        }
44    }
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
48#[serde(rename_all = "camelCase")]
49pub struct ProcessSnapshot {
50    pub name: String,
51    pub command: String,
52    pub pid: Option<u32>,
53    pub state: ProcessState,
54    pub started_at_ms: u64,
55    pub output: String,
56    pub pty: bool,
57    pub cwd: PathBuf,
58    pub health: ProcessHealth,
59    #[serde(default)]
60    pub detected_urls: Vec<String>,
61}
62
63struct RunningProcess {
64    snapshot: ProcessSnapshot,
65    child: Box<dyn Child + Send + Sync>,
66    master: Option<Box<dyn MasterPty + Send>>,
67    writer: Option<Box<dyn Write + Send>>,
68    output: Arc<Mutex<VecDeque<u8>>>,
69    reader: Option<thread::JoinHandle<()>>,
70    reader_done: mpsc::Receiver<()>,
71    #[cfg(windows)]
72    job: WindowsJob,
73}
74
75pub struct ProcessManager {
76    root: PathBuf,
77    processes: BTreeMap<String, RunningProcess>,
78}
79
80impl std::fmt::Debug for ProcessManager {
81    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        formatter
83            .debug_struct("ProcessManager")
84            .field("root", &self.root)
85            .field("process_count", &self.processes.len())
86            .finish()
87    }
88}
89
90impl ProcessManager {
91    pub fn new(root: impl Into<PathBuf>) -> Self {
92        Self {
93            root: root.into(),
94            processes: BTreeMap::new(),
95        }
96    }
97
98    pub fn start(&mut self, name: &str, command: &str) -> DevelopmentResult<ProcessSnapshot> {
99        validate_name(name)?;
100        if command.trim().is_empty() || command.len() > 4 * 1024 {
101            return Err(DevelopmentError::InvalidInput(
102                "process command must be non-empty and at most 4096 bytes".into(),
103            ));
104        }
105        let builder = shell_command(command);
106        self.start_command(name, command, builder, self.root.clone())
107    }
108
109    /// Start an exact argv vector in a PTY without interpolating a shell command.
110    ///
111    /// DAP reverse requests use this path so adapter-provided arguments remain
112    /// separate values while Glass retains process-tree ownership and output.
113    pub fn start_argv(
114        &mut self,
115        name: &str,
116        arguments: &[String],
117        cwd: &std::path::Path,
118        environment: &BTreeMap<String, String>,
119    ) -> DevelopmentResult<ProcessSnapshot> {
120        validate_name(name)?;
121        if arguments.is_empty()
122            || arguments.len() > 256
123            || arguments.iter().any(|argument| argument.len() > 16 * 1024)
124        {
125            return Err(DevelopmentError::InvalidInput(
126                "process argv requires 1..=256 arguments of at most 16384 bytes".into(),
127            ));
128        }
129        if environment.len() > 256
130            || environment
131                .iter()
132                .any(|(key, value)| key.is_empty() || key.contains('=') || value.len() > 64 * 1024)
133        {
134            return Err(DevelopmentError::InvalidInput(
135                "process environment is invalid or exceeds its bounded limits".into(),
136            ));
137        }
138        let root = self.root.canonicalize()?;
139        let cwd = cwd.canonicalize()?;
140        if !cwd.starts_with(&root) {
141            return Err(DevelopmentError::InvalidInput(format!(
142                "process cwd {} escapes workspace {}",
143                cwd.display(),
144                root.display()
145            )));
146        }
147        let mut builder =
148            CommandBuilder::from_argv(arguments.iter().map(OsString::from).collect::<Vec<_>>());
149        for (key, value) in environment {
150            builder.env(key, value);
151        }
152        let display = serde_json::to_string(arguments)
153            .map_err(|error| DevelopmentError::Process(error.to_string()))?;
154        self.start_command(name, &display, builder, cwd)
155    }
156
157    fn start_command(
158        &mut self,
159        name: &str,
160        display_command: &str,
161        mut builder: CommandBuilder,
162        cwd: PathBuf,
163    ) -> DevelopmentResult<ProcessSnapshot> {
164        self.poll()?;
165        if self.processes.len() >= 32 {
166            return Err(DevelopmentError::Process(
167                "process manager is limited to 32 registered processes".into(),
168            ));
169        }
170        if self.processes.contains_key(name) {
171            return Err(DevelopmentError::Process(format!(
172                "process {name} is already registered"
173            )));
174        }
175        let pty = native_pty_system()
176            .openpty(PtySize {
177                rows: 32,
178                cols: 120,
179                pixel_width: 0,
180                pixel_height: 0,
181            })
182            .map_err(|error| DevelopmentError::Process(error.to_string()))?;
183        builder.cwd(cwd.as_os_str());
184        let child = pty
185            .slave
186            .spawn_command(builder)
187            .map_err(|error| DevelopmentError::Process(error.to_string()))?;
188        #[cfg(windows)]
189        let mut child = child;
190        let pid = child.process_id();
191        #[cfg(windows)]
192        let job = match pid
193            .ok_or_else(|| std::io::Error::other("PTY child PID is unavailable"))
194            .and_then(WindowsJob::assign)
195        {
196            Ok(job) => job,
197            Err(error) => {
198                let _ = child.kill();
199                return Err(DevelopmentError::Process(format!(
200                    "failed to place PTY process in a kill-on-close Windows Job Object: {error}"
201                )));
202            }
203        };
204        let reader = pty
205            .master
206            .try_clone_reader()
207            .map_err(|error| DevelopmentError::Process(error.to_string()))?;
208        let writer = pty
209            .master
210            .take_writer()
211            .map_err(|error| DevelopmentError::Process(error.to_string()))?;
212        #[cfg(windows)]
213        let writer = {
214            let mut writer = writer;
215            // ConPTY asks the terminal for its cursor position (`CSI 6 n`)
216            // before dispatching some short-lived commands. Seed the canonical
217            // response so the shell cannot stall before Glass' reader starts.
218            writer.write_all(b"\x1b[1;1R")?;
219            writer.flush()?;
220            writer
221        };
222        let output = Arc::new(Mutex::new(VecDeque::new()));
223        let reader_output = Arc::clone(&output);
224        let (reader_done_tx, reader_done) = mpsc::channel();
225        let reader_handle = thread::Builder::new()
226            .name(format!("glass-process-{name}"))
227            .spawn(move || {
228                read_output(reader, reader_output);
229                let _ = reader_done_tx.send(());
230            })
231            .map_err(DevelopmentError::Io)?;
232        let snapshot = ProcessSnapshot {
233            name: name.into(),
234            command: display_command.into(),
235            pid,
236            state: ProcessState::Running,
237            started_at_ms: now_ms(),
238            output: String::new(),
239            pty: true,
240            cwd,
241            health: ProcessHealth::Starting,
242            detected_urls: Vec::new(),
243        };
244        self.processes.insert(
245            name.into(),
246            RunningProcess {
247                snapshot: snapshot.clone(),
248                child,
249                master: Some(pty.master),
250                writer: Some(writer),
251                output,
252                reader: Some(reader_handle),
253                reader_done,
254                #[cfg(windows)]
255                job,
256            },
257        );
258        Ok(snapshot)
259    }
260
261    pub fn send_input(&mut self, name: &str, input: &str) -> DevelopmentResult<()> {
262        if input.len() > 16 * 1024 {
263            return Err(DevelopmentError::InvalidInput(
264                "process input exceeds 16384 bytes".into(),
265            ));
266        }
267        let process = self
268            .processes
269            .get_mut(name)
270            .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
271        let writer = process
272            .writer
273            .as_mut()
274            .ok_or_else(|| DevelopmentError::Process("process input is closed".into()))?;
275        writer.write_all(input.as_bytes())?;
276        writer.flush()?;
277        Ok(())
278    }
279
280    /// Finalize process input while retaining output and lifecycle tracking.
281    ///
282    /// Bounded, non-interactive commands use this after spawning. Unix shells
283    /// observe EOF. Windows ConPTY turns a closed input pipe into Control-C, so
284    /// its owned console receives the platform EOF key (Control-Z then Enter)
285    /// and retains the input handle until the child exits naturally.
286    pub fn close_input(&mut self, name: &str) -> DevelopmentResult<()> {
287        let process = self
288            .processes
289            .get_mut(name)
290            .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
291
292        #[cfg(windows)]
293        if let Some(writer) = process.writer.as_mut() {
294            writer.write_all(b"\x1a\r\n")?;
295            writer.flush()?;
296            return Ok(());
297        }
298
299        #[cfg(not(windows))]
300        process.writer.take();
301        Ok(())
302    }
303
304    /// Run a bounded non-interactive command without routing it through ConPTY.
305    ///
306    /// Windows pseudo consoles intentionally model an interactive terminal and
307    /// do not provide portable pipe-EOF semantics. One-shot commands use normal
308    /// pipes while retaining the same Job Object descendant ownership.
309    #[cfg(windows)]
310    pub fn run_bounded(
311        &self,
312        name: &str,
313        command: &str,
314        timeout: Duration,
315    ) -> DevelopmentResult<ProcessSnapshot> {
316        validate_name(name)?;
317        if command.trim().is_empty() || command.len() > 4 * 1024 {
318            return Err(DevelopmentError::InvalidInput(
319                "process command must be non-empty and at most 4096 bytes".into(),
320            ));
321        }
322        let started_at_ms = now_ms();
323        let mut child = std::process::Command::new("cmd.exe")
324            .args(["/D", "/Q", "/C", command])
325            .current_dir(&self.root)
326            .stdin(std::process::Stdio::null())
327            .stdout(std::process::Stdio::piped())
328            .stderr(std::process::Stdio::piped())
329            .spawn()?;
330        let job = WindowsJob::assign(child.id()).map_err(|error| {
331            let _ = child.kill();
332            DevelopmentError::Process(format!(
333                "failed to own bounded Windows process tree: {error}"
334            ))
335        })?;
336        let output = Arc::new(Mutex::new(VecDeque::new()));
337        let mut readers = Vec::with_capacity(2);
338        if let Some(reader) = child.stdout.take() {
339            let reader_output = Arc::clone(&output);
340            readers.push(thread::spawn(move || read_output(reader, reader_output)));
341        }
342        if let Some(reader) = child.stderr.take() {
343            let reader_output = Arc::clone(&output);
344            readers.push(thread::spawn(move || read_output(reader, reader_output)));
345        }
346        let deadline = Instant::now() + timeout;
347        let status = loop {
348            if let Some(status) = child.try_wait()? {
349                break status;
350            }
351            if Instant::now() >= deadline {
352                // SAFETY: `job` exclusively owns this valid handle.
353                unsafe {
354                    windows_sys::Win32::System::JobObjects::TerminateJobObject(job.handle, 1)
355                };
356                let _ = child.wait();
357                for reader in readers {
358                    let _ = reader.join();
359                }
360                return Err(DevelopmentError::Process(format!(
361                    "process {name} exceeded {} seconds",
362                    timeout.as_secs()
363                )));
364            }
365            thread::sleep(Duration::from_millis(20));
366        };
367        for reader in readers {
368            reader
369                .join()
370                .map_err(|_| DevelopmentError::Process("process output reader panicked".into()))?;
371        }
372        let output = output_string(&output);
373        Ok(ProcessSnapshot {
374            name: name.into(),
375            command: command.into(),
376            pid: Some(child.id()),
377            state: ProcessState::Exited {
378                code: status.code().map(|code| code as u32),
379            },
380            started_at_ms,
381            output: output.clone(),
382            pty: false,
383            cwd: self.root.clone(),
384            health: if status.success() {
385                ProcessHealth::Exited
386            } else {
387                ProcessHealth::Failed
388            },
389            detected_urls: detect_urls(&output),
390        })
391    }
392
393    pub fn resize(&mut self, name: &str, cols: u16, rows: u16) -> DevelopmentResult<()> {
394        if cols == 0 || rows == 0 {
395            return Err(DevelopmentError::InvalidInput(
396                "PTY dimensions must be non-zero".into(),
397            ));
398        }
399        let process = self
400            .processes
401            .get_mut(name)
402            .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
403        process
404            .master
405            .as_ref()
406            .ok_or_else(|| DevelopmentError::Process("process PTY is closed".into()))?
407            .resize(PtySize {
408                rows,
409                cols,
410                pixel_width: 0,
411                pixel_height: 0,
412            })
413            .map_err(|error| DevelopmentError::Process(error.to_string()))
414    }
415
416    pub fn stop(&mut self, name: &str) -> DevelopmentResult<ProcessSnapshot> {
417        let process = self
418            .processes
419            .get_mut(name)
420            .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
421        terminate_process_tree(process)?;
422        finish_reader(process)?;
423        process.snapshot.state = ProcessState::Stopped;
424        process.snapshot.health = ProcessHealth::Stopped;
425        Ok(snapshot(process))
426    }
427
428    pub fn restart(&mut self, name: &str) -> DevelopmentResult<ProcessSnapshot> {
429        let command = self
430            .processes
431            .get(name)
432            .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?
433            .snapshot
434            .command
435            .clone();
436        if matches!(
437            self.processes
438                .get(name)
439                .map(|process| &process.snapshot.state),
440            Some(ProcessState::Running)
441        ) {
442            self.stop(name)?;
443        }
444        self.processes.remove(name);
445        self.start(name, &command)
446    }
447
448    pub fn remove(&mut self, name: &str) -> DevelopmentResult<ProcessSnapshot> {
449        if matches!(
450            self.processes
451                .get(name)
452                .map(|process| &process.snapshot.state),
453            Some(ProcessState::Running)
454        ) {
455            return Err(DevelopmentError::Conflict(format!(
456                "stop process {name} before removing it"
457            )));
458        }
459        self.processes
460            .remove(name)
461            .map(|process| snapshot(&process))
462            .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))
463    }
464
465    pub fn poll(&mut self) -> DevelopmentResult<Vec<ProcessSnapshot>> {
466        let mut updated = Vec::new();
467        for process in self.processes.values_mut() {
468            if matches!(process.snapshot.state, ProcessState::Running)
469                && let Some(status) = process
470                    .child
471                    .try_wait()
472                    .map_err(|error| DevelopmentError::Process(error.to_string()))?
473            {
474                process.snapshot.state = ProcessState::Exited {
475                    code: Some(status.exit_code()),
476                };
477                process.snapshot.health = if status.success() {
478                    ProcessHealth::Exited
479                } else {
480                    ProcessHealth::Failed
481                };
482                finish_reader(process)?;
483            }
484            process.snapshot.output = output_string(&process.output);
485            process.snapshot.detected_urls = detect_urls(&process.snapshot.output);
486            if matches!(process.snapshot.state, ProcessState::Running)
487                && (!process.snapshot.detected_urls.is_empty()
488                    || process
489                        .snapshot
490                        .output
491                        .to_ascii_lowercase()
492                        .contains("ready"))
493            {
494                process.snapshot.health = ProcessHealth::Healthy;
495            }
496            updated.push(snapshot(process));
497        }
498        Ok(updated)
499    }
500
501    pub fn list(&mut self) -> Vec<ProcessSnapshot> {
502        self.list_checked().unwrap_or_else(|error| {
503            self.processes
504                .values_mut()
505                .map(|process| {
506                    process.snapshot.state = ProcessState::Failed;
507                    process.snapshot.health = ProcessHealth::Failed;
508                    let mut value = snapshot(process);
509                    value.output =
510                        format!("{}\n[process state unavailable: {error}]", value.output);
511                    value
512                })
513                .collect()
514        })
515    }
516
517    /// Return current process state without discarding polling failures.
518    pub fn list_checked(&mut self) -> DevelopmentResult<Vec<ProcessSnapshot>> {
519        self.poll()
520    }
521
522    pub fn output(&self, name: &str) -> DevelopmentResult<String> {
523        let process = self
524            .processes
525            .get(name)
526            .ok_or_else(|| DevelopmentError::NotFound(format!("process {name}")))?;
527        Ok(output_string(&process.output))
528    }
529}
530
531impl Drop for ProcessManager {
532    fn drop(&mut self) {
533        for process in self.processes.values_mut() {
534            if matches!(process.snapshot.state, ProcessState::Running) {
535                let _ = terminate_process_tree(process);
536                let _ = finish_reader(process);
537            }
538        }
539    }
540}
541
542fn finish_reader(process: &mut RunningProcess) -> DevelopmentResult<()> {
543    process.writer.take();
544    #[cfg(windows)]
545    process.master.take();
546    if process.reader.is_none() {
547        return Ok(());
548    }
549    match process.reader_done.recv_timeout(Duration::from_secs(2)) {
550        Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => {}
551        Err(mpsc::RecvTimeoutError::Timeout) => {
552            return Err(DevelopmentError::Process(
553                "PTY output did not close within 2 seconds after process exit".into(),
554            ));
555        }
556    }
557    let reader = process
558        .reader
559        .take()
560        .expect("reader existence checked above");
561    reader
562        .join()
563        .map_err(|_| DevelopmentError::Process("PTY output reader panicked".into()))
564}
565
566fn terminate_process_tree(process: &mut RunningProcess) -> DevelopmentResult<()> {
567    #[cfg(unix)]
568    {
569        let pid = process.snapshot.pid.ok_or_else(|| {
570            DevelopmentError::Process("owned PTY process has no process-group ID".into())
571        })?;
572        // portable-pty creates a new session for the spawned command on Unix;
573        // its PID is therefore also the process-group ID. Signal the group so
574        // grandchildren cannot outlive the owning Glass workspace.
575        for (signal, grace) in [
576            (libc::SIGINT, Duration::from_millis(250)),
577            (libc::SIGTERM, Duration::from_millis(500)),
578        ] {
579            let result = unsafe { libc::kill(-(pid as i32), signal) };
580            if result != 0 {
581                let error = std::io::Error::last_os_error();
582                if error.raw_os_error() != Some(libc::ESRCH) {
583                    return Err(DevelopmentError::Process(format!(
584                        "failed to signal process group {pid}: {error}"
585                    )));
586                }
587            }
588            let deadline = Instant::now() + grace;
589            while Instant::now() < deadline {
590                if process
591                    .child
592                    .try_wait()
593                    .map_err(|error| DevelopmentError::Process(error.to_string()))?
594                    .is_some()
595                {
596                    return Ok(());
597                }
598                std::thread::sleep(Duration::from_millis(20));
599            }
600        }
601        let result = unsafe { libc::kill(-(pid as i32), libc::SIGKILL) };
602        if result != 0 && std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) {
603            return Err(DevelopmentError::Process(format!(
604                "failed to kill process group {pid}: {}",
605                std::io::Error::last_os_error()
606            )));
607        }
608        let _ = process.child.wait();
609        Ok(())
610    }
611
612    #[cfg(windows)]
613    {
614        // SAFETY: the handle is created and exclusively owned by WindowsJob
615        // until this process record is dropped.
616        let terminated = unsafe {
617            windows_sys::Win32::System::JobObjects::TerminateJobObject(process.job.handle, 1)
618        };
619        if terminated == 0 {
620            return Err(DevelopmentError::Process(format!(
621                "failed to terminate Windows process job: {}",
622                std::io::Error::last_os_error()
623            )));
624        }
625        let _ = process.child.wait();
626        return Ok(());
627    }
628
629    #[cfg(not(any(unix, windows)))]
630    process
631        .child
632        .kill()
633        .map_err(|error| DevelopmentError::Process(error.to_string()))?;
634    #[cfg(not(any(unix, windows)))]
635    let _ = process.child.wait();
636    #[cfg(not(any(unix, windows)))]
637    Ok(())
638}
639
640#[cfg(windows)]
641struct WindowsJob {
642    handle: windows_sys::Win32::Foundation::HANDLE,
643}
644
645#[cfg(windows)]
646// SAFETY: WindowsJob uniquely owns the kernel handle and only uses it through
647// thread-safe kernel object operations; Drop closes it exactly once.
648unsafe impl Send for WindowsJob {}
649
650#[cfg(windows)]
651impl WindowsJob {
652    fn assign(pid: u32) -> std::io::Result<Self> {
653        use windows_sys::Win32::{
654            Foundation::CloseHandle,
655            System::{
656                JobObjects::{
657                    AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
658                    JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
659                    SetInformationJobObject,
660                },
661                Threading::{
662                    OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA,
663                    PROCESS_TERMINATE,
664                },
665            },
666        };
667        // SAFETY: null security/name creates an unnamed job owned by this process.
668        let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
669        if handle.is_null() {
670            return Err(std::io::Error::last_os_error());
671        }
672        let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
673        limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
674        // SAFETY: the information pointer and size match the requested class.
675        let configured = unsafe {
676            SetInformationJobObject(
677                handle,
678                JobObjectExtendedLimitInformation,
679                (&raw const limits).cast(),
680                std::mem::size_of_val(&limits) as u32,
681            )
682        };
683        // SAFETY: requested rights are limited to job assignment and lifecycle.
684        let process = unsafe {
685            OpenProcess(
686                PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION,
687                0,
688                pid,
689            )
690        };
691        if configured == 0 || process.is_null() {
692            // SAFETY: non-null job handle is owned here.
693            unsafe { CloseHandle(handle) };
694            return Err(std::io::Error::last_os_error());
695        }
696        // SAFETY: both handles are valid and owned for the duration of the call.
697        let assigned = unsafe { AssignProcessToJobObject(handle, process) };
698        // SAFETY: the temporary process handle is no longer needed.
699        unsafe { CloseHandle(process) };
700        if assigned == 0 {
701            // SAFETY: assignment failed; closing the owned job is sufficient cleanup.
702            unsafe { CloseHandle(handle) };
703            return Err(std::io::Error::last_os_error());
704        }
705        Ok(Self { handle })
706    }
707}
708
709#[cfg(windows)]
710impl Drop for WindowsJob {
711    fn drop(&mut self) {
712        // SAFETY: this type exclusively owns the job handle.
713        unsafe { windows_sys::Win32::Foundation::CloseHandle(self.handle) };
714    }
715}
716
717fn snapshot(process: &RunningProcess) -> ProcessSnapshot {
718    let mut snapshot = process.snapshot.clone();
719    snapshot.output = output_string(&process.output);
720    snapshot
721}
722
723fn read_output(mut reader: impl Read, output: Arc<Mutex<VecDeque<u8>>>) {
724    let mut buffer = [0_u8; 1024];
725    loop {
726        match reader.read(&mut buffer) {
727            Ok(0) | Err(_) => break,
728            Ok(count) => {
729                if let Ok(mut output) = output.lock() {
730                    for byte in &buffer[..count] {
731                        if output.len() == MAX_PROCESS_OUTPUT_BYTES {
732                            output.pop_front();
733                        }
734                        output.push_back(*byte);
735                    }
736                }
737            }
738        }
739    }
740}
741
742fn output_string(output: &Mutex<VecDeque<u8>>) -> String {
743    output
744        .lock()
745        .map(|value| {
746            let bytes: Vec<u8> = value.iter().copied().collect();
747            String::from_utf8_lossy(&bytes).into_owned()
748        })
749        .unwrap_or_else(|_| "process output unavailable".into())
750}
751
752fn shell_command(command: &str) -> CommandBuilder {
753    #[cfg(windows)]
754    {
755        let mut builder = CommandBuilder::new("cmd.exe");
756        builder.args(["/C", command]);
757        builder
758    }
759    #[cfg(not(windows))]
760    {
761        let mut builder = CommandBuilder::new("sh");
762        builder.args(["-lc", command]);
763        builder
764    }
765}
766
767fn validate_name(name: &str) -> DevelopmentResult<()> {
768    if name.is_empty()
769        || name.len() > 64
770        || name
771            .chars()
772            .any(|character| !(character.is_ascii_alphanumeric() || "-_.".contains(character)))
773    {
774        return Err(DevelopmentError::InvalidInput(
775            "process name must be 1-64 ASCII letters, digits, '.', '_' or '-'".into(),
776        ));
777    }
778    Ok(())
779}
780
781fn now_ms() -> u64 {
782    SystemTime::now()
783        .duration_since(UNIX_EPOCH)
784        .map_or(0, |duration| duration.as_millis() as u64)
785}
786
787fn detect_urls(output: &str) -> Vec<String> {
788    let mut urls = output
789        .split_whitespace()
790        .filter_map(|token| {
791            let token = token.trim_matches(|character: char| {
792                matches!(character, '(' | ')' | '[' | ']' | ',' | ';' | '\'' | '"')
793            });
794            let parsed = url::Url::parse(token).ok()?;
795            if matches!(parsed.scheme(), "http" | "https")
796                && matches!(
797                    parsed.host_str(),
798                    Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
799                )
800            {
801                Some(parsed.to_string())
802            } else {
803                None
804            }
805        })
806        .take(8)
807        .collect::<Vec<_>>();
808    urls.sort();
809    urls.dedup();
810    urls
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816    use std::time::Duration;
817
818    #[test]
819    fn pty_process_emits_output_and_exits() {
820        let mut manager = ProcessManager::new(std::env::temp_dir());
821        manager.start("echo", "echo glass-process-ok").unwrap();
822        manager.close_input("echo").unwrap();
823        for _ in 0..40 {
824            let snapshots = manager.poll().unwrap();
825            if snapshots[0].state != ProcessState::Running
826                && !manager.output("echo").unwrap().is_empty()
827            {
828                break;
829            }
830            std::thread::sleep(Duration::from_millis(10));
831        }
832        let output = manager.output("echo").unwrap();
833        assert!(output.contains("glass-process-ok"), "output={output:?}");
834        assert!(matches!(
835            manager.list()[0].state,
836            ProcessState::Exited { .. }
837        ));
838    }
839
840    #[test]
841    fn process_detects_local_dev_server_urls_and_can_restart() {
842        let mut manager = ProcessManager::new(std::env::temp_dir());
843        manager
844            .start("server", "echo ready http://localhost:3000")
845            .unwrap();
846        for _ in 0..200 {
847            let snapshots = manager.poll().unwrap();
848            if !snapshots[0].detected_urls.is_empty() {
849                break;
850            }
851            std::thread::sleep(Duration::from_millis(10));
852        }
853        assert_eq!(
854            manager.list()[0].detected_urls,
855            vec!["http://localhost:3000/".to_string()]
856        );
857        manager.restart("server").unwrap();
858        assert!(matches!(
859            manager.list()[0].state,
860            ProcessState::Running | ProcessState::Exited { .. }
861        ));
862    }
863
864    #[cfg(unix)]
865    #[test]
866    fn stopping_owned_process_terminates_its_descendant_tree() {
867        let mut manager = ProcessManager::new(std::env::temp_dir());
868        manager
869            .start("tree", "sleep 30 & printf 'child=%s\\n' \"$!\"; wait")
870            .unwrap();
871        let child_pid = (0..100).find_map(|_| {
872            let _ = manager.poll();
873            let pid = manager.output("tree").ok().and_then(|output| {
874                output
875                    .lines()
876                    .find_map(|line| line.trim().strip_prefix("child="))?
877                    .parse::<i32>()
878                    .ok()
879            });
880            if pid.is_none() {
881                std::thread::sleep(Duration::from_millis(20));
882            }
883            pid
884        });
885        let child_pid = child_pid.expect("descendant PID must be reported by the PTY process");
886
887        manager.stop("tree").unwrap();
888        let gone = (0..50).any(|_| {
889            // SAFETY: signal zero performs a read-only existence probe.
890            let result = unsafe { libc::kill(child_pid, 0) };
891            if result != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) {
892                true
893            } else {
894                std::thread::sleep(Duration::from_millis(20));
895                false
896            }
897        });
898        assert!(
899            gone,
900            "descendant process {child_pid} survived group shutdown"
901        );
902    }
903}