muster-workspace 0.3.1

A terminal workspace for running CLI agents and dev processes side by side
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::Paragraph,
};

/// One compact key/action hint.
type Hint = (&'static str, &'static str);

/// Leader key chord shown before the terminal-mode hints.
const LEADER_LABEL: &str = " C-a ";
/// The always-present hint pointing at the full keymap overlay.
const HELP_HINT: Hint = ("?", "help");
/// Process navigation hint.
const MOVE_HINT: Hint = ("↑↓", "move");
/// Process attachment hint.
const ATTACH_HINT: Hint = ("", "attach");
/// Process start or graceful-stop hint.
const START_STOP_HINT: Hint = ("s", "start/stop");
/// Process restart hint.
const RESTART_HINT: Hint = ("r", "restart");
/// Immediate process kill hint.
const KILL_HINT: Hint = ("x", "kill");
/// Process autostart hint.
const AUTOSTART_HINT: Hint = ("t", "autostart");
/// Add-process hint.
const ADD_HINT: Hint = ("a", "add");
/// Close runtime agent-session hint.
const CLOSE_HINT: Hint = ("d", "close");
/// Reopen the most recently closed agent session.
const REOPEN_HINT: Hint = ("u", "reopen");
/// Attached terminal detach hint.
const DETACH_HINT: Hint = ("h", "detach");
/// Slim hints for a process selected in the active project.
const PROCESS_HINTS: &[Hint] = &[
    MOVE_HINT,
    ATTACH_HINT,
    START_STOP_HINT,
    RESTART_HINT,
    KILL_HINT,
    AUTOSTART_HINT,
    REOPEN_HINT,
    ADD_HINT,
];
/// Process hints in retention order when the status row is narrow.
const PROCESS_HINT_PRIORITY: &[Hint] = &[
    START_STOP_HINT,
    ADD_HINT,
    RESTART_HINT,
    KILL_HINT,
    MOVE_HINT,
    ATTACH_HINT,
    AUTOSTART_HINT,
    REOPEN_HINT,
];
/// Slim hints for a runtime agent session selected in the sidebar.
const AGENT_SESSION_HINTS: &[Hint] = &[
    MOVE_HINT,
    ATTACH_HINT,
    START_STOP_HINT,
    RESTART_HINT,
    KILL_HINT,
    CLOSE_HINT,
    REOPEN_HINT,
    ADD_HINT,
];
/// Agent-session hints in retention order when the status row is narrow.
const AGENT_SESSION_HINT_PRIORITY: &[Hint] = &[
    CLOSE_HINT,
    REOPEN_HINT,
    START_STOP_HINT,
    ADD_HINT,
    RESTART_HINT,
    KILL_HINT,
    MOVE_HINT,
    ATTACH_HINT,
];
/// Slim hints for a collapsed other-project row.
const PROJECT_HINTS: &[Hint] = &[("↑↓", "move"), ("", "open"), ("d", "remove")];
/// Slim hints for an active project that has no processes yet.
const EMPTY_HINTS: &[Hint] = &[ADD_HINT, REOPEN_HINT, ("n", "new"), ("o", "projects")];
/// Slim hints for an attached terminal; each key follows the leader chord.
const TERMINAL_HINTS: &[Hint] = &[
    DETACH_HINT,
    START_STOP_HINT,
    RESTART_HINT,
    KILL_HINT,
    REOPEN_HINT,
];
/// Terminal hints in retention order when the status row is narrow.
const TERMINAL_HINT_PRIORITY: &[Hint] = &[
    START_STOP_HINT,
    REOPEN_HINT,
    RESTART_HINT,
    KILL_HINT,
    DETACH_HINT,
];
/// Slim hints while attached to a runtime agent session.
const TERMINAL_AGENT_SESSION_HINTS: &[Hint] = &[
    DETACH_HINT,
    START_STOP_HINT,
    RESTART_HINT,
    KILL_HINT,
    CLOSE_HINT,
    REOPEN_HINT,
];
/// Attached agent-session hint retention order for narrow rows.
const TERMINAL_AGENT_SESSION_HINT_PRIORITY: &[Hint] = &[
    CLOSE_HINT,
    REOPEN_HINT,
    START_STOP_HINT,
    RESTART_HINT,
    KILL_HINT,
    DETACH_HINT,
];

/// The sidebar/terminal context the status bar advertises hints for. The full
/// keymap lives in the `?` overlay; each context shows only its slim subset.
pub enum StatusContext {
    /// A process in the active project is selected.
    Process,
    /// A runtime agent session is selected.
    AgentSession,
    /// A collapsed other-project row is selected.
    Project,
    /// The active project has no processes.
    Empty,
    /// A terminal pane is attached.
    Terminal,
    /// A runtime agent session's terminal is attached.
    TerminalAgentSession,
}

impl StatusContext {
    /// This context's slim hint set, excluding the always-present help hint.
    fn hints(&self, available_width: u16) -> Vec<Hint> {
        match self {
            Self::Process => process_hints(available_width),
            Self::AgentSession => prioritized_hints(
                AGENT_SESSION_HINTS,
                AGENT_SESSION_HINT_PRIORITY,
                available_width,
            ),
            Self::Project => PROJECT_HINTS.to_vec(),
            Self::Empty => EMPTY_HINTS.to_vec(),
            Self::Terminal => {
                prioritized_hints(TERMINAL_HINTS, TERMINAL_HINT_PRIORITY, available_width)
            },
            Self::TerminalAgentSession => prioritized_hints(
                TERMINAL_AGENT_SESSION_HINTS,
                TERMINAL_AGENT_SESSION_HINT_PRIORITY,
                available_width,
            ),
        }
    }
}

/// Color of key chords.
const KEY_COLOR: Color = Color::Cyan;
/// Color of descriptive labels.
const LABEL_COLOR: Color = Color::DarkGray;
/// Background of the status row while the terminal leader chord is pending.
const LEADER_PENDING_BACKGROUND: Color = Color::Cyan;
/// Foreground of the status row while the terminal leader chord is pending.
const LEADER_PENDING_FOREGROUND: Color = Color::Black;
/// Trailing spaces after each hint label for separation.
const HINT_GAP: &str = "   ";
/// Color of the crashed-process alert.
const ALERT_COLOR: Color = Color::Red;
/// Glyph preceding the crashed-process count.
const ALERT_GLYPH: &str = "";

/// Prefix on a transient notice line.
const NOTICE_PREFIX: &str = " ! ";

/// Visual priority for a transient status-bar notice.
#[derive(Clone, Copy)]
pub enum NoticeTone {
    /// A failure or unavailable action that needs attention.
    Error,
}

/// Renders the status bar: a transient notice if one is set, otherwise the slim
/// hints for `context` (always ending in `? help`) plus a right-aligned alert
/// when any process has crashed. A pending terminal leader fills the row with a
/// high-contrast background until the next key completes the chord.
pub fn render(
    frame: &mut Frame,
    area: Rect,
    context: StatusContext,
    crashed: usize,
    notice: Option<(&str, NoticeTone)>,
    leader_pending: bool,
) {
    let terminal_context = matches!(
        context,
        StatusContext::Terminal | StatusContext::TerminalAgentSession
    );
    let leader_pending = leader_pending && terminal_context;
    if let Some((notice, tone)) = notice {
        let style = if leader_pending {
            Style::default()
                .fg(LEADER_PENDING_FOREGROUND)
                .bg(LEADER_PENDING_BACKGROUND)
                .add_modifier(Modifier::BOLD)
        } else {
            let color = match tone {
                NoticeTone::Error => ALERT_COLOR,
            };
            Style::default().fg(color).add_modifier(Modifier::BOLD)
        };
        let prefix = match tone {
            NoticeTone::Error => NOTICE_PREFIX,
        };
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(format!("{prefix}{notice}"), style)))
                .style(style),
            area,
        );
        return;
    }
    let key_color = if leader_pending {
        LEADER_PENDING_FOREGROUND
    } else {
        KEY_COLOR
    };
    let label_color = if leader_pending {
        LEADER_PENDING_FOREGROUND
    } else {
        LABEL_COLOR
    };
    let mut spans = Vec::new();
    if terminal_context {
        spans.push(Span::styled(LEADER_LABEL, Style::default().fg(key_color)));
    }
    let alert_width = if crashed > 0 {
        alert_label(crashed).chars().count() as u16
    } else {
        0
    };
    let leader_width = if terminal_context {
        LEADER_LABEL.chars().count() as u16
    } else {
        0
    };
    let reserved_width = alert_width
        .saturating_add(leader_width)
        .saturating_add(hint_width(HELP_HINT));
    let available_width = area.width.saturating_sub(reserved_width);
    spans.extend(hint_spans(
        &context.hints(available_width),
        key_color,
        label_color,
    ));
    spans.extend(hint_spans(&[HELP_HINT], key_color, label_color));
    let style = if leader_pending {
        Style::default().bg(LEADER_PENDING_BACKGROUND)
    } else {
        Style::default()
    };
    frame.render_widget(Paragraph::new(Line::from(spans)).style(style), area);
    if crashed > 0 {
        render_alert(frame, area, crashed, leader_pending);
    }
}

/// Draws the crashed-process count pinned to the right of the status row.
fn render_alert(frame: &mut Frame, area: Rect, crashed: usize, leader_pending: bool) {
    let label = alert_label(crashed);
    let width = label.chars().count() as u16;
    if area.width <= width {
        return;
    }
    let alert = Rect {
        x: area.x + area.width - width,
        y: area.y,
        width,
        height: area.height,
    };
    let style = if leader_pending {
        Style::default()
            .fg(LEADER_PENDING_FOREGROUND)
            .bg(LEADER_PENDING_BACKGROUND)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
            .fg(ALERT_COLOR)
            .add_modifier(Modifier::BOLD)
    };
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(label, style))),
        alert,
    );
}

/// Builds the crashed-process alert label.
fn alert_label(crashed: usize) -> String {
    format!("{ALERT_GLYPH} {crashed} crashed ")
}

/// Selects process hints that fit, retaining lifecycle actions before secondary
/// navigation and configuration actions while preserving display order.
fn process_hints(available_width: u16) -> Vec<Hint> {
    prioritized_hints(PROCESS_HINTS, PROCESS_HINT_PRIORITY, available_width)
}

/// Selects hints by retention priority, then restores their canonical order.
fn prioritized_hints(canonical: &[Hint], priority: &[Hint], available_width: u16) -> Vec<Hint> {
    let mut remaining = available_width;
    let mut selected = Vec::new();
    for hint in priority {
        let width = hint_width(*hint);
        if width <= remaining {
            selected.push(*hint);
            remaining -= width;
        }
    }
    canonical
        .iter()
        .filter(|hint| selected.contains(hint))
        .copied()
        .collect()
}

/// Rendered width of one compact hint, including its trailing separation.
fn hint_width((key, label): Hint) -> u16 {
    format!("{key} {label}{HINT_GAP}").chars().count() as u16
}

/// Builds the styled key/label spans for a set of hints.
fn hint_spans(hints: &[Hint], key_color: Color, label_color: Color) -> Vec<Span<'static>> {
    let mut spans = Vec::new();
    for (key, label) in hints {
        spans.push(Span::styled(
            format!("{key} "),
            Style::default().fg(key_color),
        ));
        spans.push(Span::styled(
            format!("{label}{HINT_GAP}"),
            Style::default().fg(label_color),
        ));
    }
    spans
}

#[cfg(test)]
mod tests {
    use ratatui::{Terminal, backend::TestBackend};

    use super::*;

    /// A wide process row keeps navigation, lifecycle, and configuration hints.
    #[test]
    fn a_wide_process_row_keeps_every_hint() {
        assert_eq!(process_hints(u16::MAX), PROCESS_HINTS);
    }

    /// The add action remains visible when only the highest-priority process
    /// actions fit.
    #[test]
    fn a_narrow_process_row_keeps_the_add_hint() {
        let width = hint_width(START_STOP_HINT) + hint_width(ADD_HINT);

        assert_eq!(process_hints(width), vec![START_STOP_HINT, ADD_HINT]);
    }

    /// Session hints expose close and omit the persistent autostart action.
    #[test]
    fn an_agent_session_prioritizes_close_without_autostart() {
        let hints = StatusContext::AgentSession.hints(u16::MAX);

        assert!(hints.contains(&CLOSE_HINT));
        assert!(!hints.contains(&AUTOSTART_HINT));
    }

    #[test]
    fn shows_a_crashed_alert_pinned_right() {
        let mut terminal = Terminal::new(TestBackend::new(60, 1)).unwrap();
        terminal
            .draw(|frame| render(frame, frame.area(), StatusContext::Process, 2, None, false))
            .unwrap();
        insta::assert_snapshot!(terminal.backend());
    }

    #[test]
    fn no_alert_when_nothing_has_crashed() {
        let mut terminal = Terminal::new(TestBackend::new(60, 1)).unwrap();
        terminal
            .draw(|frame| render(frame, frame.area(), StatusContext::Process, 0, None, false))
            .unwrap();
        insta::assert_snapshot!(terminal.backend());
    }

    #[test]
    fn a_project_row_shows_its_own_hints() {
        let mut terminal = Terminal::new(TestBackend::new(60, 1)).unwrap();
        terminal
            .draw(|frame| render(frame, frame.area(), StatusContext::Project, 0, None, false))
            .unwrap();
        insta::assert_snapshot!(terminal.backend());
    }

    #[test]
    fn a_notice_replaces_the_hints() {
        let mut terminal = Terminal::new(TestBackend::new(60, 1)).unwrap();
        terminal
            .draw(|frame| {
                render(
                    frame,
                    frame.area(),
                    StatusContext::Process,
                    0,
                    Some(("one: no such file", NoticeTone::Error)),
                    false,
                )
            })
            .unwrap();
        insta::assert_snapshot!(terminal.backend());
    }

    /// The pending leader chord fills the status row with its active-mode color.
    #[test]
    fn a_pending_leader_chord_highlights_the_status_row() {
        let width = 60;
        let mut terminal = Terminal::new(TestBackend::new(width, 1)).unwrap();
        terminal
            .draw(|frame| render(frame, frame.area(), StatusContext::Terminal, 1, None, true))
            .unwrap();

        let buffer = terminal.backend().buffer();
        for x in 0..width {
            let cell = buffer.cell((x, 0)).unwrap();
            assert_eq!(cell.bg, LEADER_PENDING_BACKGROUND);
        }
    }

    /// An asynchronous notice retains the pending leader chord's full-row cue.
    #[test]
    fn a_notice_keeps_the_pending_leader_cue_visible() {
        let width = 60;
        let mut terminal = Terminal::new(TestBackend::new(width, 1)).unwrap();
        terminal
            .draw(|frame| {
                render(
                    frame,
                    frame.area(),
                    StatusContext::Terminal,
                    0,
                    Some(("agent: finished", NoticeTone::Error)),
                    true,
                )
            })
            .unwrap();

        let buffer = terminal.backend().buffer();
        assert!(buffer.content.iter().any(|cell| cell.symbol() == "!"));
        for x in 0..width {
            let cell = buffer.cell((x, 0)).unwrap();
            assert_eq!(cell.bg, LEADER_PENDING_BACKGROUND);
        }
    }
}