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