croft-software 0.2.232

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! In-process OUTPUT bus: the data behind the panel group's OUTPUT tab, a
//! read-only VS Code-style log viewer with a channel dropdown. Log call sites
//! across croft push levelled lines into named channels (one per language
//! server, plus Debug Adapter, Git, and Server Provisioning); the OUTPUT widget
//! renders the selected channel's tail. Mirrors VS Code's
//! `window.createOutputChannel` model, where each producer owns a channel, and
//! Zed's per-language-server log view with its RPC-messages toggle.
//!
//! This is a sibling of the always-on `lsp::log_file` disk log: producers
//! mirror to both, so the on-disk log keeps working while the UI gets a live,
//! per-channel, in-memory view with no file polling.

use std::collections::{BTreeMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};

/// VS Code `LogOutputChannel` severity. Drives the row colour and the optional
/// minimum-level filter; ordered low to high so `level >= min` is a cheap
/// compare.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum OutputLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

impl OutputLevel {
    /// Short tag rendered before the message, matching VS Code's `[info]` style.
    pub fn label(self) -> &'static str {
        match self {
            Self::Trace => "trace",
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warn => "warn",
            Self::Error => "error",
        }
    }
}

/// Well-known channel names for the non-LSP producers. Language servers each
/// own a channel named after the server (`ty`, `rust-analyzer`, ...), so they
/// need no constant here.
pub const CHANNEL_DAP: &str = "Debug Adapter";
pub const CHANNEL_GIT: &str = "Git";
pub const CHANNEL_PROVISION: &str = "Server Provisioning";
pub const CHANNEL_TESTS: &str = "Test Runner";
/// Every status-bar message, in full (#1609): the bar may have to cut one
/// to fit, and a click on it opens this channel.
pub const CHANNEL_MESSAGES: &str = "Messages";
/// Fleet run results, one line per host plus the summary (#363).
pub const CHANNEL_FLEET: &str = "Fleet";
/// Remote provisioning: which hosts got croft installed, and why an install
/// failed (#364).
pub const CHANNEL_REMOTE: &str = "Remote";
/// Notification-sink delivery failures (#358).
pub const CHANNEL_NOTIFICATIONS: &str = "Notifications";
/// The Run and Debug panel's console, mirrored (#867): program output and
/// REPL results at full width, searchable and copyable, where the sidebar
/// shows only a narrow tail.
pub const CHANNEL_DEBUG_CONSOLE: &str = "Debug Console";

/// One line in a channel: when it arrived, how severe, and the text.
#[derive(Clone, Debug, PartialEq)]
pub struct OutputLine {
    pub ts: f64,
    pub level: OutputLevel,
    pub text: String,
}

/// Per-channel ring-buffer cap. Same order of magnitude as the terminal
/// scrollback; the oldest line drops off the front so a chatty server can't
/// grow the buffer without bound.
pub const MAX_LINES: usize = 5000;

/// Per-line cap. `MAX_LINES` alone bounded the count, not the size: with RPC
/// tracing on, every JSON-RPC body is one line, and a semantic-tokens or
/// workspace-diagnostics reply can be megabytes, so 5000 of them held
/// gigabytes (#694). The rest of an over-long line is dropped with a note.
const MAX_LINE_BYTES: usize = 16 * 1024;

/// `text` cut to [`MAX_LINE_BYTES`] at a char boundary, with how much went.
fn capped_line(text: &str) -> String {
    if text.len() <= MAX_LINE_BYTES {
        return text.to_string();
    }
    let mut end = MAX_LINE_BYTES;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}… ({} more bytes)", &text[..end], text.len() - end)
}

/// One channel's lines, with a count of every line pushed into it since it
/// was created or last cleared, so a reader can take only the lines it has
/// not seen yet (#2861).
#[derive(Default)]
struct Channel {
    lines: VecDeque<OutputLine>,
    /// Lines pushed since the channel was created or last cleared, the ones
    /// trimmed off the front included.
    pushed: u64,
    /// How many times the channel was cleared, so a reader's count from
    /// before a clear is never taken for one after it.
    cleared: u64,
}

impl Channel {
    fn mark(&self) -> ReadMark {
        ReadMark {
            cleared: self.cleared,
            pushed: self.pushed,
        }
    }
}

struct Registry {
    channels: BTreeMap<String, Channel>,
}

/// How far a reader of one channel has read: the channel's counts when the
/// reader last took its lines. Opaque; only [`read_since`] makes and reads one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ReadMark {
    cleared: u64,
    pushed: u64,
}

/// What a channel holds beyond a reader's [`ReadMark`].
#[derive(Debug, PartialEq)]
pub enum Since {
    /// The lines pushed since the mark, oldest first. The reader appends them
    /// and then drops lines off its front past [`MAX_LINES`], as the channel
    /// did. Empty when nothing was pushed.
    Appended(Vec<OutputLine>),
    /// The reader's lines are no longer the front of the channel's (it was
    /// cleared, or more lines arrived than the channel keeps, or the reader
    /// had none): these are all the channel's lines, to keep instead.
    Replaced(Vec<OutputLine>),
}

fn registry() -> &'static Mutex<Registry> {
    static REG: OnceLock<Mutex<Registry>> = OnceLock::new();
    REG.get_or_init(|| {
        Mutex::new(Registry {
            channels: BTreeMap::new(),
        })
    })
}

/// Bumped on every push/clear so a renderer can skip re-pulling an unchanged
/// channel set: one relaxed load per frame instead of cloning every line.
static GENERATION: AtomicU64 = AtomicU64::new(0);

/// Whether raw JSON-RPC tracing is active (the OUTPUT panel's "RPC" toggle,
/// Zed's RPC-messages equivalent). Off by default: tracing tees every LSP
/// frame, so the hot path loads this first and skips the push when off.
static TRACE_ENABLED: AtomicBool = AtomicBool::new(false);

pub fn generation() -> u64 {
    GENERATION.load(Ordering::Relaxed)
}

pub fn trace_enabled() -> bool {
    TRACE_ENABLED.load(Ordering::Relaxed)
}

pub fn set_trace_enabled(on: bool) {
    TRACE_ENABLED.store(on, Ordering::Relaxed);
}

fn now() -> f64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs_f64())
        .unwrap_or(0.0)
}

/// Append one line to `channel`, creating the channel on first use. Drops the
/// oldest line once the channel passes `MAX_LINES`.
pub fn push(channel: &str, level: OutputLevel, text: &str) {
    let Ok(mut reg) = registry().lock() else {
        return;
    };
    let ch = reg.channels.entry(channel.to_string()).or_default();
    ch.lines.push_back(OutputLine {
        ts: now(),
        level,
        text: capped_line(text),
    });
    ch.pushed += 1;
    while ch.lines.len() > MAX_LINES {
        ch.lines.pop_front();
    }
    GENERATION.fetch_add(1, Ordering::Relaxed);
}

/// The channel names, sorted (BTreeMap order) for a stable dropdown.
pub fn channel_names() -> Vec<String> {
    registry()
        .lock()
        .map(|r| r.channels.keys().cloned().collect())
        .unwrap_or_default()
}

/// Each channel's name, line count and bytes of line text, for the memory
/// report (#694). Counts under the lock rather than cloning the lines.
pub fn channel_sizes() -> Vec<(String, usize, usize)> {
    registry()
        .lock()
        .map(|r| {
            r.channels
                .iter()
                .map(|(name, ch)| {
                    let bytes = ch.lines.iter().map(|l| l.text.len()).sum();
                    (name.clone(), ch.lines.len(), bytes)
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Clone a channel's lines for rendering. `None` if the channel doesn't exist.
pub fn snapshot(channel: &str) -> Option<Vec<OutputLine>> {
    let reg = registry().lock().ok()?;
    reg.channels
        .get(channel)
        .map(|ch| ch.lines.iter().cloned().collect())
}

/// A channel's lines beyond `mark`, with the mark that reads to its end now.
/// `None` if the channel doesn't exist. A reader that keeps the mark and
/// applies each answer holds exactly the channel's lines, and copies each
/// line once rather than the whole channel on every change (#2861): a
/// channel keeps up to [`MAX_LINES`] lines of up to 16 KB each.
pub fn read_since(channel: &str, mark: Option<ReadMark>) -> Option<(ReadMark, Since)> {
    let reg = registry().lock().ok()?;
    let ch = reg.channels.get(channel)?;
    let unseen = mark
        .filter(|m| m.cleared == ch.cleared && m.pushed <= ch.pushed)
        .map(|m| ch.pushed - m.pushed)
        .and_then(|n| usize::try_from(n).ok())
        .filter(|&n| n <= ch.lines.len());
    let since = match unseen {
        Some(n) => Since::Appended(ch.lines.range(ch.lines.len() - n..).cloned().collect()),
        None => Since::Replaced(ch.lines.iter().cloned().collect()),
    };
    Some((ch.mark(), since))
}

/// Clear one channel's lines, keeping the channel in the list (VS Code's clear
/// action). Bumps the generation so the view refreshes.
pub fn clear(channel: &str) {
    if let Ok(mut reg) = registry().lock()
        && let Some(ch) = reg.channels.get_mut(channel)
    {
        ch.lines.clear();
        ch.pushed = 0;
        ch.cleared += 1;
        GENERATION.fetch_add(1, Ordering::Relaxed);
    }
}

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

    #[test]
    fn push_creates_a_channel_and_appends_in_order() {
        let ch = "test-create-append";
        push(ch, OutputLevel::Info, "first");
        push(ch, OutputLevel::Error, "second");
        let lines = snapshot(ch).expect("channel exists after push");
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].text, "first");
        assert_eq!(lines[1].text, "second");
        assert_eq!(lines[1].level, OutputLevel::Error);
        assert!(channel_names().iter().any(|c| c == ch));
    }

    /// #694: the memory report reads each channel's line count and text
    /// bytes.
    #[test]
    fn channel_sizes_count_lines_and_text_bytes() {
        let ch = "test-channel-sizes";
        push(ch, OutputLevel::Info, "abc");
        push(ch, OutputLevel::Info, "de");
        let sizes = channel_sizes();
        let (_, lines, bytes) = sizes.iter().find(|(n, _, _)| n == ch).unwrap();
        assert_eq!((*lines, *bytes), (2, 5));
    }

    /// #694: a multi-megabyte traced JSON-RPC body is held as one capped
    /// line, cut on a char boundary, with a note of what was dropped.
    #[test]
    fn an_over_long_line_is_capped() {
        let ch = "test-line-cap";
        let body = format!(
            "{}é{}",
            "x".repeat(MAX_LINE_BYTES - 1),
            "y".repeat(3 * 1024 * 1024)
        );
        push(ch, OutputLevel::Info, &body);
        let line = &snapshot(ch).unwrap()[0].text;
        assert!(
            line.len() < MAX_LINE_BYTES + 64,
            "{} bytes held",
            line.len()
        );
        let dropped = body.len() - (MAX_LINE_BYTES - 1);
        assert!(
            line.ends_with(&format!("… ({dropped} more bytes)")),
            "{}",
            &line[line.len() - 40..]
        );
        assert!(line.starts_with(&"x".repeat(MAX_LINE_BYTES - 1)));
        push(ch, OutputLevel::Info, "short");
        assert_eq!(snapshot(ch).unwrap()[1].text, "short");
    }

    #[test]
    fn push_bumps_the_generation() {
        let before = generation();
        push("test-generation", OutputLevel::Info, "x");
        assert!(generation() > before, "a push must bump the generation");
    }

    #[test]
    fn clear_empties_a_channel_but_keeps_it_listed() {
        let ch = "test-clear";
        push(ch, OutputLevel::Info, "a");
        push(ch, OutputLevel::Info, "b");
        clear(ch);
        assert_eq!(snapshot(ch).map(|l| l.len()), Some(0));
        assert!(
            channel_names().iter().any(|c| c == ch),
            "clear keeps the channel in the dropdown",
        );
    }

    #[test]
    fn levels_order_low_to_high_for_filtering() {
        assert!(OutputLevel::Error > OutputLevel::Warn);
        assert!(OutputLevel::Warn > OutputLevel::Info);
        assert!(OutputLevel::Info > OutputLevel::Debug);
        assert!(OutputLevel::Debug > OutputLevel::Trace);
    }

    #[test]
    fn trace_toggle_round_trips() {
        set_trace_enabled(true);
        assert!(trace_enabled());
        set_trace_enabled(false);
        assert!(!trace_enabled());
    }

    fn texts(lines: &[OutputLine]) -> Vec<&str> {
        lines.iter().map(|l| l.text.as_str()).collect()
    }

    #[test]
    fn read_since_hands_a_reader_only_the_lines_it_has_not_seen() {
        let ch = "test-read-since-appends";
        push(ch, OutputLevel::Info, "one");
        push(ch, OutputLevel::Info, "two");
        let (mark, first) = read_since(ch, None).expect("channel exists");
        assert_eq!(
            first,
            Since::Replaced(snapshot(ch).unwrap()),
            "a reader with no mark takes every line"
        );
        let (same, nothing) = read_since(ch, Some(mark)).unwrap();
        assert_eq!((same, nothing), (mark, Since::Appended(Vec::new())));
        push(ch, OutputLevel::Warn, "three");
        let (_, more) = read_since(ch, Some(mark)).unwrap();
        let Since::Appended(lines) = more else {
            panic!("a push since the mark is an append: {more:?}");
        };
        assert_eq!(texts(&lines), ["three"]);
        assert!(read_since("test-read-since-no-such-channel", None).is_none());
    }

    #[test]
    fn read_since_replaces_after_a_clear_even_when_the_counts_line_up() {
        let ch = "test-read-since-clear";
        push(ch, OutputLevel::Info, "old");
        let (mark, _) = read_since(ch, None).unwrap();
        // Cleared and refilled to the same count: the reader's "old" must
        // still go, so the mark has to tell this channel from the one it read.
        clear(ch);
        push(ch, OutputLevel::Info, "new");
        let (_, after) = read_since(ch, Some(mark)).unwrap();
        let Since::Replaced(lines) = after else {
            panic!("a clear since the mark replaces: {after:?}");
        };
        assert_eq!(texts(&lines), ["new"]);
    }

    #[test]
    fn read_since_replaces_once_a_reader_falls_further_behind_than_the_cap() {
        let ch = "test-read-since-behind";
        push(ch, OutputLevel::Info, "first");
        let (mark, _) = read_since(ch, None).unwrap();
        for i in 0..MAX_LINES + 1 {
            push(ch, OutputLevel::Info, &format!("line {i}"));
        }
        let (_, after) = read_since(ch, Some(mark)).unwrap();
        let Since::Replaced(lines) = after else {
            panic!("more unseen lines than the channel keeps replaces: {after:?}");
        };
        assert_eq!(lines.len(), MAX_LINES);
        assert_eq!(lines.last().unwrap().text, format!("line {MAX_LINES}"));
    }

    #[test]
    fn a_reader_that_applies_each_answer_holds_the_channels_lines() {
        let ch = "test-read-since-mirror";
        let mut mine: Vec<OutputLine> = Vec::new();
        let mut mark = None;
        let mut step = |mine: &mut Vec<OutputLine>| {
            let (m, since) = read_since(ch, mark).unwrap();
            mark = Some(m);
            match since {
                Since::Appended(new) => mine.extend(new),
                Since::Replaced(all) => *mine = all,
            }
            let over = mine.len().saturating_sub(MAX_LINES);
            mine.drain(..over);
        };
        push(ch, OutputLevel::Info, "a");
        step(&mut mine);
        // Past the cap the channel drops lines off its front; the reader's
        // trim must drop the same ones.
        for i in 0..MAX_LINES + 7 {
            push(ch, OutputLevel::Info, &format!("n{i}"));
            if i % 1000 == 0 {
                step(&mut mine);
            }
        }
        step(&mut mine);
        assert_eq!(mine, snapshot(ch).unwrap());
        clear(ch);
        push(ch, OutputLevel::Error, "z");
        step(&mut mine);
        assert_eq!(mine, snapshot(ch).unwrap());
    }
}