Skip to main content

pitchfork_cli/tui/
app.rs

1use crate::Result;
2use crate::daemon::Daemon;
3use crate::daemon_id::DaemonId;
4use crate::daemon_list::{DaemonListEntry, NamespaceFilter};
5use crate::ipc::client::IpcClient;
6use crate::log_store::LogStore;
7use crate::log_store::sqlite::LOG_STORE;
8use crate::pitchfork_toml::{
9    CronRetrigger, HealthCmd, HealthHttp, HealthPort, PitchforkToml, PitchforkTomlAuto,
10    PitchforkTomlCron, PitchforkTomlDaemon, ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort, Retry,
11    RunCommand, namespace_from_path,
12};
13use crate::procs::{PROCS, ProcessStats};
14use crate::settings::settings;
15use fuzzy_matcher::FuzzyMatcher;
16use fuzzy_matcher::skim::SkimMatcherV2;
17use indexmap::IndexMap;
18use listeners::Listener;
19use std::collections::{HashMap, HashSet, VecDeque};
20use std::path::PathBuf;
21use std::sync::Arc;
22use std::time::Instant;
23
24/// Convert character index to byte index for UTF-8 strings
25fn char_to_byte_index(s: &str, char_idx: usize) -> usize {
26    s.char_indices()
27        .nth(char_idx)
28        .map(|(i, _)| i)
29        .unwrap_or(s.len())
30}
31
32/// A snapshot of stats at a point in time
33#[derive(Debug, Clone, Copy)]
34pub struct StatsSnapshot {
35    pub cpu_percent: f32,
36    pub memory_bytes: u64,
37    pub disk_read_bytes: u64,
38    pub disk_write_bytes: u64,
39}
40
41impl From<&ProcessStats> for StatsSnapshot {
42    fn from(stats: &ProcessStats) -> Self {
43        Self {
44            cpu_percent: stats.cpu_percent,
45            memory_bytes: stats.memory_bytes,
46            disk_read_bytes: stats.disk_read_bytes,
47            disk_write_bytes: stats.disk_write_bytes,
48        }
49    }
50}
51
52/// Historical stats for a daemon
53#[derive(Debug, Clone, Default)]
54pub struct StatsHistory {
55    pub samples: VecDeque<StatsSnapshot>,
56}
57
58impl StatsHistory {
59    pub fn push(&mut self, snapshot: StatsSnapshot) {
60        self.samples.push_back(snapshot);
61        let max_history = settings().tui.stat_history.max(1) as usize;
62        while self.samples.len() > max_history {
63            self.samples.pop_front();
64        }
65    }
66
67    pub fn cpu_values(&self) -> Vec<f32> {
68        self.samples.iter().map(|s| s.cpu_percent).collect()
69    }
70
71    pub fn memory_values(&self) -> Vec<u64> {
72        self.samples.iter().map(|s| s.memory_bytes).collect()
73    }
74
75    pub fn disk_read_values(&self) -> Vec<u64> {
76        self.samples.iter().map(|s| s.disk_read_bytes).collect()
77    }
78
79    pub fn disk_write_values(&self) -> Vec<u64> {
80        self.samples.iter().map(|s| s.disk_write_bytes).collect()
81    }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum View {
86    Dashboard,
87    Logs,
88    Network,
89    Help,
90    Confirm,
91    Details,
92    ConfigEditor,
93    ConfigFileSelect,
94}
95
96/// Edit mode for the config editor
97#[derive(Debug, Clone, PartialEq)]
98pub enum EditMode {
99    Create,
100    Edit { original_id: String },
101}
102
103/// Form field value types
104#[derive(Debug, Clone)]
105pub enum FormFieldValue {
106    Text(String),
107    OptionalText(Option<String>),
108    Number(u32),
109    OptionalNumber(Option<u64>),
110    OptionalPort(Option<ReadyPort>),
111    #[allow(dead_code)]
112    Boolean(bool),
113    OptionalBoolean(Option<bool>),
114    AutoBehavior(Vec<PitchforkTomlAuto>),
115    Retrigger(CronRetrigger),
116    StringList(Vec<String>),
117}
118
119/// A form field with metadata
120#[derive(Debug, Clone)]
121pub struct FormField {
122    pub name: &'static str,
123    pub label: &'static str,
124    pub value: FormFieldValue,
125    pub required: bool,
126    #[allow(dead_code)]
127    pub help_text: &'static str,
128    pub error: Option<String>,
129    pub editing: bool,
130    pub cursor: usize,
131}
132
133impl FormField {
134    fn text(name: &'static str, label: &'static str, help: &'static str, required: bool) -> Self {
135        Self {
136            name,
137            label,
138            value: FormFieldValue::Text(String::new()),
139            required,
140            help_text: help,
141            error: None,
142            editing: false,
143            cursor: 0,
144        }
145    }
146
147    fn optional_text(name: &'static str, label: &'static str, help: &'static str) -> Self {
148        Self {
149            name,
150            label,
151            value: FormFieldValue::OptionalText(None),
152            required: false,
153            help_text: help,
154            error: None,
155            editing: false,
156            cursor: 0,
157        }
158    }
159
160    fn number(name: &'static str, label: &'static str, help: &'static str, default: u32) -> Self {
161        Self {
162            name,
163            label,
164            value: FormFieldValue::Number(default),
165            required: false,
166            help_text: help,
167            error: None,
168            editing: false,
169            cursor: 0,
170        }
171    }
172
173    fn optional_number(name: &'static str, label: &'static str, help: &'static str) -> Self {
174        Self {
175            name,
176            label,
177            value: FormFieldValue::OptionalNumber(None),
178            required: false,
179            help_text: help,
180            error: None,
181            editing: false,
182            cursor: 0,
183        }
184    }
185
186    fn optional_port(name: &'static str, label: &'static str, help: &'static str) -> Self {
187        Self {
188            name,
189            label,
190            value: FormFieldValue::OptionalPort(None),
191            required: false,
192            help_text: help,
193            error: None,
194            editing: false,
195            cursor: 0,
196        }
197    }
198
199    fn optional_bool(name: &'static str, label: &'static str, help: &'static str) -> Self {
200        Self {
201            name,
202            label,
203            value: FormFieldValue::OptionalBoolean(None),
204            required: false,
205            help_text: help,
206            error: None,
207            editing: false,
208            cursor: 0,
209        }
210    }
211
212    fn auto_behavior(name: &'static str, label: &'static str, help: &'static str) -> Self {
213        Self {
214            name,
215            label,
216            value: FormFieldValue::AutoBehavior(vec![]),
217            required: false,
218            help_text: help,
219            error: None,
220            editing: false,
221            cursor: 0,
222        }
223    }
224
225    fn retrigger(name: &'static str, label: &'static str, help: &'static str) -> Self {
226        Self {
227            name,
228            label,
229            value: FormFieldValue::Retrigger(CronRetrigger::Finish),
230            required: false,
231            help_text: help,
232            error: None,
233            editing: false,
234            cursor: 0,
235        }
236    }
237
238    fn string_list(name: &'static str, label: &'static str, help: &'static str) -> Self {
239        Self {
240            name,
241            label,
242            value: FormFieldValue::StringList(vec![]),
243            required: false,
244            help_text: help,
245            error: None,
246            editing: false,
247            cursor: 0,
248        }
249    }
250
251    pub fn get_text(&self) -> String {
252        match &self.value {
253            FormFieldValue::Text(s) => s.clone(),
254            FormFieldValue::OptionalText(Some(s)) => s.clone(),
255            FormFieldValue::OptionalText(None) => String::new(),
256            FormFieldValue::Number(n) => n.to_string(),
257            FormFieldValue::OptionalNumber(Some(n)) => n.to_string(),
258            FormFieldValue::OptionalNumber(None) => String::new(),
259            FormFieldValue::OptionalPort(Some(p)) => p.to_string(),
260            FormFieldValue::OptionalPort(None) => String::new(),
261            FormFieldValue::StringList(v) => v.join(", "),
262            _ => String::new(),
263        }
264    }
265
266    pub fn set_text(&mut self, text: String) {
267        // Any edit invalidates a previous validation error; arms below
268        // re-set it for input that fails to parse.
269        self.error = None;
270        match &mut self.value {
271            FormFieldValue::Text(s) => *s = text,
272            FormFieldValue::OptionalText(opt) => {
273                *opt = if text.is_empty() { None } else { Some(text) };
274            }
275            FormFieldValue::Number(n) => {
276                let trimmed = text.trim();
277                if trimmed.is_empty() {
278                    *n = 0;
279                    self.error = None;
280                } else {
281                    match trimmed.parse() {
282                        Ok(value) => {
283                            *n = value;
284                            self.error = None;
285                        }
286                        Err(_) => {
287                            *n = 0;
288                            self.error = Some("Invalid number".to_string());
289                        }
290                    }
291                }
292            }
293            FormFieldValue::OptionalNumber(opt) => {
294                *opt = text.parse().ok();
295            }
296            FormFieldValue::OptionalPort(opt) => {
297                let trimmed = text.trim();
298                if trimmed.is_empty() {
299                    *opt = None;
300                    self.error = None;
301                } else {
302                    match trimmed.parse() {
303                        Ok(value) => {
304                            *opt = Some(value);
305                            self.error = None;
306                        }
307                        Err(e) => {
308                            *opt = None;
309                            self.error = Some(e);
310                        }
311                    }
312                }
313            }
314            FormFieldValue::StringList(v) => {
315                *v = text
316                    .split(',')
317                    .map(|s| s.trim().to_string())
318                    .filter(|s| !s.is_empty())
319                    .collect();
320            }
321            _ => {}
322        }
323    }
324
325    pub fn is_text_editable(&self) -> bool {
326        matches!(
327            self.value,
328            FormFieldValue::Text(_)
329                | FormFieldValue::OptionalText(_)
330                | FormFieldValue::Number(_)
331                | FormFieldValue::OptionalNumber(_)
332                | FormFieldValue::OptionalPort(_)
333                | FormFieldValue::StringList(_)
334        )
335    }
336}
337
338/// An argv `run` as text for the single-line editor field, read back by
339/// [`edit_text_to_argv`].
340///
341/// POSIX shell quoting, except on Windows: there a backslash separates path
342/// components, so it is never an escape, and quoting uses single or double
343/// quotes only.
344fn argv_to_edit_text(argv: &[String]) -> String {
345    if cfg!(windows) {
346        argv.iter()
347            .map(|arg| windows_edit_quote(arg))
348            .collect::<Vec<_>>()
349            .join(" ")
350    } else {
351        shell_words::join(argv)
352    }
353}
354
355/// Why the editor's text cannot be saved as an argv command, if it cannot.
356fn argv_edit_error(text: &str) -> Option<String> {
357    match edit_text_to_argv(text).as_deref() {
358        Ok([]) => Some("Required".to_string()),
359        Ok([program, ..]) if program.is_empty() => Some("The program name is empty".to_string()),
360        Ok([program, ..]) if program == "exec" => {
361            Some("Remove exec: this command starts the program without a shell".to_string())
362        }
363        Ok(_) => None,
364        Err(_) => Some("Unbalanced quotes".to_string()),
365    }
366}
367
368/// Split the editor's text back into arguments; `Err` for an unclosed quote.
369fn edit_text_to_argv(text: &str) -> Result<Vec<String>, String> {
370    if cfg!(windows) {
371        windows_edit_split(text)
372    } else {
373        shell_words::split(text).map_err(|e| e.to_string())
374    }
375}
376
377/// Quote `arg` so [`windows_edit_split`] reads it back unchanged.
378fn windows_edit_quote(arg: &str) -> String {
379    if !arg.is_empty() && !arg.contains(|c: char| c.is_whitespace() || c == '\'' || c == '"') {
380        return arg.to_string();
381    }
382    // Quoted runs join into one word, so a single quote can sit in a
383    // double-quoted run next to single-quoted text: it's -> 'it'"'"'s'.
384    let mut quoted = String::from("'");
385    for c in arg.chars() {
386        if c == '\'' {
387            quoted.push_str("'\"'\"'");
388        } else {
389            quoted.push(c);
390        }
391    }
392    quoted.push('\'');
393    quoted
394}
395
396/// Split on whitespace, with `'...'` and `"..."` taken literally, and
397/// backslashes kept as they are.
398fn windows_edit_split(text: &str) -> Result<Vec<String>, String> {
399    let mut words = Vec::new();
400    let mut word = String::new();
401    // Whether a word has begun: `''` is an empty argument, not nothing.
402    let mut in_word = false;
403    let mut chars = text.chars();
404    while let Some(c) = chars.next() {
405        match c {
406            '\'' | '"' => {
407                in_word = true;
408                loop {
409                    match chars.next() {
410                        Some(q) if q == c => break,
411                        Some(other) => word.push(other),
412                        None => return Err("unclosed quote".to_string()),
413                    }
414                }
415            }
416            c if c.is_whitespace() => {
417                if in_word {
418                    words.push(std::mem::take(&mut word));
419                    in_word = false;
420                }
421            }
422            c => {
423                in_word = true;
424                word.push(c);
425            }
426        }
427    }
428    if in_word {
429        words.push(word);
430    }
431    Ok(words)
432}
433
434/// State for the daemon config editor
435#[derive(Debug, Clone)]
436pub struct EditorState {
437    pub mode: EditMode,
438    pub daemon_id: String,
439    pub daemon_id_editing: bool,
440    pub daemon_id_cursor: usize,
441    pub daemon_id_error: Option<String>,
442    pub fields: Vec<FormField>,
443    pub focused_field: usize,
444    pub config_path: PathBuf,
445    pub unsaved_changes: bool,
446    #[allow(dead_code)]
447    pub scroll_offset: usize,
448    /// Preserved config field for ready_cmd (no form UI yet)
449    preserved_ready_cmd: Option<ReadyCmd>,
450    /// Preserved `oneshot` flag (no form UI yet). Without this, saving a
451    /// oneshot daemon through the editor would silently turn it back into a
452    /// long-running service.
453    preserved_oneshot: Option<bool>,
454    /// The argv form of `run`, which the single-line field cannot hold. Saving
455    /// with the field unchanged keeps it; editing the text makes it a shell
456    /// command line.
457    preserved_run_argv: Option<RunCommand>,
458    /// Preserved ready_http statuses (no form UI yet)
459    preserved_ready_http_status: Option<Vec<u16>>,
460    /// Preserved ready_http timeout (no form UI yet)
461    preserved_ready_http_timeout: Option<std::time::Duration>,
462    /// Preserved ready_output timeout (no form UI yet)
463    preserved_ready_output_timeout: Option<std::time::Duration>,
464    /// Preserved health_cmd parameters (only `run` has form UI)
465    preserved_health_cmd: Option<HealthCmd>,
466    /// Preserved health_http parameters (only `url` has form UI)
467    preserved_health_http: Option<HealthHttp>,
468    /// Preserved health_port parameters (only the port has form UI)
469    preserved_health_port: Option<HealthPort>,
470    preserved_depends_as: IndexMap<String, DaemonId>,
471}
472
473impl EditorState {
474    pub fn new_create(config_path: PathBuf) -> Self {
475        Self {
476            mode: EditMode::Create,
477            daemon_id: String::new(),
478            daemon_id_editing: true,
479            daemon_id_cursor: 0,
480            daemon_id_error: None,
481            fields: Self::default_fields(),
482            focused_field: 0,
483            config_path,
484            unsaved_changes: false,
485            scroll_offset: 0,
486            preserved_ready_cmd: None,
487            preserved_oneshot: None,
488            preserved_run_argv: None,
489            preserved_ready_http_status: None,
490            preserved_ready_http_timeout: None,
491            preserved_ready_output_timeout: None,
492            preserved_health_cmd: None,
493            preserved_health_http: None,
494            preserved_health_port: None,
495            preserved_depends_as: IndexMap::new(),
496        }
497    }
498
499    pub fn new_edit(daemon_id: String, config: &PitchforkTomlDaemon, config_path: PathBuf) -> Self {
500        Self {
501            mode: EditMode::Edit {
502                original_id: daemon_id.clone(),
503            },
504            daemon_id,
505            daemon_id_editing: false,
506            daemon_id_cursor: 0,
507            daemon_id_error: None,
508            fields: Self::fields_from_config(config),
509            focused_field: 0,
510            config_path,
511            unsaved_changes: false,
512            scroll_offset: 0,
513            preserved_ready_cmd: config.ready_cmd.clone(),
514            preserved_oneshot: config.oneshot,
515            preserved_run_argv: config.run.is_argv().then(|| config.run.clone()),
516            preserved_ready_http_status: config
517                .ready_http
518                .as_ref()
519                .and_then(|h| (!h.status.is_empty()).then(|| h.status.clone())),
520            preserved_ready_http_timeout: config.ready_http.as_ref().and_then(|h| h.timeout),
521            preserved_ready_output_timeout: config.ready_output.as_ref().and_then(|o| o.timeout),
522            preserved_health_cmd: config.health_cmd.clone(),
523            preserved_health_http: config.health_http.clone(),
524            preserved_health_port: config.health_port.clone(),
525            preserved_depends_as: config.depends_as.clone(),
526        }
527    }
528
529    fn default_fields() -> Vec<FormField> {
530        vec![
531            FormField::text(
532                "run",
533                "Run Command",
534                "Command to execute. Prepend 'exec' to avoid shell overhead.",
535                true,
536            ),
537            FormField::optional_text(
538                "dir",
539                "Working Directory",
540                "Working directory for the daemon. Relative to pitchfork.toml location.",
541            ),
542            FormField::string_list(
543                "env",
544                "Environment Variables",
545                "Comma-separated KEY=VALUE pairs (e.g., NODE_ENV=dev, PORT=3000).",
546            ),
547            FormField::auto_behavior(
548                "auto",
549                "Auto Behavior",
550                "Auto start/stop based on directory hooks.",
551            ),
552            FormField::number(
553                "retry",
554                "Retry Count",
555                "Number of retry attempts on failure (0 = no retries).",
556                0,
557            ),
558            FormField::optional_number(
559                "ready_delay",
560                "Ready Delay (ms)",
561                "Milliseconds to wait before considering daemon ready.",
562            ),
563            FormField::optional_text(
564                "ready_output",
565                "Ready Output Pattern",
566                "Regex pattern in ANSI-stripped stdout/stderr indicating readiness.",
567            ),
568            FormField::optional_text(
569                "ready_http",
570                "Ready HTTP URL",
571                "HTTP URL to poll for readiness (expects 2xx).",
572            ),
573            FormField::optional_port(
574                "ready_port",
575                "Ready Port",
576                "TCP port to check for readiness (1-65535).",
577            ),
578            FormField::optional_text(
579                "health_cmd",
580                "Health Command",
581                "Shell command that must exit 0 for the daemon to stay healthy.",
582            ),
583            FormField::optional_text(
584                "health_http",
585                "Health HTTP URL",
586                "HTTP URL to poll for health (expects 2xx).",
587            ),
588            FormField::optional_port(
589                "health_port",
590                "Health Port",
591                "TCP port that must accept connections for the daemon to stay healthy (1-65535).",
592            ),
593            FormField::optional_bool(
594                "boot_start",
595                "Start on Boot",
596                "Automatically start this daemon on system boot.",
597            ),
598            FormField::string_list(
599                "depends",
600                "Dependencies",
601                "Comma-separated daemon names that must start first.",
602            ),
603            FormField::string_list(
604                "watch",
605                "Watch Files",
606                "Comma-separated glob patterns to watch for auto-restart.",
607            ),
608            FormField::optional_text(
609                "cron_schedule",
610                "Cron Schedule",
611                "Cron expression (e.g., '*/5 * * * *' for every 5 minutes).",
612            ),
613            FormField::retrigger(
614                "cron_retrigger",
615                "Cron Retrigger",
616                "Behavior when cron triggers while previous run is active.",
617            ),
618            FormField::optional_bool(
619                "cron_immediate",
620                "Cron Immediate",
621                "Trigger immediately on first check (default: false).",
622            ),
623        ]
624    }
625
626    fn fields_from_config(config: &PitchforkTomlDaemon) -> Vec<FormField> {
627        let mut fields = Self::default_fields();
628
629        for field in &mut fields {
630            match field.name {
631                "run" => {
632                    field.value = FormFieldValue::Text(match &config.run {
633                        RunCommand::Argv(argv) => argv_to_edit_text(argv),
634                        RunCommand::Shell(run) => run.clone(),
635                    })
636                }
637                "dir" => field.value = FormFieldValue::OptionalText(config.dir.clone()),
638                "env" => {
639                    field.value = FormFieldValue::StringList(
640                        config
641                            .env
642                            .as_ref()
643                            .map(|m| m.iter().map(|(k, v)| format!("{k}={v}")).collect())
644                            .unwrap_or_default(),
645                    );
646                }
647                "auto" => field.value = FormFieldValue::AutoBehavior(config.auto.clone()),
648                "retry" => field.value = FormFieldValue::Number(config.retry.count()),
649                "ready_delay" => field.value = FormFieldValue::OptionalNumber(config.ready_delay),
650                "ready_output" => {
651                    field.value = FormFieldValue::OptionalText(
652                        config.ready_output.as_ref().map(|o| o.pattern.clone()),
653                    )
654                }
655                "ready_http" => {
656                    field.value = FormFieldValue::OptionalText(
657                        config.ready_http.as_ref().map(|h| h.url.clone()),
658                    )
659                }
660                "ready_port" => {
661                    field.value = FormFieldValue::OptionalPort(config.ready_port.clone())
662                }
663                "health_cmd" => {
664                    field.value = FormFieldValue::OptionalText(config.health_cmd.as_ref().map(
665                        |c| match &c.run {
666                            RunCommand::Argv(argv) => argv_to_edit_text(argv),
667                            RunCommand::Shell(run) => run.clone(),
668                        },
669                    ))
670                }
671                "health_http" => {
672                    field.value = FormFieldValue::OptionalText(
673                        config.health_http.as_ref().map(|h| h.url.clone()),
674                    )
675                }
676                "health_port" => {
677                    field.value =
678                        FormFieldValue::OptionalPort(config.health_port.as_ref().map(|hp| {
679                            ReadyPort {
680                                port: hp.port,
681                                template: hp.template.clone(),
682                                timeout: None,
683                            }
684                        }))
685                }
686                "boot_start" => field.value = FormFieldValue::OptionalBoolean(config.boot_start),
687                "depends" => {
688                    field.value = FormFieldValue::StringList(
689                        config
690                            .depends
691                            .iter()
692                            .map(|d: &DaemonId| d.qualified())
693                            .collect(),
694                    )
695                }
696                "watch" => field.value = FormFieldValue::StringList(config.watch.clone()),
697                "cron_schedule" => {
698                    field.value = FormFieldValue::OptionalText(
699                        config.cron.as_ref().map(|c| c.schedule.clone()),
700                    );
701                }
702                "cron_retrigger" => {
703                    field.value = FormFieldValue::Retrigger(
704                        config
705                            .cron
706                            .as_ref()
707                            .map(|c| c.retrigger)
708                            .unwrap_or(CronRetrigger::Finish),
709                    );
710                }
711                "cron_immediate" => {
712                    field.value =
713                        FormFieldValue::OptionalBoolean(config.cron.as_ref().map(|c| c.immediate));
714                }
715                _ => {}
716            }
717        }
718
719        fields
720    }
721
722    pub fn to_daemon_config(&self) -> PitchforkTomlDaemon {
723        let mut config = PitchforkTomlDaemon {
724            ready_cmd: self.preserved_ready_cmd.clone(),
725            oneshot: self.preserved_oneshot,
726            path: Some(self.config_path.clone()),
727            ..PitchforkTomlDaemon::default()
728        };
729
730        let mut cron_schedule: Option<String> = None;
731        let mut cron_retrigger = CronRetrigger::Finish;
732        let mut cron_immediate = false;
733
734        for field in &self.fields {
735            match (field.name, &field.value) {
736                ("run", FormFieldValue::Text(s)) => {
737                    config.run = match &self.preserved_run_argv {
738                        Some(RunCommand::Argv(argv)) if argv_to_edit_text(argv) == *s => {
739                            RunCommand::Argv(argv.clone())
740                        }
741                        // An edit is split back the way the field quoted it, and
742                        // stays an array. `validate` has already refused text
743                        // that cannot be.
744                        Some(_) => match edit_text_to_argv(s) {
745                            Ok(words) if !words.is_empty() => words.into(),
746                            _ => s.clone().into(),
747                        },
748                        None => s.clone().into(),
749                    };
750                }
751                ("dir", FormFieldValue::OptionalText(s)) => config.dir = s.clone(),
752                ("env", FormFieldValue::StringList(v)) => {
753                    if v.is_empty() {
754                        config.env = None;
755                    } else {
756                        let mut map = indexmap::IndexMap::new();
757                        for entry in v {
758                            if let Some((k, val)) = entry.split_once('=') {
759                                map.insert(k.trim().to_string(), val.trim().to_string());
760                            }
761                        }
762                        config.env = if map.is_empty() { None } else { Some(map) };
763                    }
764                }
765                ("auto", FormFieldValue::AutoBehavior(v)) => config.auto = v.clone(),
766                ("retry", FormFieldValue::Number(n)) => config.retry = Retry(*n),
767                ("ready_delay", FormFieldValue::OptionalNumber(n)) => config.ready_delay = *n,
768                ("ready_output", FormFieldValue::OptionalText(s)) => {
769                    config.ready_output = s.clone().map(|pattern| ReadyOutput {
770                        pattern,
771                        timeout: self.preserved_ready_output_timeout,
772                    })
773                }
774                ("ready_http", FormFieldValue::OptionalText(s)) => {
775                    config.ready_http = s.clone().map(|url| ReadyHttp {
776                        url,
777                        status: self.preserved_ready_http_status.clone().unwrap_or_default(),
778                        timeout: self.preserved_ready_http_timeout,
779                    })
780                }
781                ("ready_port", FormFieldValue::OptionalPort(p)) => config.ready_port = p.clone(),
782                ("health_cmd", FormFieldValue::OptionalText(s)) => {
783                    config.health_cmd = s.clone().map(|text| {
784                        let mut cmd = self.preserved_health_cmd.clone().unwrap_or_default();
785                        // An array stays an array, edited or not, as for `run`.
786                        cmd.run = match &cmd.run {
787                            RunCommand::Argv(argv) if argv_to_edit_text(argv) == text => {
788                                RunCommand::Argv(argv.clone())
789                            }
790                            RunCommand::Argv(_) => match edit_text_to_argv(&text) {
791                                Ok(words) if !words.is_empty() => words.into(),
792                                _ => text.into(),
793                            },
794                            RunCommand::Shell(_) => text.into(),
795                        };
796                        cmd
797                    })
798                }
799                ("health_http", FormFieldValue::OptionalText(s)) => {
800                    config.health_http = s.clone().map(|url| {
801                        let mut http = self.preserved_health_http.clone().unwrap_or_default();
802                        http.url = url;
803                        http
804                    })
805                }
806                ("health_port", FormFieldValue::OptionalPort(p)) => {
807                    config.health_port = p.clone().map(|port_value| {
808                        let mut hp = self.preserved_health_port.clone().unwrap_or_default();
809                        hp.port = port_value.port;
810                        hp.template = port_value.template;
811                        hp
812                    })
813                }
814                ("boot_start", FormFieldValue::OptionalBoolean(b)) => config.boot_start = *b,
815                ("depends", FormFieldValue::StringList(v)) => {
816                    config.depends = v.iter().filter_map(|s| DaemonId::parse(s).ok()).collect();
817                    // Keep the template names of dependencies still listed.
818                    config.depends_as = self
819                        .preserved_depends_as
820                        .iter()
821                        .filter(|(_, id)| config.depends.contains(id))
822                        .map(|(alias, id)| (alias.clone(), id.clone()))
823                        .collect();
824                }
825                ("watch", FormFieldValue::StringList(v)) => config.watch = v.clone(),
826                ("cron_schedule", FormFieldValue::OptionalText(s)) => cron_schedule = s.clone(),
827                ("cron_retrigger", FormFieldValue::Retrigger(r)) => cron_retrigger = *r,
828                ("cron_immediate", FormFieldValue::OptionalBoolean(b)) => {
829                    cron_immediate = b.unwrap_or(false);
830                }
831                _ => {}
832            }
833        }
834
835        if let Some(schedule) = cron_schedule {
836            config.cron = Some(PitchforkTomlCron {
837                schedule,
838                retrigger: cron_retrigger,
839                immediate: cron_immediate,
840            });
841        }
842
843        config
844    }
845
846    pub fn next_field(&mut self) {
847        // Stop editing current field if text editing
848        if let Some(field) = self.fields.get_mut(self.focused_field) {
849            field.editing = false;
850        }
851
852        // When leaving daemon_id editing, don't increment - just move to first form field
853        if self.daemon_id_editing {
854            self.daemon_id_editing = false;
855            return;
856        }
857
858        if self.focused_field < self.fields.len() - 1 {
859            self.focused_field += 1;
860        }
861    }
862
863    pub fn prev_field(&mut self) {
864        // Stop editing current field if text editing
865        if let Some(field) = self.fields.get_mut(self.focused_field) {
866            field.editing = false;
867        }
868        self.daemon_id_editing = false;
869
870        if self.focused_field > 0 {
871            self.focused_field -= 1;
872        }
873    }
874
875    pub fn toggle_current_field(&mut self) {
876        if let Some(field) = self.fields.get_mut(self.focused_field) {
877            let toggled = match &mut field.value {
878                FormFieldValue::Boolean(b) => {
879                    *b = !*b;
880                    true
881                }
882                FormFieldValue::OptionalBoolean(opt) => {
883                    *opt = match opt {
884                        None => Some(true),
885                        Some(true) => Some(false),
886                        Some(false) => None,
887                    };
888                    true
889                }
890                FormFieldValue::AutoBehavior(v) => {
891                    // Cycle through: [] -> [Start] -> [Stop] -> [Start, Stop] -> []
892                    let has_start = v.contains(&PitchforkTomlAuto::Start);
893                    let has_stop = v.contains(&PitchforkTomlAuto::Stop);
894                    *v = match (has_start, has_stop) {
895                        (false, false) => vec![PitchforkTomlAuto::Start],
896                        (true, false) => vec![PitchforkTomlAuto::Stop],
897                        (false, true) => vec![PitchforkTomlAuto::Start, PitchforkTomlAuto::Stop],
898                        (true, true) => vec![],
899                    };
900                    true
901                }
902                FormFieldValue::Retrigger(r) => {
903                    *r = match r {
904                        CronRetrigger::Finish => CronRetrigger::Always,
905                        CronRetrigger::Always => CronRetrigger::Success,
906                        CronRetrigger::Success => CronRetrigger::Fail,
907                        CronRetrigger::Fail => CronRetrigger::Finish,
908                    };
909                    true
910                }
911                _ => false,
912            };
913            if toggled {
914                self.unsaved_changes = true;
915            }
916        }
917    }
918
919    pub fn start_editing(&mut self) {
920        if let Some(field) = self.fields.get_mut(self.focused_field) {
921            if field.is_text_editable() {
922                field.editing = true;
923                field.cursor = field.get_text().chars().count();
924            } else {
925                // For non-text fields, toggle them
926                self.toggle_current_field();
927            }
928        }
929    }
930
931    pub fn stop_editing(&mut self) {
932        if let Some(field) = self.fields.get_mut(self.focused_field) {
933            field.editing = false;
934        }
935        self.daemon_id_editing = false;
936    }
937
938    pub fn is_editing(&self) -> bool {
939        self.daemon_id_editing
940            || self
941                .fields
942                .get(self.focused_field)
943                .map(|f| f.editing)
944                .unwrap_or(false)
945    }
946
947    pub fn text_push(&mut self, c: char) {
948        if self.daemon_id_editing {
949            let byte_idx = char_to_byte_index(&self.daemon_id, self.daemon_id_cursor);
950            self.daemon_id.insert(byte_idx, c);
951            self.daemon_id_cursor += 1;
952            self.unsaved_changes = true;
953        } else if let Some(field) = self.fields.get_mut(self.focused_field)
954            && field.editing
955        {
956            let mut text = field.get_text();
957            let byte_idx = char_to_byte_index(&text, field.cursor);
958            text.insert(byte_idx, c);
959            field.cursor += 1;
960            field.set_text(text);
961            self.unsaved_changes = true;
962        }
963    }
964
965    pub fn text_pop(&mut self) {
966        if self.daemon_id_editing && self.daemon_id_cursor > 0 {
967            self.daemon_id_cursor -= 1;
968            let byte_idx = char_to_byte_index(&self.daemon_id, self.daemon_id_cursor);
969            self.daemon_id.remove(byte_idx);
970            self.unsaved_changes = true;
971        } else if let Some(field) = self.fields.get_mut(self.focused_field)
972            && field.editing
973            && field.cursor > 0
974        {
975            let mut text = field.get_text();
976            // Value-backed fields (OptionalNumber/OptionalPort) drop invalid
977            // input in set_text, so the cursor can be past the derived text.
978            field.cursor = field.cursor.min(text.chars().count());
979            if field.cursor == 0 {
980                return;
981            }
982            field.cursor -= 1;
983            let byte_idx = char_to_byte_index(&text, field.cursor);
984            text.remove(byte_idx);
985            field.set_text(text);
986            // For Number fields, sync cursor to end if value defaulted to "0"
987            // This handles the case where backspacing to empty makes value 0
988            if matches!(field.value, FormFieldValue::Number(_)) {
989                field.cursor = field.get_text().chars().count();
990            }
991            self.unsaved_changes = true;
992        }
993    }
994
995    pub fn validate(&mut self) -> bool {
996        let mut valid = true;
997
998        // Validate daemon ID
999        self.daemon_id_error = None;
1000        if self.daemon_id.is_empty() {
1001            self.daemon_id_error = Some("Name is required".to_string());
1002            valid = false;
1003        } else if !self
1004            .daemon_id
1005            .chars()
1006            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
1007        {
1008            self.daemon_id_error =
1009                Some("Only letters, digits, hyphens, and underscores allowed".to_string());
1010            valid = false;
1011        }
1012
1013        // Validate fields
1014        let run_is_argv = self.preserved_run_argv.is_some();
1015        let health_cmd_is_argv = self
1016            .preserved_health_cmd
1017            .as_ref()
1018            .is_some_and(|c| c.run.is_argv());
1019        for field in &mut self.fields {
1020            // Keep parse errors from set_text (e.g. out-of-range ready_port):
1021            // the typed value was already dropped, so saving now would
1022            // silently lose the field.
1023            if field.error.is_some() {
1024                valid = false;
1025                continue;
1026            }
1027
1028            match (field.name, &field.value) {
1029                ("run", FormFieldValue::Text(s)) if s.is_empty() => {
1030                    field.error = Some("Required".to_string());
1031                    valid = false;
1032                }
1033                ("run", FormFieldValue::Text(s)) if run_is_argv => {
1034                    if let Some(error) = argv_edit_error(s) {
1035                        field.error = Some(error);
1036                        valid = false;
1037                    }
1038                }
1039                ("health_cmd", FormFieldValue::OptionalText(Some(s))) if health_cmd_is_argv => {
1040                    if let Some(error) = argv_edit_error(s) {
1041                        field.error = Some(error);
1042                        valid = false;
1043                    }
1044                }
1045                ("ready_http", FormFieldValue::OptionalText(Some(url)))
1046                    if !(url.starts_with("http://") || url.starts_with("https://")) =>
1047                {
1048                    field.error = Some("Must start with http:// or https://".to_string());
1049                    valid = false;
1050                }
1051                ("health_http", FormFieldValue::OptionalText(Some(url)))
1052                    if !(url.starts_with("http://") || url.starts_with("https://")) =>
1053                {
1054                    field.error = Some("Must start with http:// or https://".to_string());
1055                    valid = false;
1056                }
1057                _ => {}
1058            }
1059        }
1060
1061        valid
1062    }
1063}
1064
1065/// State for config file selection
1066#[derive(Debug, Clone)]
1067pub struct ConfigFileSelector {
1068    pub files: Vec<PathBuf>,
1069    pub selected: usize,
1070}
1071
1072#[derive(Debug, Clone)]
1073pub enum PendingAction {
1074    Stop(DaemonId),
1075    Restart(DaemonId),
1076    Disable(DaemonId),
1077    // Batch operations
1078    BatchStop(Vec<DaemonId>),
1079    BatchRestart(Vec<DaemonId>),
1080    BatchDisable(Vec<DaemonId>),
1081    Clean(Vec<DaemonId>),
1082    // Config editor actions
1083    DeleteDaemon { id: String, config_path: PathBuf },
1084    DiscardEditorChanges,
1085}
1086
1087#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1088pub enum SortColumn {
1089    #[default]
1090    Name,
1091    Status,
1092    Cpu,
1093    Memory,
1094    Uptime,
1095}
1096
1097impl SortColumn {
1098    pub fn next(self) -> Self {
1099        match self {
1100            Self::Name => Self::Status,
1101            Self::Status => Self::Cpu,
1102            Self::Cpu => Self::Memory,
1103            Self::Memory => Self::Uptime,
1104            Self::Uptime => Self::Name,
1105        }
1106    }
1107}
1108
1109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1110pub enum SortOrder {
1111    #[default]
1112    Ascending,
1113    Descending,
1114}
1115
1116impl SortOrder {
1117    pub fn toggle(self) -> Self {
1118        match self {
1119            Self::Ascending => Self::Descending,
1120            Self::Descending => Self::Ascending,
1121        }
1122    }
1123
1124    pub fn indicator(self) -> &'static str {
1125        match self {
1126            Self::Ascending => "↑",
1127            Self::Descending => "↓",
1128        }
1129    }
1130}
1131
1132pub struct App {
1133    pub daemons: Vec<Daemon>,
1134    pub disabled: Vec<DaemonId>,
1135    pub selected: usize,
1136    pub view: View,
1137    pub prev_view: View,
1138    pub log_content: Vec<String>,
1139    pub log_daemon_id: Option<DaemonId>,
1140    pub log_scroll: usize,
1141    pub log_follow: bool, // Auto-scroll to bottom as new lines appear
1142    pub message: Option<String>,
1143    pub message_time: Option<Instant>,
1144    pub process_stats: HashMap<u32, ProcessStats>, // PID -> stats
1145    pub stats_history: HashMap<DaemonId, StatsHistory>, // daemon_id -> history
1146    pub pending_action: Option<PendingAction>,
1147    pub loading_text: Option<String>,
1148    pub search_query: String,
1149    pub search_active: bool,
1150    // Sorting
1151    pub sort_column: SortColumn,
1152    pub sort_order: SortOrder,
1153    // Log search
1154    pub log_search_query: String,
1155    pub log_search_active: bool,
1156    pub log_search_matches: Vec<usize>, // Line indices that match
1157    pub log_search_current: usize,      // Current match index
1158    // Details view daemon (now used for full-page details view from 'l' key)
1159    pub details_daemon_id: Option<DaemonId>,
1160    // Whether logs are expanded to fill the screen (hides charts)
1161    pub logs_expanded: bool,
1162    // Multi-select state
1163    pub multi_select: HashSet<DaemonId>,
1164    // Config-only daemons (defined in pitchfork.toml but not currently active)
1165    pub config_daemon_ids: HashSet<DaemonId>,
1166    // Whether to show config-only daemons in the list
1167    pub show_available: bool,
1168    // Config editor state
1169    pub editor_state: Option<EditorState>,
1170    // Config file selector state
1171    pub file_selector: Option<ConfigFileSelector>,
1172    // Network view state
1173    pub network_listeners: Vec<Listener>,
1174    pub network_search_query: String,
1175    pub network_search_active: bool,
1176    pub network_selected: usize,
1177    pub network_scroll_offset: usize,
1178    pub network_selected_pid: Option<u32>, // Store PID to ensure correct targeting
1179    pub network_visible_rows: usize,       // Cached visible row count for scroll calculations
1180    // Namespace scope from `--namespace`/`--project`; applied when fetching
1181    // the daemon list, so search/sort/selection all operate on the scoped set
1182    pub namespace_filter: NamespaceFilter,
1183}
1184
1185impl App {
1186    pub fn new(namespace_filter: NamespaceFilter) -> Self {
1187        Self {
1188            namespace_filter,
1189            daemons: Vec::new(),
1190            disabled: Vec::new(),
1191            selected: 0,
1192            view: View::Dashboard,
1193            prev_view: View::Dashboard,
1194            log_content: Vec::new(),
1195            log_daemon_id: None,
1196            log_scroll: 1,
1197            log_follow: true,
1198            message: None,
1199            message_time: None,
1200            process_stats: HashMap::new(),
1201            stats_history: HashMap::new(),
1202            pending_action: None,
1203            loading_text: None,
1204            search_query: String::new(),
1205            search_active: false,
1206            sort_column: SortColumn::default(),
1207            sort_order: SortOrder::default(),
1208            log_search_query: String::new(),
1209            log_search_active: false,
1210            log_search_matches: Vec::new(),
1211            log_search_current: 0,
1212            details_daemon_id: None,
1213            logs_expanded: false,
1214            multi_select: HashSet::new(),
1215            config_daemon_ids: HashSet::new(),
1216            show_available: true, // Show available daemons by default
1217            editor_state: None,
1218            file_selector: None,
1219            network_listeners: Vec::new(),
1220            network_search_query: String::new(),
1221            network_search_active: false,
1222            network_selected: 0,
1223            network_scroll_offset: 0,
1224            network_selected_pid: None,
1225            network_visible_rows: 20, // Default value, updated during draw
1226        }
1227    }
1228
1229    pub fn confirm_action(&mut self, action: PendingAction) {
1230        self.pending_action = Some(action);
1231        self.prev_view = self.view;
1232        self.view = View::Confirm;
1233    }
1234
1235    pub fn cancel_confirm(&mut self) {
1236        self.pending_action = None;
1237        self.view = self.prev_view;
1238    }
1239
1240    pub fn take_pending_action(&mut self) -> Option<PendingAction> {
1241        self.view = self.prev_view;
1242        self.pending_action.take()
1243    }
1244
1245    pub fn start_loading(&mut self, text: impl Into<String>) {
1246        self.loading_text = Some(text.into());
1247    }
1248
1249    pub fn stop_loading(&mut self) {
1250        self.loading_text = None;
1251    }
1252
1253    // Search functionality
1254    pub fn start_search(&mut self) {
1255        self.search_active = true;
1256    }
1257
1258    pub fn end_search(&mut self) {
1259        self.search_active = false;
1260    }
1261
1262    pub fn clear_search(&mut self) {
1263        self.search_query.clear();
1264        self.search_active = false;
1265        self.selected = 0;
1266    }
1267
1268    pub fn search_push(&mut self, c: char) {
1269        self.search_query.push(c);
1270        // Reset selection when search changes
1271        self.selected = 0;
1272    }
1273
1274    pub fn search_pop(&mut self) {
1275        self.search_query.pop();
1276        self.selected = 0;
1277    }
1278
1279    pub fn filtered_daemons(&self) -> Vec<&Daemon> {
1280        let mut filtered: Vec<&Daemon> = if self.search_query.is_empty() {
1281            self.daemons.iter().collect()
1282        } else {
1283            // Use fuzzy matching with SkimMatcherV2
1284            let matcher = SkimMatcherV2::default();
1285            let mut scored: Vec<_> = self
1286                .daemons
1287                .iter()
1288                .filter_map(|d| {
1289                    matcher
1290                        .fuzzy_match(&d.id.qualified(), &self.search_query)
1291                        .map(|score| (d, score))
1292                })
1293                .collect();
1294            // Sort by score descending (best matches first)
1295            scored.sort_by_key(|s| std::cmp::Reverse(s.1));
1296            scored.into_iter().map(|(d, _)| d).collect()
1297        };
1298
1299        // Sort the filtered list
1300        filtered.sort_by(|a, b| {
1301            let cmp = match self.sort_column {
1302                SortColumn::Name => {
1303                    a.id.to_string()
1304                        .to_lowercase()
1305                        .cmp(&b.id.to_string().to_lowercase())
1306                }
1307                SortColumn::Status => {
1308                    let status_order = |d: &Daemon| match &d.status {
1309                        crate::daemon_status::DaemonStatus::Running => 0,
1310                        crate::daemon_status::DaemonStatus::Waiting => 1,
1311                        crate::daemon_status::DaemonStatus::Stopping
1312                        | crate::daemon_status::DaemonStatus::Restarting => 2,
1313                        crate::daemon_status::DaemonStatus::Completed => 3,
1314                        crate::daemon_status::DaemonStatus::Stopped => 4,
1315                        crate::daemon_status::DaemonStatus::Errored(_) => 5,
1316                        crate::daemon_status::DaemonStatus::Failed(_) => 6,
1317                    };
1318                    status_order(a).cmp(&status_order(b))
1319                }
1320                SortColumn::Cpu => {
1321                    let cpu_a = a
1322                        .pid
1323                        .and_then(|p| self.get_stats(p))
1324                        .map(|s| s.cpu_percent)
1325                        .unwrap_or(0.0);
1326                    let cpu_b = b
1327                        .pid
1328                        .and_then(|p| self.get_stats(p))
1329                        .map(|s| s.cpu_percent)
1330                        .unwrap_or(0.0);
1331                    cpu_a
1332                        .partial_cmp(&cpu_b)
1333                        .unwrap_or(std::cmp::Ordering::Equal)
1334                }
1335                SortColumn::Memory => {
1336                    let mem_a = a
1337                        .pid
1338                        .and_then(|p| self.get_stats(p))
1339                        .map(|s| s.memory_bytes)
1340                        .unwrap_or(0);
1341                    let mem_b = b
1342                        .pid
1343                        .and_then(|p| self.get_stats(p))
1344                        .map(|s| s.memory_bytes)
1345                        .unwrap_or(0);
1346                    mem_a.cmp(&mem_b)
1347                }
1348                SortColumn::Uptime => {
1349                    let up_a = a
1350                        .pid
1351                        .and_then(|p| self.get_stats(p))
1352                        .map(|s| s.uptime_secs)
1353                        .unwrap_or(0);
1354                    let up_b = b
1355                        .pid
1356                        .and_then(|p| self.get_stats(p))
1357                        .map(|s| s.uptime_secs)
1358                        .unwrap_or(0);
1359                    up_a.cmp(&up_b)
1360                }
1361            };
1362            match self.sort_order {
1363                SortOrder::Ascending => cmp,
1364                SortOrder::Descending => cmp.reverse(),
1365            }
1366        });
1367
1368        filtered
1369    }
1370
1371    // Sorting
1372    pub fn cycle_sort(&mut self) {
1373        // If clicking the same column, toggle order; otherwise switch column
1374        self.sort_column = self.sort_column.next();
1375        self.selected = 0;
1376    }
1377
1378    pub fn toggle_sort_order(&mut self) {
1379        self.sort_order = self.sort_order.toggle();
1380        self.selected = 0;
1381    }
1382
1383    pub fn selected_daemon(&self) -> Option<&Daemon> {
1384        let filtered = self.filtered_daemons();
1385        filtered.get(self.selected).copied()
1386    }
1387
1388    pub fn select_next(&mut self) {
1389        let count = self.filtered_daemons().len();
1390        if count > 0 {
1391            self.selected = (self.selected + 1) % count;
1392        }
1393    }
1394
1395    pub fn select_prev(&mut self) {
1396        let count = self.filtered_daemons().len();
1397        if count > 0 {
1398            self.selected = self.selected.checked_sub(1).unwrap_or(count - 1);
1399        }
1400    }
1401
1402    // Log follow mode
1403    pub fn toggle_log_follow(&mut self) {
1404        self.log_follow = !self.log_follow;
1405        if self.log_follow && !self.log_content.is_empty() {
1406            // Jump to bottom when enabling follow
1407            self.log_scroll = self.log_content.len();
1408        }
1409    }
1410
1411    // Toggle logs expanded (hide/show charts)
1412    pub fn toggle_logs_expanded(&mut self) {
1413        self.logs_expanded = !self.logs_expanded;
1414    }
1415
1416    // Multi-select methods
1417    pub fn toggle_select(&mut self) {
1418        if let Some(daemon) = self.selected_daemon() {
1419            let id = daemon.id.clone();
1420            if self.multi_select.contains(&id) {
1421                self.multi_select.remove(&id);
1422            } else {
1423                self.multi_select.insert(id);
1424            }
1425        }
1426    }
1427
1428    pub fn select_all_visible(&mut self) {
1429        // Collect IDs first to avoid borrow conflict
1430        let ids: Vec<DaemonId> = self
1431            .filtered_daemons()
1432            .iter()
1433            .map(|d| d.id.clone())
1434            .collect();
1435        for id in ids {
1436            self.multi_select.insert(id);
1437        }
1438    }
1439
1440    pub fn clear_selection(&mut self) {
1441        self.multi_select.clear();
1442    }
1443
1444    pub fn is_selected(&self, daemon_id: &DaemonId) -> bool {
1445        self.multi_select.contains(daemon_id)
1446    }
1447
1448    pub fn has_selection(&self) -> bool {
1449        !self.multi_select.is_empty()
1450    }
1451
1452    pub fn selected_daemon_ids(&self) -> Vec<DaemonId> {
1453        self.multi_select.iter().cloned().collect()
1454    }
1455
1456    pub fn set_message(&mut self, msg: impl Into<String>) {
1457        self.message = Some(msg.into());
1458        self.message_time = Some(Instant::now());
1459    }
1460
1461    pub fn clear_stale_message(&mut self) {
1462        let duration = settings().tui_message_duration();
1463        if let Some(time) = self.message_time
1464            && time.elapsed() >= duration
1465        {
1466            self.message = None;
1467            self.message_time = None;
1468        }
1469    }
1470
1471    pub fn get_stats(&self, pid: u32) -> Option<&ProcessStats> {
1472        self.process_stats.get(&pid)
1473    }
1474
1475    fn refresh_process_stats(&mut self) {
1476        let pids: Vec<u32> = self.daemons.iter().filter_map(|d| d.pid).collect();
1477        if !pids.is_empty() {
1478            PROCS.refresh_if_stale();
1479        }
1480        self.process_stats.clear();
1481
1482        let stats_by_pid = PROCS.get_batch_tree_stats_map(&pids);
1483
1484        for daemon in &self.daemons {
1485            if let Some(pid) = daemon.pid
1486                && let Some(stats) = stats_by_pid.get(&pid).copied()
1487            {
1488                self.process_stats.insert(pid, stats);
1489                // Record history for this daemon
1490                let history = self.stats_history.entry(daemon.id.clone()).or_default();
1491                history.push(StatsSnapshot::from(&stats));
1492            }
1493        }
1494    }
1495
1496    /// Get stats history for a daemon
1497    pub fn get_stats_history(&self, daemon_id: &DaemonId) -> Option<&StatsHistory> {
1498        self.stats_history.get(daemon_id)
1499    }
1500
1501    /// Fetch fresh daemon data from IPC. Called from a background task.
1502    pub async fn fetch_daemon_data(
1503        client: &Arc<IpcClient>,
1504        namespace_filter: &NamespaceFilter,
1505    ) -> Result<Vec<DaemonListEntry>> {
1506        use crate::daemon_list::get_all_daemons;
1507        get_all_daemons(client, namespace_filter).await
1508    }
1509
1510    /// Apply previously fetched daemon data to update app state.
1511    pub fn apply_refresh(&mut self, all_entries: Vec<DaemonListEntry>) {
1512        // Clear current lists
1513        self.daemons.clear();
1514        self.disabled.clear();
1515        self.config_daemon_ids.clear();
1516
1517        for entry in all_entries {
1518            let daemon_id = entry.daemon.id.clone();
1519
1520            if entry.is_disabled {
1521                self.disabled.push(daemon_id.clone());
1522            }
1523
1524            if entry.is_available {
1525                self.config_daemon_ids.insert(daemon_id.clone());
1526            }
1527
1528            if !entry.is_available || self.show_available {
1529                self.daemons.push(entry.daemon);
1530            }
1531        }
1532
1533        self.refresh_process_stats();
1534        self.clear_stale_message();
1535
1536        let total_count = self.total_daemon_count();
1537        if total_count > 0 && self.selected >= total_count {
1538            self.selected = total_count - 1;
1539        }
1540
1541        if self.view == View::Logs
1542            && let Some(id) = self.log_daemon_id.clone()
1543        {
1544            self.load_logs(&id);
1545        }
1546    }
1547
1548    pub async fn refresh(&mut self, client: &Arc<IpcClient>) -> Result<()> {
1549        let entries = Self::fetch_daemon_data(client, &self.namespace_filter).await?;
1550        self.apply_refresh(entries);
1551        Ok(())
1552    }
1553
1554    /// Apply network listener data fetched by a background task.
1555    pub fn apply_network_refresh(&mut self, listeners: Vec<Listener>) {
1556        self.network_listeners = listeners;
1557
1558        let filtered_count = self.filtered_network_listeners().len();
1559
1560        if filtered_count > 0 && self.network_selected >= filtered_count {
1561            self.network_selected = filtered_count - 1;
1562        } else if filtered_count == 0 {
1563            self.network_selected = 0;
1564        }
1565
1566        let selected_pid = self
1567            .filtered_network_listeners()
1568            .get(self.network_selected)
1569            .map(|l| l.process.pid);
1570        self.network_selected_pid = selected_pid;
1571    }
1572
1573    /// Get filtered network listeners based on search query
1574    pub fn filtered_network_listeners(&self) -> Vec<&listeners::Listener> {
1575        if self.network_search_query.is_empty() {
1576            return self.network_listeners.iter().collect();
1577        }
1578
1579        let matcher = SkimMatcherV2::default();
1580        let query = &self.network_search_query;
1581
1582        self.network_listeners
1583            .iter()
1584            .filter(|listener| {
1585                // Search by process name, PID, or port
1586                let search_text = format!(
1587                    "{} {} {}",
1588                    listener.process.name,
1589                    listener.process.pid,
1590                    listener.socket.port()
1591                );
1592                matcher.fuzzy_match(&search_text, query).is_some()
1593            })
1594            .collect()
1595    }
1596
1597    /// Toggle network search active state
1598    pub fn toggle_network_search(&mut self) {
1599        self.network_search_active = !self.network_search_active;
1600        if !self.network_search_active {
1601            self.network_search_query.clear();
1602        }
1603        // Reset scroll and selection when toggling search
1604        self.network_selected = 0;
1605        self.network_scroll_offset = 0;
1606        // Update PID for new selection
1607        let filtered = self.filtered_network_listeners();
1608        self.network_selected_pid = filtered.first().map(|l| l.process.pid);
1609    }
1610
1611    /// Clear network search
1612    pub fn clear_network_search(&mut self) {
1613        self.network_search_query.clear();
1614        self.network_search_active = false;
1615        // Reset scroll and selection
1616        self.network_selected = 0;
1617        self.network_scroll_offset = 0;
1618        // Update PID for new selection
1619        let filtered = self.filtered_network_listeners();
1620        self.network_selected_pid = filtered.first().map(|l| l.process.pid);
1621    }
1622
1623    /// Check if a daemon is from config only (not currently active)
1624    pub fn is_config_only(&self, daemon_id: &DaemonId) -> bool {
1625        self.config_daemon_ids.contains(daemon_id)
1626    }
1627
1628    /// Toggle showing available daemons from config
1629    pub fn toggle_show_available(&mut self) {
1630        self.show_available = !self.show_available;
1631    }
1632
1633    /// Get total daemon count (for selection bounds)
1634    fn total_daemon_count(&self) -> usize {
1635        self.filtered_daemons().len()
1636    }
1637
1638    pub fn scroll_logs_down(&mut self) {
1639        let max_scroll = self.log_content.len();
1640        self.log_scroll = (self.log_scroll + 1).clamp(1, max_scroll);
1641    }
1642
1643    pub fn scroll_logs_up(&mut self) {
1644        self.log_scroll = self.log_scroll.saturating_sub(1).max(1);
1645    }
1646
1647    /// Scroll down by half page (Ctrl+D)
1648    pub fn scroll_logs_page_down(&mut self, visible_lines: usize) {
1649        let half_page = visible_lines / 2;
1650        let max_scroll = self.log_content.len();
1651        self.log_scroll = (self.log_scroll + half_page).clamp(1, max_scroll);
1652    }
1653
1654    /// Scroll up by half page (Ctrl+U)
1655    pub fn scroll_logs_page_up(&mut self, visible_lines: usize) {
1656        let half_page = visible_lines / 2;
1657        self.log_scroll = self.log_scroll.saturating_sub(half_page).max(1);
1658    }
1659
1660    // Log search
1661    pub fn start_log_search(&mut self) {
1662        self.log_search_active = true;
1663        self.log_search_query.clear();
1664        self.log_search_matches.clear();
1665        self.log_search_current = 0;
1666    }
1667
1668    pub fn end_log_search(&mut self) {
1669        self.log_search_active = false;
1670    }
1671
1672    pub fn clear_log_search(&mut self) {
1673        self.log_search_query.clear();
1674        self.log_search_active = false;
1675        self.log_search_matches.clear();
1676        self.log_search_current = 0;
1677    }
1678
1679    pub fn log_search_push(&mut self, c: char) {
1680        self.log_search_query.push(c);
1681        self.update_log_search_matches();
1682    }
1683
1684    pub fn log_search_pop(&mut self) {
1685        self.log_search_query.pop();
1686        self.update_log_search_matches();
1687    }
1688
1689    fn update_log_search_matches(&mut self) {
1690        self.log_search_matches.clear();
1691        if !self.log_search_query.is_empty() {
1692            let query = self.log_search_query.to_lowercase();
1693            for (i, line) in self.log_content.iter().enumerate() {
1694                if line.to_lowercase().contains(&query) {
1695                    self.log_search_matches.push(i);
1696                }
1697            }
1698            // Jump to first match if any
1699            if !self.log_search_matches.is_empty() {
1700                self.log_search_current = 0;
1701                self.jump_to_log_match();
1702            }
1703        }
1704    }
1705
1706    pub fn log_search_next(&mut self) {
1707        if !self.log_search_matches.is_empty() {
1708            self.log_search_current = (self.log_search_current + 1) % self.log_search_matches.len();
1709            self.jump_to_log_match();
1710        }
1711    }
1712
1713    pub fn log_search_prev(&mut self) {
1714        if !self.log_search_matches.is_empty() {
1715            self.log_search_current = self
1716                .log_search_current
1717                .checked_sub(1)
1718                .unwrap_or(self.log_search_matches.len() - 1);
1719            self.jump_to_log_match();
1720        }
1721    }
1722
1723    fn jump_to_log_match(&mut self) {
1724        if let Some(&line_idx) = self.log_search_matches.get(self.log_search_current) {
1725            // Scroll so the match is visible (center it if possible)
1726            let half_page = 10; // Assume ~20 visible lines
1727            self.log_scroll = line_idx.saturating_sub(half_page).max(1);
1728            self.log_follow = false;
1729        }
1730    }
1731
1732    // Details view
1733    pub fn show_details(&mut self, daemon_id: &DaemonId) {
1734        self.details_daemon_id = Some(daemon_id.clone());
1735        self.prev_view = self.view;
1736        self.view = View::Details;
1737    }
1738
1739    pub fn hide_details(&mut self) {
1740        self.details_daemon_id = None;
1741        self.view = View::Dashboard;
1742    }
1743
1744    /// View daemon details (charts + logs)
1745    pub fn view_daemon_details(&mut self, daemon_id: &DaemonId) {
1746        self.log_daemon_id = Some(daemon_id.clone());
1747        self.logs_expanded = false; // Start with charts visible
1748        self.load_logs(daemon_id);
1749        self.view = View::Logs; // Logs view is now the full daemon details view
1750    }
1751
1752    fn load_logs(&mut self, daemon_id: &DaemonId) {
1753        const TUI_LOG_LIMIT: usize = 5000;
1754        let prev_len = self.log_content.len();
1755
1756        self.log_content = match LOG_STORE.query(&crate::log_store::LogQuery {
1757            daemon_ids: vec![daemon_id.qualified()],
1758            from: None,
1759            to: None,
1760            limit: Some(TUI_LOG_LIMIT),
1761            order_desc: true,
1762            after_id: None,
1763            before_id: None,
1764            message_filters: Vec::new(),
1765            field_filters: Vec::new(),
1766            include_structured: false,
1767        }) {
1768            Ok(entries) if !entries.is_empty() => {
1769                let mut lines: Vec<String> = entries
1770                    .into_iter()
1771                    .map(|e| {
1772                        let ts = e.timestamp.format("%H:%M:%S").to_string();
1773                        format!("{} {}", ts, e.message)
1774                    })
1775                    .collect();
1776                lines.reverse();
1777                lines
1778            }
1779            _ => vec!["No logs available".to_string()],
1780        };
1781
1782        // Auto-scroll to bottom when in follow mode
1783        if self.log_follow {
1784            self.log_scroll = self.log_content.len().max(1);
1785        } else if prev_len == 0 {
1786            // First load - start at bottom
1787            self.log_scroll = self.log_content.len().max(1);
1788        }
1789        // If not following and not first load, keep scroll position
1790    }
1791
1792    pub fn show_help(&mut self) {
1793        self.view = View::Help;
1794    }
1795
1796    pub fn back_to_dashboard(&mut self) {
1797        self.view = View::Dashboard;
1798        self.log_daemon_id = None;
1799        self.log_content.clear();
1800        self.log_scroll = 1;
1801    }
1802
1803    /// Returns (total, running, stopped, errored, available)
1804    pub fn stats(&self) -> (usize, usize, usize, usize, usize) {
1805        let available = self.config_daemon_ids.len();
1806        let total = self.daemons.len();
1807        let running = self
1808            .daemons
1809            .iter()
1810            .filter(|d| d.status.is_running())
1811            .count();
1812        // Don't count config-only daemons as stopped
1813        let stopped = self
1814            .daemons
1815            .iter()
1816            .filter(|d| d.status.is_stopped() && !self.config_daemon_ids.contains(&d.id))
1817            .count();
1818        let errored = self
1819            .daemons
1820            .iter()
1821            .filter(|d| d.status.is_errored() || d.status.is_failed())
1822            .count();
1823        (total, running, stopped, errored, available)
1824    }
1825
1826    pub fn is_disabled(&self, daemon_id: &DaemonId) -> bool {
1827        self.disabled.contains(daemon_id)
1828    }
1829
1830    // Config editor methods
1831
1832    /// Get list of available config file paths
1833    pub fn get_config_files(&self) -> Vec<PathBuf> {
1834        let mut files: Vec<PathBuf> = PitchforkToml::list_paths()
1835            .into_iter()
1836            .filter(|p| p.exists())
1837            .collect();
1838
1839        // Add option to create in current directory if not present
1840        let cwd_config = crate::env::CWD.join("pitchfork.toml");
1841        if !files.contains(&cwd_config) {
1842            files.push(cwd_config);
1843        }
1844
1845        files
1846    }
1847
1848    /// Open file selector for creating a new daemon
1849    pub fn open_file_selector(&mut self) {
1850        let files = self.get_config_files();
1851        self.file_selector = Some(ConfigFileSelector { files, selected: 0 });
1852        self.view = View::ConfigFileSelect;
1853    }
1854
1855    /// Open editor for a new daemon with the selected config file
1856    pub fn open_editor_create(&mut self, config_path: PathBuf) {
1857        self.editor_state = Some(EditorState::new_create(config_path));
1858        self.file_selector = None;
1859        self.view = View::ConfigEditor;
1860    }
1861
1862    /// Open editor for an existing daemon
1863    pub fn open_editor_edit(&mut self, daemon_id: &DaemonId) {
1864        let config = match PitchforkToml::all_merged() {
1865            Ok(config) => config,
1866            Err(e) => {
1867                self.set_message(format!("Failed to load config: {e}"));
1868                return;
1869            }
1870        };
1871        if let Some(daemon_config) = config.daemons.get(daemon_id) {
1872            let config_path = daemon_config
1873                .path
1874                .clone()
1875                .unwrap_or_else(|| crate::env::CWD.join("pitchfork.toml"));
1876            self.editor_state = Some(EditorState::new_edit(
1877                daemon_id.to_string(),
1878                daemon_config,
1879                config_path,
1880            ));
1881            self.view = View::ConfigEditor;
1882        } else {
1883            self.set_message(format!("Daemon '{daemon_id}' not found in config"));
1884        }
1885    }
1886
1887    /// Close the editor and return to dashboard
1888    pub fn close_editor(&mut self) {
1889        self.editor_state = None;
1890        self.file_selector = None;
1891        self.view = View::Dashboard;
1892    }
1893
1894    /// Save the current editor state to config file.
1895    /// Returns Ok(true) if saved successfully, Ok(false) if validation/duplicate error (don't close editor).
1896    pub fn save_editor_config(&mut self) -> Result<bool> {
1897        let editor = self
1898            .editor_state
1899            .as_mut()
1900            .ok_or_else(|| miette::miette!("No editor state"))?;
1901
1902        // Validate
1903        if !editor.validate() {
1904            self.set_message("Please fix validation errors before saving");
1905            return Ok(false);
1906        }
1907
1908        // Build daemon config
1909        let daemon_config = editor.to_daemon_config();
1910
1911        // Parse daemon ID from string
1912        let daemon_id = DaemonId::parse(&editor.daemon_id)
1913            .map_err(|e| miette::miette!("Invalid daemon ID: {}", e))?;
1914
1915        // Read existing config (or create new)
1916        let mut config = PitchforkToml::read(&editor.config_path)?;
1917
1918        // Check for duplicate daemon ID
1919        let is_duplicate = match &editor.mode {
1920            EditMode::Create => config.daemons.contains_key(&daemon_id),
1921            EditMode::Edit { original_id } => {
1922                // Only a duplicate if ID changed AND new ID already exists
1923                let original_daemon_id = DaemonId::parse(original_id)
1924                    .map_err(|e| miette::miette!("Invalid original daemon ID: {}", e))?;
1925                original_daemon_id != daemon_id && config.daemons.contains_key(&daemon_id)
1926            }
1927        };
1928
1929        if is_duplicate {
1930            self.set_message(format!("A daemon named '{daemon_id}' already exists"));
1931            return Ok(false);
1932        }
1933
1934        // Handle rename case
1935        if let EditMode::Edit { original_id } = &editor.mode {
1936            let original_daemon_id = DaemonId::parse(original_id)
1937                .map_err(|e| miette::miette!("Invalid original daemon ID: {}", e))?;
1938            if original_daemon_id != daemon_id {
1939                config.daemons.shift_remove(&original_daemon_id);
1940            }
1941        }
1942
1943        // Insert/update daemon
1944        config.daemons.insert(daemon_id, daemon_config);
1945
1946        // A rename can make a dependency's `as` name clash with a daemon.
1947        if let Err(e) = config.validate_dependency_aliases() {
1948            self.set_message(format!("{e}"));
1949            return Ok(false);
1950        }
1951
1952        // An `as` name can also clash with a daemon in a sibling file, or with
1953        // one a rename un-overrides. Check the merged config as it will load
1954        // after the save, before writing. A project that already fails to load
1955        // can still be saved, so it can be repaired.
1956        if let Err(e) = PitchforkToml::validate_aliases_after_save(&crate::env::CWD, &config) {
1957            self.set_message(format!("Not saved: {e}"));
1958            return Ok(false);
1959        }
1960
1961        config.write()?;
1962
1963        editor.unsaved_changes = false;
1964        let daemon_id = editor.daemon_id.clone();
1965        self.set_message(format!("Saved daemon '{daemon_id}'"));
1966
1967        Ok(true)
1968    }
1969
1970    /// Delete a daemon from the config file. Returns Ok(true) if deleted, Ok(false) if not found.
1971    pub fn delete_daemon_from_config(
1972        &mut self,
1973        id: &str,
1974        config_path: &std::path::Path,
1975    ) -> Result<bool> {
1976        let mut config = PitchforkToml::read(config_path)?;
1977
1978        // For qualified IDs, parse directly; for bare names derive the namespace
1979        // from the config file path so project-level daemons are found correctly.
1980        let daemon_id = if id.contains('/') {
1981            DaemonId::parse(id)?
1982        } else {
1983            let ns = namespace_from_path(config_path)?;
1984            DaemonId::try_new(&ns, id)?
1985        };
1986
1987        if config.daemons.shift_remove(&daemon_id).is_some() {
1988            config.write()?;
1989            Ok(true)
1990        } else {
1991            Ok(false)
1992        }
1993    }
1994}
1995
1996impl Default for App {
1997    fn default() -> Self {
1998        Self::new(NamespaceFilter::default())
1999    }
2000}
2001
2002#[cfg(test)]
2003mod run_argv_editor_tests {
2004    use super::*;
2005
2006    fn argv(words: &[&str]) -> RunCommand {
2007        RunCommand::Argv(words.iter().map(|w| w.to_string()).collect())
2008    }
2009
2010    fn editor(run: RunCommand) -> EditorState {
2011        let config = PitchforkTomlDaemon {
2012            run,
2013            ..PitchforkTomlDaemon::default()
2014        };
2015        EditorState::new_edit("api".to_string(), &config, PathBuf::from("pitchfork.toml"))
2016    }
2017
2018    fn set_run(editor: &mut EditorState, text: &str) {
2019        let field = editor.fields.iter_mut().find(|f| f.name == "run").unwrap();
2020        field.set_text(text.to_string());
2021    }
2022
2023    #[test]
2024    fn saving_keeps_dependency_template_names() {
2025        let dep = DaemonId::new("search-abc", "app");
2026        let mut config = PitchforkTomlDaemon {
2027            run: "echo".into(),
2028            depends: vec![dep.clone()],
2029            ..PitchforkTomlDaemon::default()
2030        };
2031        config.depends_as.insert("search".to_string(), dep.clone());
2032        let editor =
2033            EditorState::new_edit("api".to_string(), &config, PathBuf::from("pitchfork.toml"));
2034        let saved = editor.to_daemon_config();
2035        assert_eq!(saved.depends, vec![dep.clone()]);
2036        assert_eq!(saved.depends_as["search"], dep);
2037    }
2038
2039    #[test]
2040    fn an_untouched_array_is_saved_as_an_array() {
2041        let run = argv(&["node", "my server.js"]);
2042        let editor = editor(run.clone());
2043        assert_eq!(editor.to_daemon_config().run, run);
2044    }
2045
2046    #[test]
2047    fn an_edited_array_stays_an_array() {
2048        let mut editor = editor(argv(&["node", "my server.js"]));
2049        set_run(&mut editor, "node 'my server.js' --port 8080");
2050        assert!(editor.validate());
2051        assert_eq!(
2052            editor.to_daemon_config().run,
2053            argv(&["node", "my server.js", "--port", "8080"])
2054        );
2055    }
2056
2057    #[test]
2058    fn an_edited_array_must_still_parse() {
2059        let mut editor = editor(argv(&["node", "server.js"]));
2060        set_run(&mut editor, "node 'server.js");
2061        assert!(!editor.validate());
2062        set_run(&mut editor, "exec node server.js");
2063        assert!(!editor.validate());
2064    }
2065
2066    #[test]
2067    fn a_string_stays_a_string() {
2068        let mut editor = editor("exec node server.js".into());
2069        set_run(&mut editor, "exec node 'my server.js'");
2070        assert!(editor.validate());
2071        assert_eq!(editor.to_daemon_config().run, "exec node 'my server.js'");
2072    }
2073}
2074
2075#[cfg(test)]
2076mod run_argv_editor_review_tests {
2077    use super::*;
2078
2079    fn editor(run: RunCommand) -> EditorState {
2080        let config = PitchforkTomlDaemon {
2081            run,
2082            ..PitchforkTomlDaemon::default()
2083        };
2084        EditorState::new_edit("api".to_string(), &config, PathBuf::from("pitchfork.toml"))
2085    }
2086
2087    fn set_run(editor: &mut EditorState, text: &str) {
2088        let field = editor.fields.iter_mut().find(|f| f.name == "run").unwrap();
2089        field.set_text(text.to_string());
2090    }
2091
2092    #[test]
2093    fn windows_edit_text_round_trips_awkward_arguments() {
2094        let argv: Vec<String> = [
2095            r"C:\Program Files\node.exe",
2096            "",
2097            "it's",
2098            "say \"hi\"",
2099            "both ' and \"",
2100            r"trailing\",
2101            "a&b",
2102        ]
2103        .map(str::to_string)
2104        .to_vec();
2105        let text = argv
2106            .iter()
2107            .map(|a| windows_edit_quote(a))
2108            .collect::<Vec<_>>()
2109            .join(" ");
2110        assert_eq!(windows_edit_split(&text).unwrap(), argv, "text: {text}");
2111    }
2112
2113    #[test]
2114    fn windows_edit_split_keeps_backslashes_and_refuses_open_quotes() {
2115        assert_eq!(
2116            windows_edit_split(r#"C:\Tools\node.exe "my server.js"  x"#).unwrap(),
2117            vec![r"C:\Tools\node.exe", "my server.js", "x"]
2118        );
2119        assert!(windows_edit_split("node 'server.js").is_err());
2120    }
2121
2122    #[test]
2123    fn an_empty_program_is_rejected() {
2124        let mut editor = editor(RunCommand::Argv(vec!["node".into()]));
2125        set_run(&mut editor, "'' node");
2126        assert!(!editor.validate());
2127    }
2128
2129    #[cfg(windows)]
2130    #[test]
2131    fn a_windows_path_keeps_its_backslashes() {
2132        let mut editor = editor(RunCommand::Argv(vec!["node".into()]));
2133        set_run(&mut editor, r"C:\Tools\node.exe --port 8080");
2134        assert!(editor.validate());
2135        assert_eq!(
2136            editor.to_daemon_config().run,
2137            RunCommand::Argv(vec![
2138                r"C:\Tools\node.exe".into(),
2139                "--port".into(),
2140                "8080".into()
2141            ])
2142        );
2143    }
2144}
2145
2146#[cfg(test)]
2147mod health_cmd_argv_editor_tests {
2148    use super::*;
2149    use crate::config_types::HealthCmd;
2150
2151    fn argv(words: &[&str]) -> RunCommand {
2152        RunCommand::Argv(words.iter().map(|w| w.to_string()).collect())
2153    }
2154
2155    fn editor(health_cmd: HealthCmd) -> EditorState {
2156        let config = PitchforkTomlDaemon {
2157            run: "sleep 60".into(),
2158            health_cmd: Some(health_cmd),
2159            ..PitchforkTomlDaemon::default()
2160        };
2161        EditorState::new_edit("api".to_string(), &config, PathBuf::from("pitchfork.toml"))
2162    }
2163
2164    fn set_health_cmd(editor: &mut EditorState, text: &str) {
2165        let field = editor
2166            .fields
2167            .iter_mut()
2168            .find(|f| f.name == "health_cmd")
2169            .unwrap();
2170        field.set_text(text.to_string());
2171    }
2172
2173    #[test]
2174    fn an_untouched_array_is_saved_as_an_array_with_its_settings() {
2175        let health_cmd = HealthCmd {
2176            run: argv(&["pg_isready", "-h", "my host"]),
2177            interval: Some(std::time::Duration::from_secs(5)),
2178            ..HealthCmd::default()
2179        };
2180        let editor = editor(health_cmd.clone());
2181        assert_eq!(editor.to_daemon_config().health_cmd, Some(health_cmd));
2182    }
2183
2184    #[test]
2185    fn an_edited_array_stays_an_array() {
2186        let mut editor = editor(HealthCmd::new(argv(&["pg_isready"])));
2187        set_health_cmd(&mut editor, "pg_isready -h 'my host'");
2188        assert!(editor.validate());
2189        assert_eq!(
2190            editor.to_daemon_config().health_cmd.unwrap().run,
2191            argv(&["pg_isready", "-h", "my host"])
2192        );
2193    }
2194
2195    #[test]
2196    fn an_edited_array_must_still_parse() {
2197        let mut editor = editor(HealthCmd::new(argv(&["pg_isready"])));
2198        set_health_cmd(&mut editor, "pg_isready -h 'my host");
2199        assert!(!editor.validate());
2200        set_health_cmd(&mut editor, "exec pg_isready");
2201        assert!(!editor.validate());
2202    }
2203
2204    #[test]
2205    fn a_string_stays_a_string() {
2206        let mut editor = editor(HealthCmd::new("curl -f http://localhost"));
2207        set_health_cmd(&mut editor, "curl -f 'http://localhost/a b'");
2208        assert!(editor.validate());
2209        assert_eq!(
2210            editor.to_daemon_config().health_cmd.unwrap().run,
2211            "curl -f 'http://localhost/a b'"
2212        );
2213    }
2214}