codewhale-tui 0.9.3

Terminal UI for open-source and open-weight coding models
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! `/hooks` slash command — read-only listing of configured
//! lifecycle hooks (#460 MVP).
//!
//! The full picker / persisted enable-disable surface in #460 is
//! still M-sized. This MVP gives the user a no-typing view of what's
//! actually configured in `~/.codewhale/config.toml`'s `[hooks]`
//! table — the most-asked question once hooks start firing.

use crate::commands::traits::{CommandInfo, RegisterCommand};
use crate::hooks::HookEvent;
use crate::localization::MessageId;
use crate::tui::app::App;

use super::CommandResult;

pub(in crate::commands) const COMMAND_INFO: CommandInfo = CommandInfo {
    name: "hooks",
    aliases: &["hook", "gouzi"],
    usage: "/hooks [list|events]",
    description_id: MessageId::CmdHooksDescription,
};

pub(in crate::commands) struct HooksCmd;

impl RegisterCommand for HooksCmd {
    fn info() -> &'static CommandInfo {
        &COMMAND_INFO
    }

    fn execute(app: &mut App, arg: Option<&str>) -> CommandResult {
        hooks(app, arg)
    }
}

/// Top-level dispatch for `/hooks`. Subcommands:
///
/// * `/hooks`         — same as `/hooks list`.
/// * `/hooks list`    — show every configured hook grouped by event,
///   noting whether the global `[hooks].enabled` flag suppresses
///   them.
/// * `/hooks events`  — list every supported `HookEvent` value the
///   user can target in `[[hooks.hooks]]` entries. Useful for
///   discovery — without this, the only way to learn the event
///   names is to read source.
pub fn hooks(app: &App, arg: Option<&str>) -> CommandResult {
    let sub = arg.map(str::trim).unwrap_or("list").to_ascii_lowercase();
    match sub.as_str() {
        "" | "list" | "ls" | "show" => list(app),
        "events" | "event" | "list-events" => events(),
        other => CommandResult::error(format!(
            "unknown subcommand `{other}`. Try `/hooks list` or `/hooks events`."
        )),
    }
}

fn events() -> CommandResult {
    let mut out = String::new();
    out.push_str(
        "Available hook events (use one of these as `event = \"...\"` in your `[[hooks.hooks]]` entry).\n\
         Hooks are a TUI runtime feature: `codewhale exec`, the CLI dispatcher, the app-server,\n\
         and the workflow tool do not fire them.\n\n",
    );
    // Order matters — group lifecycle events first, then per-tool,
    // then situational. Stays stable across releases so users can
    // grep on it.
    let ordered = [
        (HookEvent::SessionStart, "fires once when the TUI launches"),
        (HookEvent::SessionEnd, "fires once on graceful shutdown"),
        (
            HookEvent::TurnEnd,
            "fires after a turn completes (observer-only)",
        ),
        (
            HookEvent::MessageSubmit,
            "fires before model dispatch; can transform or block submitted text",
        ),
        (
            HookEvent::ToolCallBefore,
            "fires before each tool call; can allow/deny/ask, rewrite input, add context",
        ),
        (
            HookEvent::ToolCallAfter,
            "fires after each tool call (observer-only)",
        ),
        (
            HookEvent::ModeChange,
            "fires on Plan/Act/Operate transitions",
        ),
        (
            HookEvent::OnError,
            "fires on transport / capacity / tool errors",
        ),
        (
            HookEvent::SubagentSpawn,
            "fires when a sub-agent starts (observer-only)",
        ),
        (
            HookEvent::SubagentComplete,
            "fires when a sub-agent completes, fails, or is cancelled (observer-only)",
        ),
        (
            HookEvent::ShellEnv,
            "fires before each exec_shell; stdout KEY=VALUE lines are merged into its environment",
        ),
    ];
    for (event, desc) in ordered {
        out.push_str(&format!("  - `{}` — {desc}\n", event_label(event)));
    }
    out.push_str(
        "\nOnly `message_submit`, `tool_call_before`, and `shell_env` can steer a turn.\n\
         Observer-only means the *result* is ignored — the command still runs\n\
         and can have any external side effect.\n\n\
         Full contract: docs/HOOKS.md\n",
    );
    CommandResult::message(out.trim_end().to_string())
}

fn list(app: &App) -> CommandResult {
    let config = app.hooks.config();
    if config.hooks.is_empty() && config.problems.is_empty() {
        return CommandResult::message(
            "No hooks configured. Add a `[[hooks.hooks]]` entry to `~/.codewhale/config.toml` to define one.",
        );
    }
    if config.hooks.is_empty() {
        let mut out =
            String::from("No runnable hooks. Every configured entry was rejected at load:\n\n");
        out.push_str(&render_problems(&config.problems));
        return CommandResult::message(out.trim_end().to_string());
    }

    let mut out = String::new();
    out.push_str(&format!(
        "{} configured hook(s) (global enabled: {}):\n\n",
        config.hooks.len(),
        if config.enabled {
            "yes"
        } else {
            "no — all hooks suppressed"
        }
    ));

    let mut by_event: std::collections::BTreeMap<&str, Vec<&crate::hooks::Hook>> =
        std::collections::BTreeMap::new();
    for hook in &config.hooks {
        by_event
            .entry(event_label(hook.event))
            .or_default()
            .push(hook);
    }

    for (event, hooks) in by_event {
        out.push_str(&format!("### {event}\n"));
        for hook in hooks {
            // `name` is operator-supplied and otherwise unbounded: a name made
            // of ANSI escapes would repaint this listing, and a long one would
            // push the rest of the row off screen.
            let label = crate::hooks::sanitize_hook_label(hook.name.as_deref());
            // `[bg]` describes actual scheduling: `shell_env` ignores the flag
            // and always runs in the foreground, so it is not labelled.
            let bg = if hook.background && hook.event.honors_background() {
                " [bg, submitted not awaited]"
            } else {
                ""
            };
            let timeout = render_timeout(config, hook);
            let condition = match &hook.condition {
                None | Some(crate::hooks::HookCondition::Always) => String::new(),
                Some(c) => format!(" if {}", condition_summary(c)),
            };
            let cmd_preview = preview_command(&hook.command, 60);
            out.push_str(&format!(
                "  - {label}{bg} (timeout {timeout}){condition}\n      $ {cmd_preview}\n",
            ));
        }
        out.push('\n');
    }

    if !config.problems.is_empty() {
        out.push_str("### configuration problems\n");
        out.push_str(&render_problems(&config.problems));
        out.push('\n');
    }

    if !config.enabled {
        out.push_str(
            "Hooks are globally disabled — set `[hooks].enabled = true` in `config.toml` to fire them.\n",
        );
    }

    CommandResult::message(out.trim_end().to_string())
}

/// The timeout this hook will actually run with, plus where it came from.
///
/// `[hooks].default_timeout_secs` *replaces* every hook's own `timeout_secs`
/// (see `HooksConfig::effective_timeout_secs`). Rendering `hook.timeout_secs`
/// unconditionally made `/hooks list` report a budget no hook would ever run
/// with — a listing that disagrees with the runtime is worse than no listing.
fn render_timeout(config: &crate::hooks::HooksConfig, hook: &crate::hooks::Hook) -> String {
    let effective = config.effective_timeout_secs(hook);
    if config.timeout_is_overridden() {
        format!("{effective}s — `[hooks].default_timeout_secs` override")
    } else {
        format!("{effective}s")
    }
}

/// Render load-time problems. Only the hook's own `name`, its event, and a
/// fixed explanation are shown — never the command line, stdin payload, or
/// any resolved filesystem path.
fn render_problems(problems: &[crate::hooks::HookConfigProblem]) -> String {
    let mut out = String::new();
    for problem in problems {
        out.push_str(&format!("  - {}\n", problem.summary()));
    }
    out
}

fn event_label(event: HookEvent) -> &'static str {
    match event {
        HookEvent::SessionStart => "session_start",
        HookEvent::SessionEnd => "session_end",
        HookEvent::MessageSubmit => "message_submit",
        HookEvent::ToolCallBefore => "tool_call_before",
        HookEvent::ToolCallAfter => "tool_call_after",
        HookEvent::ModeChange => "mode_change",
        HookEvent::OnError => "on_error",
        HookEvent::TurnEnd => "turn_end",
        HookEvent::SubagentSpawn => "subagent_spawn",
        HookEvent::SubagentComplete => "subagent_complete",
        HookEvent::ShellEnv => "shell_env",
    }
}

fn condition_summary(condition: &crate::hooks::HookCondition) -> String {
    match condition {
        crate::hooks::HookCondition::Always => "always".to_string(),
        crate::hooks::HookCondition::ToolName { name } => {
            format!("tool_name=`{}`", condition_value(name))
        }
        crate::hooks::HookCondition::ToolCategory { category } => {
            format!("tool_category=`{}`", condition_value(category))
        }
        crate::hooks::HookCondition::Mode { mode } => {
            format!("mode=`{}`", condition_value(mode))
        }
        crate::hooks::HookCondition::ExitCode { code } => format!("exit_code={code}"),
        crate::hooks::HookCondition::All { conditions } => format!(
            "all of [{}]",
            conditions
                .iter()
                .map(condition_summary)
                .collect::<Vec<_>>()
                .join(", ")
        ),
        crate::hooks::HookCondition::Any { conditions } => format!(
            "any of [{}]",
            conditions
                .iter()
                .map(condition_summary)
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

/// Single-line preview of the shell command, capped at `max_chars`.
///
/// Filtering newlines is not enough on its own: the command is operator text
/// and can contain escape sequences, so it goes through the shared sanitizer
/// before the cap.
fn preview_command(command: &str, max_chars: usize) -> String {
    let single_line = crate::hooks::sanitize_hook_line(command, usize::MAX);
    if single_line.chars().count() <= max_chars {
        return single_line;
    }
    let mut out: String = single_line
        .chars()
        .take(max_chars.saturating_sub(1))
        .collect();
    out.push('');
    out
}

/// Operator-supplied strings inside a rendered condition.
///
/// `tool_name`, `tool_category`, and `mode` come from config verbatim, so the
/// same bound-and-de-fang rule that governs hook names governs these.
fn condition_value(value: &str) -> String {
    crate::hooks::sanitize_hook_line(value, crate::hooks::HOOK_LABEL_MAX_CHARS)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hooks::{Hook, HookCondition};

    #[test]
    fn preview_command_truncates_to_cap() {
        let cmd = "x".repeat(200);
        assert_eq!(preview_command(&cmd, 10).chars().count(), 10);
        assert!(preview_command(&cmd, 10).ends_with(''));
    }

    #[test]
    fn preview_command_strips_newlines() {
        assert_eq!(
            preview_command("line one\nline two", 50),
            "line one line two"
        );
    }

    /// A hook command is operator text. Filtering `\n` kept the row from
    /// splitting, but left every other control character — including the CSI
    /// introducer — free to repaint the terminal from inside `/hooks list`.
    #[test]
    fn preview_command_defangs_control_characters() {
        let preview = preview_command("echo \u{1b}[2Jhi\r\tthere\u{7}", 100);
        assert!(!preview.contains('\u{1b}'), "{preview:?}");
        assert!(!preview.contains('\r'), "{preview:?}");
        assert!(!preview.contains('\u{7}'), "{preview:?}");
        assert!(!preview.contains('\t'), "{preview:?}");
        assert!(preview.contains("there"), "{preview:?}");
    }

    #[test]
    fn hook_labels_are_bounded_and_defanged() {
        let noisy = format!("\u{1b}[31mgate\n{}", "x".repeat(500));
        let label = crate::hooks::sanitize_hook_label(Some(&noisy));
        assert!(!label.contains('\u{1b}'), "{label}");
        assert!(!label.contains('\n'), "{label}");
        assert!(
            label.chars().count() <= crate::hooks::HOOK_LABEL_MAX_CHARS + 16,
            "{} chars",
            label.chars().count()
        );
        // A name that is only whitespace, or absent, still renders something.
        assert_eq!(crate::hooks::sanitize_hook_label(Some("   ")), "(unnamed)");
        assert_eq!(crate::hooks::sanitize_hook_label(None), "(unnamed)");
    }

    /// Condition values are config strings too, and they were being
    /// interpolated raw into the same row the label was being sanitized in.
    #[test]
    fn condition_summary_defangs_operator_supplied_values() {
        let rendered = condition_summary(&HookCondition::ToolName {
            name: format!("\u{1b}[2Jexec_shell{}", "y".repeat(500)),
        });
        assert!(!rendered.contains('\u{1b}'), "{rendered}");
        assert!(
            rendered.chars().count() <= crate::hooks::HOOK_LABEL_MAX_CHARS + 32,
            "{} chars",
            rendered.chars().count()
        );
    }

    /// `default_timeout_secs = 0` is rejected at load, so the listing must
    /// report the per-hook budget the runtime will actually apply and must not
    /// credit the provenance to a setting that was ignored — while the
    /// rejection itself still shows up in the problems section.
    #[test]
    fn listed_timeout_ignores_a_rejected_zero_override() {
        let hook = Hook::new(HookEvent::SessionStart, "echo hi").with_timeout(90);
        let zeroed = crate::hooks::HooksConfig {
            enabled: true,
            hooks: vec![hook.clone()],
            default_timeout_secs: Some(0),
            ..crate::hooks::HooksConfig::default()
        };
        assert_eq!(render_timeout(&zeroed, &hook), "90s");

        let problems = zeroed.validate();
        let rendered = render_problems(&problems);
        assert!(rendered.contains("`[hooks]` setting"), "{rendered}");
        assert!(rendered.contains("default_timeout_secs = 0"), "{rendered}");
    }

    #[test]
    fn preview_command_keeps_short_input_intact() {
        assert_eq!(preview_command("echo hi", 50), "echo hi");
    }

    #[test]
    fn condition_summary_renders_all_variants() {
        assert_eq!(condition_summary(&HookCondition::Always), "always");
        assert_eq!(
            condition_summary(&HookCondition::ToolName {
                name: "exec_shell".into()
            }),
            "tool_name=`exec_shell`"
        );
        assert_eq!(
            condition_summary(&HookCondition::ToolCategory {
                category: "shell".into()
            }),
            "tool_category=`shell`"
        );
        assert_eq!(
            condition_summary(&HookCondition::Mode {
                mode: "yolo".into()
            }),
            "mode=`yolo`"
        );
        assert_eq!(
            condition_summary(&HookCondition::ExitCode { code: 1 }),
            "exit_code=1"
        );
        assert_eq!(
            condition_summary(&HookCondition::All {
                conditions: vec![
                    HookCondition::ToolName {
                        name: "exec_shell".into()
                    },
                    HookCondition::Mode {
                        mode: "yolo".into()
                    }
                ]
            }),
            "all of [tool_name=`exec_shell`, mode=`yolo`]"
        );
    }

    #[test]
    fn events_subcommand_lists_every_event_variant_in_documented_order() {
        let result = events();
        let body = result.message.expect("non-empty body");
        let positions: Vec<(usize, &str)> = [
            "session_start",
            "session_end",
            "turn_end",
            "message_submit",
            "tool_call_before",
            "tool_call_after",
            "mode_change",
            "on_error",
            "subagent_spawn",
            "subagent_complete",
            "shell_env",
        ]
        .iter()
        .map(|name| {
            (
                body.find(name).unwrap_or_else(|| {
                    panic!("event `{name}` missing from /hooks events output:\n{body}")
                }),
                *name,
            )
        })
        .collect();
        // Documented order is lifecycle → tool-call → situational.
        // Each subsequent position must be greater than the previous.
        for window in positions.windows(2) {
            let (a_pos, a_name) = window[0];
            let (b_pos, b_name) = window[1];
            assert!(
                a_pos < b_pos,
                "expected `{a_name}` before `{b_name}` in events listing"
            );
        }
        // Each event line includes the descriptive blurb.
        assert!(body.contains("fires once when the TUI launches"));
        // `tool_call_before` has been a steering hook since #3026; the listing
        // must not keep advertising it as read-only.
        assert!(
            !body.contains("read-only observer"),
            "stale read-only wording in events listing:\n{body}"
        );
        assert!(body.contains("can allow/deny/ask"));
        assert!(body.contains("docs/HOOKS.md"));
    }

    #[test]
    fn event_label_covers_every_variant() {
        // Compile-time `match` exhaustiveness; this just sanity-checks
        // the rendered strings stay stable.
        assert_eq!(event_label(HookEvent::SessionStart), "session_start");
        assert_eq!(event_label(HookEvent::SessionEnd), "session_end");
        assert_eq!(event_label(HookEvent::ToolCallBefore), "tool_call_before");
        assert_eq!(event_label(HookEvent::ToolCallAfter), "tool_call_after");
        assert_eq!(event_label(HookEvent::MessageSubmit), "message_submit");
        assert_eq!(event_label(HookEvent::ModeChange), "mode_change");
        assert_eq!(event_label(HookEvent::OnError), "on_error");
        assert_eq!(event_label(HookEvent::TurnEnd), "turn_end");
        assert_eq!(event_label(HookEvent::SubagentSpawn), "subagent_spawn");
        assert_eq!(
            event_label(HookEvent::SubagentComplete),
            "subagent_complete"
        );
    }

    #[test]
    fn list_renders_hooks_grouped_by_event_and_notes_disabled_state() {
        // We test the formatter directly via a synthetic HooksConfig
        // because `App` is heavyweight to spin up here. The actual
        // `list(&App)` path is exercised once we hand the real
        // config in via `app.hooks.config()`; the formatter logic is
        // unit-tested standalone below.
        let cfg = crate::hooks::HooksConfig {
            enabled: false,
            hooks: vec![
                Hook::new(HookEvent::SessionStart, "echo started").with_name("greet"),
                Hook::new(HookEvent::ToolCallAfter, "notify-send done")
                    .with_condition(HookCondition::ToolName {
                        name: "exec_shell".into(),
                    })
                    .with_name("notify"),
            ],
            ..crate::hooks::HooksConfig::default()
        };

        // Synthesize the expected sections by re-running the same
        // formatter logic against the BTreeMap grouping.
        let mut by_event: std::collections::BTreeMap<&str, Vec<&Hook>> =
            std::collections::BTreeMap::new();
        for h in &cfg.hooks {
            by_event.entry(event_label(h.event)).or_default().push(h);
        }
        let events: Vec<&&str> = by_event.keys().collect();
        // BTreeMap sorts alphabetically — `session_start` before `tool_call_after`.
        assert_eq!(events, vec![&"session_start", &"tool_call_after"]);
    }

    #[test]
    fn events_listing_states_scope_and_the_steering_allowlist() {
        let body = events().message.expect("non-empty body");
        // Scope truth: this is a TUI runtime feature.
        assert!(body.contains("TUI runtime feature"), "{body}");
        assert!(body.contains("codewhale exec"), "{body}");
        // Steering allowlist, matching docs/HOOKS.md.
        assert!(body.contains("`message_submit`, `tool_call_before`, and `shell_env`"));
        // And the honest caveat about what observer-only does not mean.
        assert!(body.contains("can have any external side effect"), "{body}");
    }

    #[test]
    fn events_listing_covers_every_runtime_event() {
        let body = events().message.expect("non-empty body");
        for event in crate::hooks::ALL_HOOK_EVENTS {
            assert!(
                body.contains(event.as_str()),
                "event `{}` missing from /hooks events",
                event.as_str()
            );
        }
    }

    #[test]
    fn listed_timeout_is_the_one_the_runtime_will_apply() {
        let hook = Hook::new(HookEvent::SessionStart, "echo hi").with_timeout(90);

        let per_hook = crate::hooks::HooksConfig {
            enabled: true,
            hooks: vec![hook.clone()],
            ..crate::hooks::HooksConfig::default()
        };
        assert_eq!(render_timeout(&per_hook, &hook), "90s");

        // With the global override set, the runtime uses 5s — the listing must
        // say 5s, and say why.
        let overridden = crate::hooks::HooksConfig {
            enabled: true,
            hooks: vec![hook.clone()],
            default_timeout_secs: Some(5),
            ..crate::hooks::HooksConfig::default()
        };
        let rendered = render_timeout(&overridden, &hook);
        assert!(rendered.starts_with("5s"), "{rendered}");
        assert!(!rendered.contains("90"), "{rendered}");
        assert!(rendered.contains("default_timeout_secs"), "{rendered}");
    }

    #[test]
    fn rendered_problems_name_the_hook_without_leaking_the_command() {
        let problems = vec![
            crate::hooks::HookConfigProblem {
                name: Some("gate".to_string()),
                event: Some(HookEvent::SessionStart),
                detail: "condition can never match".to_string(),
                rejected: true,
            },
            crate::hooks::HookConfigProblem {
                name: None,
                event: Some(HookEvent::ShellEnv),
                detail: "`background = true` is not honored".to_string(),
                rejected: false,
            },
        ];
        let rendered = render_problems(&problems);
        assert!(rendered.contains("rejected: `session_start` hook `gate`"));
        assert!(rendered.contains("warning: `shell_env` hook `(unnamed)`"));
        // Only the hook name, event, and fixed detail — nothing else.
        assert!(!rendered.contains('$'), "{rendered}");
        assert!(!rendered.contains('/'), "{rendered}");
    }
}