Skip to main content

pitchfork_cli/cli/
logs.rs

1use crate::cli::json_output::{JsonLogEntry, print_json};
2use crate::daemon_id::DaemonId;
3use crate::log_store::sqlite::LOG_STORE;
4use crate::log_store::{FieldFilter, LogEntry, LogQuery, LogStore, MessageFilter};
5use crate::pitchfork_toml::PitchforkToml;
6use crate::settings::settings;
7use crate::state_file::StateFile;
8use crate::ui::style::{edim, estyle, ndim};
9use crate::{Result, env};
10use chrono::{DateTime, Local, NaiveDateTime, NaiveTime, TimeZone};
11use console;
12use itertools::Itertools;
13use miette::IntoDiagnostic;
14use std::collections::BTreeSet;
15use std::fmt::Write as _;
16use std::io::{self, IsTerminal, Write};
17use std::process::{Child, Command, Stdio};
18use std::time::Duration;
19
20/// Pager configuration for displaying logs
21struct PagerConfig {
22    command: String,
23    args: Vec<String>,
24}
25
26impl PagerConfig {
27    /// Select and configure the appropriate pager.
28    /// Uses $PAGER environment variable if set, otherwise defaults to less.
29    fn new(start_at_end: bool) -> Self {
30        let command = std::env::var("PAGER").unwrap_or_else(|_| "less".to_string());
31        let args = Self::build_args(&command, start_at_end);
32        Self { command, args }
33    }
34
35    fn build_args(pager: &str, start_at_end: bool) -> Vec<String> {
36        let mut args = vec![];
37        if pager == "less" {
38            args.push("-R".to_string());
39            if start_at_end {
40                args.push("+G".to_string());
41            }
42        }
43        args
44    }
45
46    /// Spawn the pager with piped stdin
47    fn spawn_piped(&self) -> io::Result<Child> {
48        Command::new(&self.command)
49            .args(&self.args)
50            .stdin(Stdio::piped())
51            .spawn()
52    }
53}
54
55/// Fields already displayed in dedicated positions; excluded from the
56/// extra-fields section of structured log output.
57const KNOWN_FIELD_KEYS: &[&str] = &[
58    "level",
59    "severity",
60    "lvl",
61    "PRIORITY",
62    "@level",
63    "msg",
64    "message",
65    "event",
66    "@message",
67    "logger",
68    "name",
69    "component",
70    "module",
71    "timestamp",
72    "ts",
73    "time",
74    "@timestamp",
75];
76
77/// Format a log level badge: `[ERR]`, `[WRN|`, etc.
78///
79/// Brackets use the same dim color as the logger; the level letters use the
80/// level's accent color in bold.
81fn level_badge(level: &str) -> String {
82    let label = match level {
83        "error" => console::style("ERR").red().bold(),
84        "warn" => console::style("WRN").yellow().bold(),
85        "info" => console::style("INF").cyan().bold(),
86        "debug" => console::style("DBG").magenta().bold(),
87        "trace" => console::style("TRC").dim().bold(),
88        _ => return String::new(),
89    };
90    format!("{}{}{}", ndim("["), label, ndim("]"))
91}
92
93/// Format a single JSON value for display in the fields section.
94///
95/// Strings that look like booleans, null, numbers, or contain spaces are
96/// quoted to avoid ambiguity. Numbers are green, booleans are
97/// yellow/red, null is dim.
98fn format_field_value(value: &serde_json::Value) -> String {
99    match value {
100        serde_json::Value::String(s) => {
101            let needs_quotes = s.is_empty()
102                || s.contains(' ')
103                || s.contains('=')
104                || s.contains('\t')
105                || s == "true"
106                || s == "false"
107                || s == "null"
108                || s.parse::<f64>().is_ok();
109            if needs_quotes {
110                format!("\"{s}\"")
111            } else {
112                s.clone()
113            }
114        }
115        serde_json::Value::Number(n) => console::style(n).green().to_string(),
116        serde_json::Value::Bool(true) => console::style("true").yellow().to_string(),
117        serde_json::Value::Bool(false) => console::style("false").red().to_string(),
118        serde_json::Value::Null => console::style("null").dim().to_string(),
119        serde_json::Value::Object(_) | serde_json::Value::Array(_) => {
120            serde_json::to_string(value).unwrap_or_else(|_| value.to_string())
121        }
122    }
123}
124
125/// Format structured fields as `key=value` pairs, excluding known keys.
126fn format_fields(fields_json: &str) -> String {
127    let Ok(serde_json::Value::Object(obj)) = serde_json::from_str(fields_json) else {
128        return String::new();
129    };
130    let mut parts = Vec::new();
131    for (key, value) in &obj {
132        if KNOWN_FIELD_KEYS.contains(&key.as_str()) {
133            continue;
134        }
135        let key_styled = console::style(key.as_str()).blue().to_string();
136        let value_styled = format_field_value(value);
137        parts.push(format!("{key_styled}={value_styled}"));
138    }
139    parts.join(" ")
140}
141
142/// Format and write a single log entry with structured field highlighting.
143///
144/// When `raw` is set, the original message is emitted verbatim (after ANSI
145/// stripping if requested), ignoring any structured fields. This keeps `--raw`
146/// honored even when `--jq` populates `fields_json` for filtering.
147///
148/// Otherwise, when the entry has structured fields (`fields_json` is `Some`),
149/// renders as: `<timestamp> [LEVEL] logger: message > key=value key=value`
150/// For warn/error levels, the timestamp and message use the level's accent color.
151///
152/// Falls back to plain display: `<timestamp> message`
153#[allow(clippy::too_many_arguments)]
154fn write_formatted_log(
155    w: &mut dyn Write,
156    entry: &LogEntry,
157    date: &str,
158    single_daemon: bool,
159    strip_ansi: bool,
160    show_timestamp: bool,
161    raw: bool,
162) -> io::Result<()> {
163    // Always strip PTY control sequences (cursor moves, clear screen, etc.)
164    // while preserving SGR color codes. PTY daemons emit these sequences which
165    // can corrupt pager output (e.g. triggering page breaks in `less`).
166    let clean_msg = strip_pty_controls(&entry.message);
167    let raw_msg: std::borrow::Cow<'_, str> = if strip_ansi {
168        console::strip_ansi_codes(&clean_msg)
169    } else {
170        std::borrow::Cow::Owned(clean_msg)
171    };
172
173    let mut out = String::with_capacity(256);
174
175    if raw {
176        // Raw mode: emit timestamp + original line verbatim. Structured
177        // fields may still be populated (e.g. --jq needs them for
178        // filtering) but must not alter the raw output format.
179        if show_timestamp {
180            out.push_str(&ndim(date).to_string());
181            out.push(' ');
182        }
183        if !single_daemon {
184            let colors_on = !strip_ansi && console::colors_enabled();
185            out.push_str(&colored_id_label(&entry.daemon_id, colors_on));
186            out.push(' ');
187        }
188        out.push_str(&raw_msg);
189    } else if entry.fields_json.is_some() {
190        // Structured display: [LEVEL] logger: message > key=value
191        let level = entry.level.as_deref();
192        let accent = match level {
193            Some("error") => "error",
194            Some("warn") => "warn",
195            _ => "",
196        };
197
198        // Timestamp — accent-colored for warn/error
199        if show_timestamp {
200            let ts = match accent {
201                "error" => console::style(date).red().to_string(),
202                "warn" => console::style(date).yellow().to_string(),
203                _ => ndim(date).to_string(),
204            };
205            out.push_str(&ts);
206            out.push(' ');
207        }
208
209        // Daemon ID (multi-daemon mode)
210        if !single_daemon {
211            let colors_on = !strip_ansi && console::colors_enabled();
212            out.push_str(&colored_id_label(&entry.daemon_id, colors_on));
213            out.push(' ');
214        }
215
216        let mut need_sep = false;
217
218        // Level badge: [ERR] with dim brackets + bold accent letters
219        if let Some(lvl) = level {
220            let badge = level_badge(lvl);
221            if !badge.is_empty() {
222                out.push_str(&badge);
223                need_sep = true;
224            }
225        }
226
227        // Separators (colon, arrow): always dim regardless of level
228        let sep = ndim(":").to_string();
229        let arrow = ndim(" > ").to_string();
230
231        // Logger: italic + colon
232        if let Some(logger) = &entry.logger {
233            if need_sep {
234                out.push(' ');
235            }
236            out.push_str(&console::style(logger).italic().dim().to_string());
237            out.push_str(&sep);
238            need_sep = true;
239        }
240
241        // Message (bold, accent-colored for warn/error) + fields
242        let msg_cow = entry.msg.as_deref().filter(|s| !s.is_empty()).map(|s| {
243            let cleaned = strip_pty_controls(s);
244            if strip_ansi {
245                std::borrow::Cow::<str>::Owned(console::strip_ansi_codes(&cleaned).to_string())
246            } else {
247                std::borrow::Cow::<str>::Owned(cleaned)
248            }
249        });
250        let fields_str = entry
251            .fields_json
252            .as_deref()
253            .map(format_fields)
254            .filter(|s| !s.is_empty());
255
256        if msg_cow.is_some() || fields_str.is_some() {
257            if need_sep {
258                out.push(' ');
259            }
260            if let Some(msg) = &msg_cow {
261                let styled = match accent {
262                    "error" => console::style(msg.as_ref()).red().bold().to_string(),
263                    "warn" => console::style(msg.as_ref()).yellow().bold().to_string(),
264                    _ => console::style(msg.as_ref()).bold().to_string(),
265                };
266                out.push_str(&styled);
267                if fields_str.is_some() {
268                    out.push_str(&arrow);
269                }
270            }
271            if let Some(fields) = &fields_str {
272                out.push_str(fields);
273            }
274        } else if !need_sep {
275            // No level badge, logger, message, or fields — fall back to
276            // the raw message so the line isn't empty.
277            out.push_str(&raw_msg);
278        }
279    } else {
280        // Unstructured log: timestamp + raw message
281        if show_timestamp {
282            out.push_str(&ndim(date).to_string());
283            out.push(' ');
284        }
285        if !single_daemon {
286            let colors_on = !strip_ansi && console::colors_enabled();
287            out.push_str(&colored_id_label(&entry.daemon_id, colors_on));
288            out.push(' ');
289        }
290        out.push_str(&raw_msg);
291    }
292
293    out.push('\n');
294    w.write_all(out.as_bytes())
295}
296
297/// Return a colorized `[namespace/id]` label for display in progress jobs.
298/// Uses brighter colors than `dimmed_id` and includes the square brackets.
299pub fn colored_id_label(id: &str, colors_enabled: bool) -> String {
300    if !colors_enabled {
301        return format!("[{}]", id);
302    }
303    // Same palette as mise: Blue, Magenta, Cyan, Green
304    // Excludes Red/Yellow to avoid confusion with errors/warnings.
305    let colors: [u8; 4] = [34, 35, 36, 32]; // ANSI: Blue, Magenta, Cyan, Green
306    let mut h: usize = 0x811C_9DC5; // FNV offset basis
307    for b in id.bytes() {
308        h = h.wrapping_mul(0x0100_0193).wrapping_add(b as usize);
309    }
310    let color = colors[h % colors.len()];
311    format!("\x1b[{color}m[{id}]\x1b[0m")
312}
313
314/// Displays logs for daemon(s)
315#[derive(Debug, usage_rs::Args)]
316#[usage(
317    verbatim_doc_comment,
318    long_about = "\
319Displays logs for daemon(s)
320
321Shows logs from managed daemons. Logs are stored in the pitchfork logs directory
322and include timestamps for filtering.
323
324Examples:
325
326    pitchfork logs api              Show all logs for 'api' (paged if needed)
327    pitchfork logs api worker       Show logs for multiple daemons
328    pitchfork logs                  Show logs for all daemons
329    pitchfork logs api -n 50        Show last 50 lines
330    pitchfork logs api --follow     Follow logs in real-time
331    pitchfork logs api --since '2024-01-15 10:00:00'
332                                    Show logs since a specific time (forward)
333    pitchfork logs api --since '10:30:00'
334                                    Show logs since 10:30:00 today
335    pitchfork logs api --since '10:30' --until '12:00'
336                                    Show logs since 10:30:00 until 12:00:00 today
337    pitchfork logs api --since 5min Show logs from last 5 minutes
338    pitchfork logs api --raw        Output raw log lines without formatting
339    pitchfork logs api --raw -n 100 Output last 100 raw log lines
340    pitchfork logs api --clear      Delete logs for 'api'
341    pitchfork logs --clear          Delete logs for all daemons"
342)]
343pub struct Logs {
344    /// Show only logs for the specified daemon(s)
345    id: Vec<String>,
346
347    /// Delete logs
348    #[usage(short, long, effect = "destructive")]
349    clear: bool,
350
351    /// Show last N lines of logs
352    ///
353    /// With --since/--until, shows the last N matching lines in that time range.
354    /// Without this option, all logs are shown.
355    #[usage(short)]
356    n: Option<usize>,
357
358    /// Show logs in real-time
359    // usage-rs 7.3 requires repeated short keys for advertised aliases; it has
360    // no plural short selector. Keep both spellings until that grammar changes.
361    #[allow(
362        clippy::duplicated_attributes,
363        reason = "usage-rs intentionally repeats short to preserve both -t and -f"
364    )]
365    #[usage(short = 't', short = 'f', long, visible_alias = "follow")]
366    pub(super) tail: bool,
367
368    /// Show logs from this time
369    ///
370    /// Supports multiple formats:
371    /// - Full datetime: "YYYY-MM-DD HH:MM:SS" or "YYYY-MM-DD HH:MM"
372    /// - Time only: "HH:MM:SS" or "HH:MM" (uses today's date)
373    /// - Relative time: "5min", "2h", "1d" (e.g., last 5 minutes)
374    #[usage(short = 's', long)]
375    since: Option<String>,
376
377    /// Show logs until this time
378    ///
379    /// Supports multiple formats:
380    /// - Full datetime: "YYYY-MM-DD HH:MM:SS" or "YYYY-MM-DD HH:MM"
381    /// - Time only: "HH:MM:SS" or "HH:MM" (uses today's date)
382    #[usage(short = 'u', long)]
383    until: Option<String>,
384
385    /// Disable pager even in interactive terminal
386    #[usage(long)]
387    no_pager: bool,
388
389    /// Output raw log lines without color or formatting
390    #[usage(long)]
391    raw: bool,
392
393    /// Output in JSON format
394    #[usage(long, conflicts = "raw", conflicts = "tail")]
395    json: bool,
396
397    /// Filter logs by case-insensitive substring (can be repeated)
398    ///
399    /// Multiple --grep options are combined with OR.
400    #[usage(long)]
401    grep: Vec<String>,
402
403    /// Filter logs by regular expression
404    #[usage(long)]
405    regex: Option<String>,
406
407    /// Make --grep matching case-sensitive
408    #[usage(long)]
409    case_sensitive: bool,
410
411    /// Filter by minimum log level (error, warn, info, debug, trace)
412    ///
413    /// Shows entries at or above the given severity.
414    /// For example, `--level warn` shows warn and error.
415    /// Only effective for daemons with log_format json or logfmt.
416    #[usage(long)]
417    level: Option<String>,
418
419    /// Filter by structured field value (KEY=VALUE, can be repeated)
420    ///
421    /// Extracts the value from fields_json using json_extract($.KEY).
422    /// Multiple --field options are combined with AND.
423    #[usage(long, value_name = "KEY=VALUE")]
424    field: Vec<String>,
425
426    /// Filter log entries with a jq expression
427    ///
428    /// Each log entry is serialized as a JSON object with fields:
429    /// timestamp, daemon_id, message, level, msg, logger, fields.
430    /// Entries for which the expression produces a truthy value are shown.
431    #[usage(long, value_name = "EXPR")]
432    jq: Option<String>,
433
434    /// Omit timestamps from log output
435    #[usage(long)]
436    no_timestamp: bool,
437}
438
439impl Logs {
440    pub async fn run(&self) -> Result<()> {
441        migrate_legacy_log_dirs();
442
443        let resolved_ids: Vec<DaemonId> = if self.id.is_empty() {
444            get_all_daemon_ids()?
445        } else {
446            PitchforkToml::resolve_ids(&self.id)?
447        };
448
449        if self.clear {
450            LOG_STORE.clear(&resolved_ids)?;
451            return Ok(());
452        }
453
454        let from = if let Some(since) = self.since.as_ref() {
455            Some(parse_time_input(since, true)?)
456        } else {
457            None
458        };
459        let to = if let Some(until) = self.until.as_ref() {
460            Some(parse_time_input(until, false)?)
461        } else {
462            None
463        };
464
465        let message_filters = self.build_message_filters()?;
466        let field_filters = self.build_field_filters()?;
467
468        // Compile jq filter early so parse errors surface before any query.
469        let jq_filter = match self.jq.as_deref() {
470            Some(expr) => Some(crate::log_jq::JqFilter::new(expr)?),
471            None => None,
472        };
473
474        if self.json {
475            return self.output_json(
476                &resolved_ids,
477                from,
478                to,
479                message_filters,
480                field_filters,
481                jq_filter.as_ref(),
482            );
483        }
484
485        // Only suppress the daemon id label when the user explicitly asked
486        // for a single daemon. When no daemon is named on the command line
487        // (e.g. `pf logs`), ids are shown even if only one daemon has logs,
488        // so the user can tell where each line came from.
489        let single_daemon = resolved_ids.len() == 1 && !self.id.is_empty();
490        let show_timestamp = settings().logs.timestamp && !self.no_timestamp && !self.raw;
491        let has_time_filter = from.is_some() || to.is_some();
492
493        self.query_and_output(
494            &resolved_ids,
495            from,
496            to,
497            message_filters.clone(),
498            field_filters.clone(),
499            jq_filter.as_ref(),
500            single_daemon,
501            has_time_filter,
502            show_timestamp,
503        )?;
504
505        if self.tail {
506            tail_logs(
507                &resolved_ids,
508                single_daemon,
509                true,
510                message_filters,
511                field_filters,
512                jq_filter.as_ref(),
513                show_timestamp,
514                self.raw,
515            )
516            .await?;
517        }
518
519        Ok(())
520    }
521
522    /// The row limit for the SQL query. `-n` is applied there only when
523    /// nothing filters the rows afterwards: a time filter trims to the last N
524    /// once the rows are in chronological order, and a jq filter runs after
525    /// the query, so limiting first would show only the matches among the
526    /// last N entries rather than the last N matches.
527    fn query_limit(&self, has_time_filter: bool, has_jq_filter: bool) -> Option<usize> {
528        if has_time_filter || has_jq_filter {
529            None
530        } else {
531            self.n
532        }
533    }
534
535    /// Run `opts` and apply the jq filter, if any: newest first without a
536    /// time filter, chronological with one.
537    ///
538    /// With `--jq` and `-n` the last N matches are wanted, but jq runs after
539    /// the query, so the query reads a window of the newest rows that grows
540    /// until it holds N matches or covers them all (see [`last_matches`]).
541    fn query_entries(
542        &self,
543        mut opts: LogQuery,
544        jq_filter: Option<&crate::log_jq::JqFilter>,
545        has_time_filter: bool,
546    ) -> Result<Vec<LogEntry>> {
547        let Some(jq) = jq_filter else {
548            return LOG_STORE.query(&opts);
549        };
550        match self.n {
551            Some(n) if !has_time_filter => last_matches(
552                n,
553                |window| {
554                    opts.limit = Some(window);
555                    LOG_STORE.query(&opts)
556                },
557                |rows| jq.filter(rows),
558            ),
559            _ => Ok(jq.filter(LOG_STORE.query(&opts)?)),
560        }
561    }
562
563    fn build_message_filters(&self) -> Result<Vec<MessageFilter>> {
564        if self.case_sensitive && self.grep.is_empty() {
565            warn!("--case-sensitive has no effect without --grep");
566        }
567        let mut filters = Vec::new();
568        for pattern in &self.grep {
569            filters.push(MessageFilter::Contains {
570                pattern: pattern.clone(),
571                case_sensitive: self.case_sensitive,
572            });
573        }
574        if let Some(pattern) = self.regex.as_ref() {
575            // Validate the regex early so the user gets a clear CLI error
576            // instead of a SQLite user-function failure at query time.
577            let _ = regex::Regex::new(pattern)
578                .into_diagnostic()
579                .map_err(|e| miette::miette!("invalid regex pattern: {e}"))?;
580            filters.push(MessageFilter::Regex {
581                pattern: pattern.clone(),
582            });
583        }
584        Ok(filters)
585    }
586
587    fn build_field_filters(&self) -> Result<Vec<FieldFilter>> {
588        let mut filters = Vec::new();
589        if let Some(level) = self.level.as_ref() {
590            // Normalize the user-supplied level so "ERROR", "Error", "fatal"
591            // all match the stored canonical form.
592            let normalized = crate::log_parse::normalize_level_str(level).ok_or_else(|| {
593                miette::miette!(
594                    "invalid level '{level}'; expected one of: \
595                         error, err, fatal, critical, panic, alert, emerg, \
596                         warn, warning, info, inf, information, notice, \
597                         debug, dbg, trace, trc"
598                )
599            })?;
600            filters.push(FieldFilter::LevelMin(normalized));
601        }
602        for pair in &self.field {
603            let (key, value) = pair
604                .split_once('=')
605                .ok_or_else(|| miette::miette!("--field expects KEY=VALUE, got: {pair}"))?;
606            if key.is_empty() {
607                miette::bail!("--field key cannot be empty: {pair}");
608            }
609            // Whitelist key characters to prevent SQL injection via
610            // json_extract path interpolation.
611            if !key
612                .chars()
613                .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
614            {
615                miette::bail!(
616                    "--field key may only contain alphanumeric, underscore, and dot; got: {key}"
617                );
618            }
619            filters.push(FieldFilter::FieldEq {
620                key: key.to_string(),
621                value: value.to_string(),
622            });
623        }
624        Ok(filters)
625    }
626
627    /// Query log entries and stream them directly to output, bypassing the
628    /// intermediate `Vec<(String, String, String)>` layer. This eliminates
629    /// 3 String allocations per row (timestamp format, daemon_id clone,
630    /// message clone) by borrowing directly from `LogEntry` and reusing a
631    /// single date buffer.
632    #[allow(clippy::too_many_arguments)]
633    fn query_and_output(
634        &self,
635        resolved_ids: &[DaemonId],
636        from: Option<DateTime<Local>>,
637        to: Option<DateTime<Local>>,
638        message_filters: Vec<MessageFilter>,
639        field_filters: Vec<FieldFilter>,
640        jq_filter: Option<&crate::log_jq::JqFilter>,
641        single_daemon: bool,
642        has_time_filter: bool,
643        show_timestamp: bool,
644    ) -> Result<()> {
645        let daemon_ids: Vec<String> = resolved_ids.iter().map(|id| id.qualified()).collect();
646
647        let opts = LogQuery {
648            daemon_ids,
649            from,
650            to,
651            limit: self.query_limit(has_time_filter, jq_filter.is_some()),
652            order_desc: !has_time_filter,
653            after_id: None,
654            before_id: None,
655            message_filters,
656            field_filters,
657            include_structured: jq_filter.is_some() || !self.raw,
658        };
659        let mut entries = self.query_entries(opts, jq_filter, has_time_filter)?;
660
661        // Apply time-filter take-last-N or reverse for chronological display.
662        if has_time_filter {
663            if let Some(n) = self.n {
664                let len = entries.len();
665                if len > n {
666                    entries = entries.split_off(len - n);
667                }
668            }
669        } else {
670            entries.reverse();
671        }
672
673        if entries.is_empty() {
674            return Ok(());
675        }
676
677        let strip_ansi = self.raw || !console::colors_enabled();
678        let use_pager = !self.tail && !self.no_pager && should_use_pager(entries.len());
679        let ts_format = &settings().logs.timestamp_format;
680
681        // Reusable buffer for timestamp formatting — avoids N allocations.
682        let mut date_buf = String::with_capacity(ts_format.len() + 6);
683
684        let mut write_entries = |w: &mut dyn Write| -> io::Result<()> {
685            for entry in &entries {
686                date_buf.clear();
687                write!(date_buf, "{}", entry.timestamp.format(ts_format))
688                    .map_err(io::Error::other)?;
689                write_formatted_log(
690                    w,
691                    entry,
692                    &date_buf,
693                    single_daemon,
694                    strip_ansi,
695                    show_timestamp,
696                    self.raw,
697                )?;
698            }
699            Ok(())
700        };
701
702        if use_pager {
703            let pager_config = PagerConfig::new(!has_time_filter);
704            match pager_config.spawn_piped() {
705                Ok(mut child) => {
706                    if let Some(stdin) = child.stdin.as_mut() {
707                        if let Err(e) = write_entries(stdin) {
708                            debug!("pager write error: {e}");
709                        }
710                        let _ = child.wait();
711                    } else {
712                        debug!("Failed to get pager stdin, falling back to direct output");
713                        let stdout = io::stdout();
714                        let mut buf = io::BufWriter::new(stdout.lock());
715                        write_entries(&mut buf).into_diagnostic()?;
716                    }
717                }
718                Err(e) => {
719                    debug!("Failed to spawn pager: {e}, falling back to direct output");
720                    let stdout = io::stdout();
721                    let mut buf = io::BufWriter::new(stdout.lock());
722                    write_entries(&mut buf).into_diagnostic()?;
723                }
724            }
725        } else {
726            let stdout = io::stdout();
727            let mut buf = io::BufWriter::new(stdout.lock());
728            write_entries(&mut buf).into_diagnostic()?;
729        }
730
731        Ok(())
732    }
733
734    fn output_json(
735        &self,
736        resolved_ids: &[DaemonId],
737        from: Option<DateTime<Local>>,
738        to: Option<DateTime<Local>>,
739        message_filters: Vec<MessageFilter>,
740        field_filters: Vec<FieldFilter>,
741        jq_filter: Option<&crate::log_jq::JqFilter>,
742    ) -> Result<()> {
743        let daemon_ids: Vec<String> = resolved_ids.iter().map(|id| id.qualified()).collect();
744        let has_time_filter = from.is_some() || to.is_some();
745
746        let opts = LogQuery {
747            daemon_ids,
748            from,
749            to,
750            limit: self.query_limit(has_time_filter, jq_filter.is_some()),
751            order_desc: !has_time_filter,
752            after_id: None,
753            before_id: None,
754            message_filters,
755            field_filters,
756            include_structured: true,
757        };
758        let entries = self.query_entries(opts, jq_filter, has_time_filter)?;
759
760        // Reverse only when the SQL query returned DESC (no time filter),
761        // to produce chronological (oldest-first) output. With a time
762        // filter, the query is ASC and already chronological.
763        let mut entries: Vec<_> = if has_time_filter {
764            entries
765        } else {
766            entries.into_iter().rev().collect()
767        };
768
769        // When a time filter is active, the SQL query returned all matching
770        // entries without LIMIT. Trim to the last N here.
771        if has_time_filter
772            && let Some(n) = self.n
773            && entries.len() > n
774        {
775            entries = entries.split_off(entries.len() - n);
776        }
777
778        let json_entries: Vec<JsonLogEntry> = entries.into_iter().map(Into::into).collect();
779
780        print_json(&json_entries)
781    }
782}
783
784/// The smallest window of newest rows [`last_matches`] reads.
785const MIN_MATCH_WINDOW: usize = 1000;
786
787/// The last `n` rows that `filter` keeps, newest first, reading no more of
788/// the history than needed: `fetch(window)` returns the newest `window` rows,
789/// and the window doubles until it holds `n` matches or all the rows.
790///
791/// Each read starts again from the newest row rather than paging on, so the
792/// rows keep exactly the order the query gives them.
793fn last_matches<T>(
794    n: usize,
795    mut fetch: impl FnMut(usize) -> Result<Vec<T>>,
796    filter: impl Fn(Vec<T>) -> Vec<T>,
797) -> Result<Vec<T>> {
798    let mut window = n.max(MIN_MATCH_WINDOW);
799    loop {
800        let rows = fetch(window)?;
801        let exhausted = rows.len() < window;
802        let mut matches = filter(rows);
803        if matches.len() >= n || exhausted {
804            matches.truncate(n);
805            return Ok(matches);
806        }
807        window = window.saturating_mul(2);
808    }
809}
810
811fn should_use_pager(line_count: usize) -> bool {
812    if !io::stdout().is_terminal() {
813        return false;
814    }
815
816    let terminal_height = get_terminal_height().unwrap_or(24);
817    line_count > terminal_height
818}
819
820fn get_terminal_height() -> Option<usize> {
821    if let Ok(rows) = std::env::var("LINES")
822        && let Ok(h) = rows.parse::<usize>()
823    {
824        return Some(h);
825    }
826
827    crossterm::terminal::size().ok().map(|(_, h)| h as usize)
828}
829
830/// Rename legacy log directories that predate namespace-qualified daemon IDs.
831///
832/// Old layout: `PITCHFORK_LOGS_DIR/<name>/<name>.log`
833/// New layout: `PITCHFORK_LOGS_DIR/legacy--<name>/legacy--<name>.log`
834///
835/// Only directories that clearly match the old layout are migrated:
836/// - directory name does not contain `"--"`
837/// - directory contains `<name>.log`
838/// - `<name>` is a valid daemon short name under current DaemonId rules
839fn migrate_legacy_log_dirs() {
840    let known_safe_paths = known_daemon_safe_paths();
841    let dirs = match xx::file::ls(&*env::PITCHFORK_LOGS_DIR) {
842        Ok(d) => d,
843        Err(_) => return,
844    };
845    for dir in dirs {
846        if dir.starts_with(".") || !dir.is_dir() {
847            continue;
848        }
849        let name = match dir.file_name().map(|f| f.to_string_lossy().to_string()) {
850            Some(n) => n,
851            None => continue,
852        };
853        // Skip the supervisor's own log directory.
854        if name == "pitchfork" {
855            continue;
856        }
857        // New-format directories usually contain "--". For safety, only treat
858        // them as new-format if they match a known daemon ID safe-path.
859        if name.contains("--") {
860            // If it parses as a valid safe-path, treat it as already migrated
861            // and keep idempotent behavior silent.
862            if DaemonId::from_safe_path(&name).is_ok() {
863                continue;
864            }
865            // Keep noisy warnings only for invalid/ambiguous names that cannot
866            // be interpreted as new-format IDs.
867            if known_safe_paths.contains(&name) {
868                continue;
869            }
870            warn!(
871                "Skipping invalid legacy log directory '{name}': contains '--' but is not a valid daemon safe-path"
872            );
873            continue;
874        }
875
876        // Migrate only explicit old-layout directories to avoid renaming
877        // unrelated folders under logs/.
878        let old_log = dir.join(format!("{name}.log"));
879        if !old_log.exists() {
880            continue;
881        }
882        if DaemonId::try_new("legacy", &name).is_err() {
883            warn!("Skipping invalid legacy log directory '{name}': not a valid daemon ID");
884            continue;
885        }
886
887        let new_name = format!("legacy--{name}");
888        let new_dir = env::PITCHFORK_LOGS_DIR.join(&new_name);
889        // Skip if a target directory already exists to avoid clobbering data.
890        if new_dir.exists() {
891            continue;
892        }
893        if std::fs::rename(&dir, &new_dir).is_err() {
894            continue;
895        }
896        // Also rename the log file inside the directory.
897        let old_log = new_dir.join(format!("{name}.log"));
898        let new_log = new_dir.join(format!("{new_name}.log"));
899        if old_log.exists() {
900            let _ = std::fs::rename(&old_log, &new_log);
901        }
902        debug!("Migrated legacy log dir '{name}' → '{new_name}'");
903    }
904}
905
906fn known_daemon_safe_paths() -> BTreeSet<String> {
907    let mut out = BTreeSet::new();
908
909    match StateFile::read(&*env::PITCHFORK_STATE_FILE) {
910        Ok(state) => {
911            for id in state.daemons.keys() {
912                out.insert(id.safe_path());
913            }
914        }
915        Err(e) => {
916            warn!("Failed to read state while checking known daemon IDs: {e}");
917        }
918    }
919
920    match PitchforkToml::all_merged() {
921        Ok(config) => {
922            for id in config.daemons.keys() {
923                out.insert(id.safe_path());
924            }
925        }
926        Err(e) => {
927            warn!("Failed to read config while checking known daemon IDs: {e}");
928        }
929    }
930
931    out
932}
933
934fn get_all_daemon_ids() -> Result<Vec<DaemonId>> {
935    let mut ids = BTreeSet::new();
936
937    match StateFile::read(&*env::PITCHFORK_STATE_FILE) {
938        Ok(state) => ids.extend(state.daemons.keys().cloned()),
939        Err(e) => warn!("Failed to read state for log daemon discovery: {e}"),
940    }
941
942    match PitchforkToml::all_merged() {
943        Ok(config) => ids.extend(config.daemons.keys().cloned()),
944        Err(e) => warn!("Failed to read config for log daemon discovery: {e}"),
945    }
946
947    let logged_ids: std::collections::HashSet<String> =
948        LOG_STORE.list_daemon_ids()?.into_iter().collect();
949    Ok(ids
950        .into_iter()
951        .filter(|id| logged_ids.contains(&id.qualified()))
952        .collect())
953}
954
955#[allow(clippy::too_many_arguments)]
956pub async fn tail_logs(
957    names: &[DaemonId],
958    single_daemon: bool,
959    start_from_end: bool,
960    message_filters: Vec<MessageFilter>,
961    field_filters: Vec<FieldFilter>,
962    jq_filter: Option<&crate::log_jq::JqFilter>,
963    show_timestamp: bool,
964    raw: bool,
965) -> Result<()> {
966    // Poll SQLite log store for new entries since last known row id.
967    let strip_ansi = raw || !console::colors_enabled();
968
969    let mut states: std::collections::HashMap<String, i64> = names
970        .iter()
971        .map(|id| {
972            let since = if start_from_end {
973                // Anchor to the last entry overall, not the last filtered entry,
974                // so --tail combined with a filter does not rescan from row 1
975                // on every poll when no message matches yet.
976                LOG_STORE.last_id(id).unwrap_or(None).unwrap_or(0)
977            } else {
978                0
979            };
980            (id.qualified(), since)
981        })
982        .collect();
983
984    let interval = tokio::time::interval(Duration::from_millis(200));
985    tokio::pin!(interval);
986
987    loop {
988        interval.tick().await;
989
990        let mut out = vec![];
991        for id in names {
992            let after_id = states.get(&id.qualified()).copied();
993            match LOG_STORE.query(&LogQuery {
994                daemon_ids: vec![id.qualified()],
995                from: None,
996                to: None,
997                limit: None,
998                order_desc: false,
999                after_id,
1000                before_id: None,
1001                message_filters: message_filters.clone(),
1002                field_filters: field_filters.clone(),
1003                include_structured: jq_filter.is_some() || !raw,
1004            }) {
1005                Ok(raw_entries) => {
1006                    // Save the max id from SQL results (before jq filtering)
1007                    // so the cursor always advances past evaluated rows, even
1008                    // when jq rejects all of them.
1009                    let last_raw_id = raw_entries.last().map(|e| e.id);
1010
1011                    // Apply jq filter if present.
1012                    let entries = match jq_filter {
1013                        Some(jq) => jq.filter(raw_entries),
1014                        None => raw_entries,
1015                    };
1016                    out.extend(entries);
1017                    // Advance the cursor past rows already evaluated.
1018                    //
1019                    // Use the max id from the raw SQL result (not the jq-filtered
1020                    // subset) so the cursor advances past all rows the database
1021                    // returned, preventing re-evaluation on every poll.
1022                    //
1023                    // When the filter is active and no entries matched, fall
1024                    // back to last_id to advance past non-matching rows so they
1025                    // are not re-evaluated on every poll. The narrow race here
1026                    // (a matching row written between query and last_id) is
1027                    // accepted as the cost of bounded re-scanning.
1028                    let has_sql_filter = !message_filters.is_empty() || !field_filters.is_empty();
1029                    let new_cursor = if let Some(id) = last_raw_id {
1030                        Some(id)
1031                    } else if has_sql_filter || jq_filter.is_some() {
1032                        LOG_STORE.last_id(id).ok().flatten()
1033                    } else {
1034                        None
1035                    };
1036                    if let Some(last_id) = new_cursor {
1037                        states.insert(id.qualified(), last_id);
1038                    }
1039                }
1040                Err(e) => {
1041                    error!("Failed to tail logs for {}: {e}", id.qualified());
1042                }
1043            }
1044        }
1045
1046        if !out.is_empty() {
1047            // Single-daemon: entries are already in chronological order from
1048            // the SQL query (order_desc: false). Skip the sort.
1049            let out: Vec<LogEntry> = if single_daemon {
1050                out
1051            } else {
1052                out.into_iter()
1053                    .sorted_by(|a, b| a.timestamp.cmp(&b.timestamp).then(a.id.cmp(&b.id)))
1054                    .collect()
1055            };
1056            let stdout = io::stdout();
1057            let mut buf = io::BufWriter::new(stdout.lock());
1058            let ts_format = &settings().logs.timestamp_format;
1059            let mut date_buf = String::with_capacity(ts_format.len() + 6);
1060            for entry in &out {
1061                date_buf.clear();
1062                write!(date_buf, "{}", entry.timestamp.format(ts_format))
1063                    .map_err(io::Error::other)
1064                    .into_diagnostic()?;
1065                write_formatted_log(
1066                    &mut buf,
1067                    entry,
1068                    &date_buf,
1069                    single_daemon,
1070                    strip_ansi,
1071                    show_timestamp,
1072                    raw,
1073                )
1074                .into_diagnostic()?;
1075            }
1076        }
1077    }
1078}
1079
1080fn parse_datetime(s: &str) -> Result<DateTime<Local>> {
1081    let naive_dt = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").into_diagnostic()?;
1082    Local
1083        .from_local_datetime(&naive_dt)
1084        .single()
1085        .ok_or_else(|| miette::miette!("Invalid or ambiguous datetime: '{}'. ", s))
1086}
1087
1088/// Parse time input string into DateTime.
1089///
1090/// `is_since` indicates whether this is for --since (true) or --until (false).
1091/// The "yesterday fallback" only applies to --since: if the time is in the future,
1092/// assume the user meant yesterday. For --until, future times are kept as-is.
1093fn parse_time_input(s: &str, is_since: bool) -> Result<DateTime<Local>> {
1094    let s = s.trim();
1095
1096    // Try full datetime first (YYYY-MM-DD HH:MM:SS)
1097    if let Ok(dt) = parse_datetime(s) {
1098        return Ok(dt);
1099    }
1100
1101    // Try datetime without seconds (YYYY-MM-DD HH:MM)
1102    if let Ok(naive_dt) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M") {
1103        return Local
1104            .from_local_datetime(&naive_dt)
1105            .single()
1106            .ok_or_else(|| miette::miette!("Invalid or ambiguous datetime: '{}'", s));
1107    }
1108
1109    // Try time-only format (HH:MM:SS or HH:MM)
1110    // Note: This branch won't be reached for inputs like "10:30" that could match
1111    // parse_datetime, because parse_datetime expects a full date prefix and will fail.
1112    if let Ok(time) = parse_time_only(s) {
1113        let now = Local::now();
1114        let today = now.date_naive();
1115        let mut naive_dt = NaiveDateTime::new(today, time);
1116        let mut dt = Local
1117            .from_local_datetime(&naive_dt)
1118            .single()
1119            .ok_or_else(|| miette::miette!("Invalid or ambiguous datetime: '{}'", s))?;
1120
1121        // If the interpreted time for today is in the future, assume the user meant yesterday
1122        // BUT only for --since. For --until, a future time today is valid.
1123        if is_since
1124            && dt > now
1125            && let Some(yesterday) = today.pred_opt()
1126        {
1127            naive_dt = NaiveDateTime::new(yesterday, time);
1128            dt = Local
1129                .from_local_datetime(&naive_dt)
1130                .single()
1131                .ok_or_else(|| miette::miette!("Invalid or ambiguous datetime: '{}'", s))?;
1132        }
1133        return Ok(dt);
1134    }
1135
1136    if let Ok(duration) = humantime::parse_duration(s) {
1137        let now = Local::now();
1138        let target = now - chrono::Duration::from_std(duration).into_diagnostic()?;
1139        return Ok(target);
1140    }
1141
1142    Err(miette::miette!(
1143        "Invalid time format: '{}'. Expected formats:\n\
1144         - Full datetime: \"YYYY-MM-DD HH:MM:SS\" or \"YYYY-MM-DD HH:MM\"\n\
1145         - Time only: \"HH:MM:SS\" or \"HH:MM\" (uses today's date)\n\
1146         - Relative time: \"5min\", \"2h\", \"1d\" (e.g., last 5 minutes)",
1147        s
1148    ))
1149}
1150
1151fn parse_time_only(s: &str) -> Result<NaiveTime> {
1152    if let Ok(time) = NaiveTime::parse_from_str(s, "%H:%M:%S") {
1153        return Ok(time);
1154    }
1155
1156    if let Ok(time) = NaiveTime::parse_from_str(s, "%H:%M") {
1157        return Ok(time);
1158    }
1159
1160    Err(miette::miette!("Invalid time format: '{}'", s))
1161}
1162
1163/// Prints error log lines in a styled block matching the startup logs format.
1164///
1165/// Format:
1166/// ```text
1167///  ERROR LOGS
1168///  12:00:00 error message
1169/// ```
1170///
1171/// Timestamps use dimmed red. The tag uses white text on red background.
1172pub fn print_error_logs_block(log_lines: &[(String, String, String)]) {
1173    if log_lines.is_empty() {
1174        return;
1175    }
1176
1177    let is_tty = std::io::stderr().is_terminal();
1178    let format_msg = |msg: &str| -> String {
1179        let stripped = strip_pty_controls(msg);
1180        if is_tty {
1181            stripped
1182        } else {
1183            console::strip_ansi_codes(&stripped).to_string()
1184        }
1185    };
1186
1187    let tag = estyle(" ERROR LOGS ").white().on_red();
1188    eprintln!("\n{tag}");
1189
1190    // Determine if we need to show daemon IDs (same logic as startup logs)
1191    let unique_ids: BTreeSet<&str> = log_lines.iter().map(|(_, id, _)| id.as_str()).collect();
1192    let show_id = unique_ids.len() > 1;
1193
1194    if show_id {
1195        for (date, id, msg) in log_lines {
1196            let time = date.split(' ').nth(1).unwrap_or(date);
1197            let colored = colored_id_label(id, is_tty && console::colors_enabled_stderr());
1198            eprintln!(
1199                "{} {} {}",
1200                estyle(time).red().dim(),
1201                colored,
1202                format_msg(msg)
1203            );
1204        }
1205    } else {
1206        for (date, _, msg) in log_lines {
1207            let time = date.split(' ').nth(1).unwrap_or(date);
1208            eprintln!("{} {}", estyle(time).red().dim(), format_msg(msg));
1209        }
1210    }
1211}
1212
1213/// Describes the type of ready check being performed for display purposes.
1214pub enum ReadyCheckType {
1215    Output(String),
1216    Http(String),
1217    Port(u16),
1218    Cmd(String),
1219    Delay(u64),
1220    /// A `oneshot` daemon: ready when the process exits 0.
1221    Completion,
1222    Default,
1223}
1224
1225impl std::fmt::Display for ReadyCheckType {
1226    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1227        match self {
1228            ReadyCheckType::Output(pattern) => write!(f, "output matching '{pattern}'"),
1229            ReadyCheckType::Http(url) => write!(f, "HTTP {url}"),
1230            ReadyCheckType::Port(port) => write!(f, "TCP port {port}"),
1231            ReadyCheckType::Cmd(cmd) => write!(f, "command '{cmd}'"),
1232            ReadyCheckType::Delay(secs) => write!(f, "delay ({secs}s)"),
1233            ReadyCheckType::Completion => write!(f, "completion"),
1234            ReadyCheckType::Default => write!(f, "default readiness check"),
1235        }
1236    }
1237}
1238
1239/// How long a ready check must run before its spinner is shown.
1240///
1241/// Daemons that are ready right away (e.g. `ready_delay = 0`) never flash a
1242/// spinner, which matters when output lands in a new shell's prompt.
1243const READY_SPINNER_DELAY: Duration = Duration::from_millis(400);
1244
1245/// Whether a ready-check spinner that is still hidden should now appear.
1246fn spinner_due(elapsed: Duration) -> bool {
1247    elapsed >= READY_SPINNER_DELAY
1248}
1249
1250/// Starts the spinner of a hidden ready-check job once the threshold has passed.
1251fn reveal_spinner_if_due(
1252    job: &clx::progress::ProgressJob,
1253    started: std::time::Instant,
1254    revealed: &mut bool,
1255) {
1256    if !*revealed && spinner_due(started.elapsed()) {
1257        *revealed = true;
1258        job.set_status(clx::progress::ProgressStatus::Running);
1259    }
1260}
1261
1262/// Creates a progress job for a ready check.
1263///
1264/// The job starts hidden; [`stream_startup_logs`] reveals the spinner once the
1265/// check has run for [`READY_SPINNER_DELAY`]. Returns a `Arc<ProgressJob>` that the caller should update:
1266/// - Set body to success message and status to `Done` when the daemon is ready
1267/// - Set body to failure message and status to `Failed` when the daemon fails
1268pub fn create_ready_check_job(
1269    daemon_id: &DaemonId,
1270    check_type: &ReadyCheckType,
1271) -> std::sync::Arc<clx::progress::ProgressJob> {
1272    use clx::progress::{ProgressJobBuilder, ProgressJobDoneBehavior, ProgressStatus};
1273
1274    let is_tty = std::io::stderr().is_terminal();
1275    let colors_enabled = is_tty && console::colors_enabled_stderr();
1276    let id_label = colored_id_label(&daemon_id.qualified(), colors_enabled);
1277    let show_ts = crate::settings::settings().general.startup_log_timestamps;
1278
1279    // When timestamps are off, {{spinner()}} renders as an animated spinner
1280    // (1 char wide) matching the "•" prefix used by println.  When on,
1281    // we show a dim timestamp instead.
1282    let prefix = if show_ts {
1283        // The timestamp updates each refresh via the now() tera function.
1284        // We use a fixed-width format (HH:MM:SS = 8 chars) for alignment.
1285        edim(chrono::Local::now().format("%H:%M:%S").to_string()).to_string()
1286    } else {
1287        "{{spinner()}}".to_string()
1288    };
1289
1290    ProgressJobBuilder::new()
1291        .body(format!(
1292            "{} pitchfork: {} waiting for {{{{ check_type }}}}...",
1293            prefix, id_label
1294        ))
1295        .prop("check_type", &check_type.to_string())
1296        .status(ProgressStatus::Hide)
1297        .on_done(ProgressJobDoneBehavior::Keep)
1298        .start()
1299}
1300
1301/// Collects startup log lines for a single daemon (does not print).
1302///
1303/// Returns a list of `(time, daemon_id_qualified, message)` tuples for log
1304/// entries written after `from`.
1305pub fn collect_startup_logs(
1306    daemon_id: &DaemonId,
1307    from: DateTime<Local>,
1308) -> Result<Vec<(String, String, String)>> {
1309    let entries = LOG_STORE.query(&LogQuery {
1310        daemon_ids: vec![daemon_id.qualified()],
1311        from: Some(from),
1312        to: None,
1313        limit: None,
1314        order_desc: false,
1315        after_id: None,
1316        before_id: None,
1317        message_filters: Vec::new(),
1318        field_filters: Vec::new(),
1319        include_structured: false,
1320    })?;
1321    let log_lines = entries
1322        .into_iter()
1323        .map(|e| {
1324            let ts = e.timestamp.format("%Y-%m-%d %H:%M:%S").to_string();
1325            (ts, e.daemon_id, e.message)
1326        })
1327        .collect();
1328
1329    Ok(log_lines)
1330}
1331
1332/// Stream startup logs for a daemon to a progress job in real-time.
1333///
1334/// Spawns a background tokio task that polls the daemon's log store
1335/// and calls `job.println()` for each new line. Returns a watch sender
1336/// that stops the streaming when sent `true`.
1337pub fn stream_startup_logs(
1338    daemon_id: &DaemonId,
1339    job: std::sync::Arc<clx::progress::ProgressJob>,
1340) -> (
1341    tokio::sync::watch::Sender<bool>,
1342    tokio::task::JoinHandle<()>,
1343) {
1344    let (tx, mut rx) = tokio::sync::watch::channel(false);
1345    let id = daemon_id.clone();
1346
1347    let show_ts = crate::settings::settings().general.startup_log_timestamps;
1348
1349    // Anchor to the daemon's current max log id *synchronously* before
1350    // spawning the streaming task. This must happen before ipc.run() starts
1351    // the daemon, otherwise early output could be written to the log store
1352    // before the anchor is established and get skipped as "already seen".
1353    let anchor_id: i64 = LOG_STORE
1354        .query(&LogQuery {
1355            daemon_ids: vec![id.qualified()],
1356            limit: Some(1),
1357            order_desc: true,
1358            ..Default::default()
1359        })
1360        .ok()
1361        .and_then(|entries| entries.last().map(|e| e.id))
1362        .unwrap_or(0);
1363
1364    let started = std::time::Instant::now();
1365    let handle = tokio::spawn(async move {
1366        let mut revealed = false;
1367        let is_tty = std::io::stderr().is_terminal();
1368        let colors_enabled = is_tty && console::colors_enabled_stderr();
1369        let id_label = colored_id_label(&id.qualified(), colors_enabled);
1370        let prefix = if show_ts {
1371            String::new()
1372        } else {
1373            edim("•").to_string()
1374        };
1375
1376        let mut last_id = anchor_id;
1377
1378        // Initial fetch: catch any logs already written since the anchor.
1379        if let Ok(entries) = LOG_STORE.tail(&id, Some(last_id)) {
1380            for entry in &entries {
1381                let time = entry.timestamp.format("%H:%M:%S").to_string();
1382                let msg = strip_pty_controls(&entry.message);
1383                let msg = if is_tty {
1384                    msg
1385                } else {
1386                    console::strip_ansi_codes(&msg).to_string()
1387                };
1388                let line_prefix = if show_ts {
1389                    edim(time).to_string()
1390                } else {
1391                    prefix.clone()
1392                };
1393                job.println(&format!("{} {} {}", line_prefix, id_label, msg));
1394            }
1395            if let Some(last) = entries.last() {
1396                last_id = last.id;
1397            }
1398        }
1399
1400        loop {
1401            tokio::select! {
1402                _ = tokio::time::sleep(Duration::from_millis(200)) => {
1403                    reveal_spinner_if_due(&job, started, &mut revealed);
1404                    if let Ok(entries) = LOG_STORE.tail(&id, Some(last_id)) {
1405                        for entry in &entries {
1406                            let time = entry.timestamp.format("%H:%M:%S").to_string();
1407                            let msg = strip_pty_controls(&entry.message);
1408                            let msg = if is_tty {
1409                                msg
1410                            } else {
1411                                console::strip_ansi_codes(&msg).to_string()
1412                            };
1413                            let line_prefix = if show_ts {
1414                                edim(time).to_string()
1415                            } else {
1416                                prefix.clone()
1417                            };
1418                            job.println(&format!("{} {} {}", line_prefix, id_label, msg));
1419                        }
1420                        if let Some(last) = entries.last() {
1421                            last_id = last.id;
1422                        }
1423                    }
1424                }
1425                _ = rx.changed() => {
1426                    break;
1427                }
1428            }
1429        }
1430
1431        // Final drain
1432        if let Ok(entries) = LOG_STORE.tail(&id, Some(last_id)) {
1433            for entry in &entries {
1434                let time = entry.timestamp.format("%H:%M:%S").to_string();
1435                let msg = strip_pty_controls(&entry.message);
1436                let msg = if is_tty {
1437                    msg
1438                } else {
1439                    console::strip_ansi_codes(&msg).to_string()
1440                };
1441                let line_prefix = if show_ts {
1442                    edim(time).to_string()
1443                } else {
1444                    prefix.clone()
1445                };
1446                job.println(&format!("{} {} {}", line_prefix, id_label, msg));
1447            }
1448        }
1449    });
1450
1451    (tx, handle)
1452}
1453
1454/// Strips PTY control sequences from a string while preserving SGR (color/style) codes.
1455///
1456/// Removes CSI sequences that control cursor movement, screen clearing, erasing, etc.,
1457/// but keeps `\x1b[...m` (SGR) sequences so colors are retained.
1458fn strip_pty_controls(s: &str) -> String {
1459    struct Stripper {
1460        result: String,
1461    }
1462
1463    impl vte::Perform for Stripper {
1464        fn print(&mut self, c: char) {
1465            self.result.push(c);
1466        }
1467
1468        fn execute(&mut self, byte: u8) {
1469            // Keep \n and \t; drop other control characters (BEL, BS, CR, etc.)
1470            if byte == b'\n' || byte == b'\t' {
1471                self.result.push(byte as char);
1472            }
1473        }
1474
1475        fn csi_dispatch(
1476            &mut self,
1477            params: &vte::Params,
1478            _intermediates: &[u8],
1479            _ignore: bool,
1480            action: char,
1481        ) {
1482            // Keep SGR sequences (final byte 'm')
1483            if action == 'm' {
1484                self.result.push_str("\x1b[");
1485                let mut first = true;
1486                for sub in params.iter() {
1487                    if !first {
1488                        self.result.push(';');
1489                    }
1490                    first = false;
1491                    for (i, &p) in sub.iter().enumerate() {
1492                        if i > 0 {
1493                            self.result.push(':');
1494                        }
1495                        self.result.push_str(&p.to_string());
1496                    }
1497                }
1498                self.result.push('m');
1499            }
1500            // All other CSI sequences (cursor move, clear, erase, etc.) are dropped
1501        }
1502
1503        fn osc_dispatch(&mut self, _params: &[&[u8]], _bell_terminated: bool) {
1504            // Drop OSC sequences (e.g. window title)
1505        }
1506
1507        fn esc_dispatch(&mut self, _intermediates: &[u8], _ignore: bool, _byte: u8) {
1508            // Drop ESC sequences (e.g. ESC c = reset terminal)
1509        }
1510
1511        fn hook(
1512            &mut self,
1513            _params: &vte::Params,
1514            _intermediates: &[u8],
1515            _ignore: bool,
1516            _action: char,
1517        ) {
1518            // Drop DCS hooks
1519        }
1520
1521        fn put(&mut self, _byte: u8) {
1522            // Drop DCS data
1523        }
1524
1525        fn unhook(&mut self) {
1526            // Drop DCS unhook
1527        }
1528    }
1529
1530    let mut parser = vte::Parser::new();
1531    let mut stripper = Stripper {
1532        result: String::with_capacity(s.len()),
1533    };
1534    parser.advance(&mut stripper, s.as_bytes());
1535    stripper.result
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    use super::*;
1541
1542    #[test]
1543    fn spinner_waits_for_threshold() {
1544        assert!(!spinner_due(Duration::ZERO));
1545        assert!(!spinner_due(READY_SPINNER_DELAY - Duration::from_millis(1)));
1546        assert!(spinner_due(READY_SPINNER_DELAY));
1547    }
1548
1549    #[test]
1550    fn ready_spinner_starts_hidden_and_reveals_after_threshold() {
1551        let id = DaemonId::new("spinner-test", "ready-check");
1552        let job = create_ready_check_job(&id, &ReadyCheckType::Delay(0));
1553        assert!(!job.is_running(), "job must start hidden");
1554
1555        let mut revealed = false;
1556        let now = std::time::Instant::now();
1557        reveal_spinner_if_due(&job, now, &mut revealed);
1558        assert!(
1559            !revealed && !job.is_running(),
1560            "hidden before the threshold"
1561        );
1562
1563        let past = now - READY_SPINNER_DELAY;
1564        reveal_spinner_if_due(&job, past, &mut revealed);
1565        assert!(revealed && job.is_running(), "visible after the threshold");
1566        job.remove();
1567    }
1568
1569    /// Newest first, as the query returns them: row `i` is the `i`-th newest.
1570    fn fetch_from(rows: &[u32], reads: &mut Vec<usize>) -> impl FnMut(usize) -> Result<Vec<u32>> {
1571        move |window| {
1572            reads.push(window);
1573            Ok(rows.iter().copied().take(window).collect())
1574        }
1575    }
1576
1577    #[test]
1578    fn last_matches_reads_one_window_when_the_newest_rows_match() {
1579        let rows: Vec<u32> = (0..100_000).collect();
1580        let mut reads = Vec::new();
1581        let found = last_matches(2, fetch_from(&rows, &mut reads), |r| {
1582            r.into_iter().filter(|i| i % 10 == 0).collect()
1583        })
1584        .unwrap();
1585        assert_eq!(found, vec![0, 10]);
1586        assert_eq!(reads, vec![MIN_MATCH_WINDOW]);
1587    }
1588
1589    #[test]
1590    fn last_matches_widens_the_window_until_it_holds_n_matches() {
1591        let rows: Vec<u32> = (0..100_000).collect();
1592        let mut reads = Vec::new();
1593        let found = last_matches(2, fetch_from(&rows, &mut reads), |r| {
1594            r.into_iter().filter(|i| *i >= 3000).collect()
1595        })
1596        .unwrap();
1597        assert_eq!(found, vec![3000, 3001]);
1598        assert_eq!(reads, vec![1000, 2000, 4000]);
1599    }
1600
1601    #[test]
1602    fn last_matches_stops_once_every_row_is_read() {
1603        let rows: Vec<u32> = (0..2500).collect();
1604        let mut reads = Vec::new();
1605        let found = last_matches(5, fetch_from(&rows, &mut reads), |r| {
1606            r.into_iter().filter(|i| *i == 2400).collect()
1607        })
1608        .unwrap();
1609        assert_eq!(found, vec![2400]);
1610        assert_eq!(reads, vec![1000, 2000, 4000]);
1611    }
1612}