返回 CodeWhale
notifications.rs
根目录 / crates / tui / src / tui / notifications.rs
1 //! Desktop notifications for turn completion.
2 //!
3 //! Supports five delivery mechanisms:
4 //! - **OSC 9** — terminal escape sequence (`\x1b]9;…\x07`) for iTerm2,
5 //! Ghostty, WezTerm, and tmux (with DCS passthrough).
6 //! - **Kitty** — OSC 99 protocol with ST terminator (no audible beep).
7 //! - **Ghostty** — OSC 777 notification protocol.
8 //! - **BEL** — an explicit audio-only notification transport.
9 //!
10 //! When `method = "auto"`, the resolver picks the best method for the
11 //! current terminal. Unknown terminals fail closed to `Off`; an audible BEL
12 //! is emitted only by an explicitly selected sound or `method = "bel"`.
13 //!
14 //! Every mechanism is fed a [`NotificationPayload`] — a typed, bounded,
15 //! redaction-aware value — rather than a free-form `String` (#4834). See
16 //! [`codewhale_notify::payload`] for the per-kind disclosure
17 //! policy.
18 //!
19 //! Delivery is governed by one [`NotificationGate`] (#5041):
20 //! `[notifications].quiet` silences everything and
21 //! `[notifications.events]` disables individual categories, enforced at
22 //! the emission path so no protocol can leak a suppressed event.
23
24 use std::io::{self, Write};
25 use std::sync::atomic::{AtomicBool, Ordering};
26 use std::sync::atomic::{AtomicU8, AtomicU64};
27 use std::sync::{Mutex, OnceLock};
28 use std::time::Duration;
29
30 use codewhale_notify::delivery::notify_with_sinks;
31 #[cfg(test)]
32 use codewhale_notify::delivery::resolve_method;
33 #[cfg(test)]
34 use codewhale_notify::payload::NotificationKind;
35 pub use codewhale_notify::payload::NotificationPayload;
36 use codewhale_notify::{
37 AttentionCondition, DeliveryOutcome, Method, NotificationGate, attention_delivery_allowed_at,
38 settings_projection,
39 };
40
41 /// Process-wide configured delivery method. Installed before the event loop
42 /// starts and updated by live Settings, so producers such as the model-facing
43 /// `notify` tool cannot silently bypass `method = "off"`.
44 static CONFIGURED_METHOD: AtomicU8 = AtomicU8::new(0);
45
46 fn method_to_u8(method: Method) -> u8 {
47 match method {
48 Method::Auto => 0,
49 Method::Osc9 => 1,
50 Method::Bel => 2,
51 Method::MacOS => 3,
52 Method::Kitty => 4,
53 Method::Ghostty => 5,
54 Method::Off => 6,
55 }
56 }
57
58 /// Install `method` as the process-wide notification method for paths that
59 /// do not resolve a method of their own (the `notify` tool); `pub(crate)`
60 /// so the tool's tests can arrange the installed method.
61 pub(crate) fn install_configured_method(method: Method) {
62 CONFIGURED_METHOD.store(method_to_u8(method), Ordering::SeqCst);
63 }
64
65 /// Delivery method currently selected by Settings.
66 #[must_use]
67 pub fn configured_method() -> Method {
68 match CONFIGURED_METHOD.load(Ordering::SeqCst) {
69 1 => Method::Osc9,
70 2 => Method::Bel,
71 3 => Method::MacOS,
72 4 => Method::Kitty,
73 5 => Method::Ghostty,
74 6 => Method::Off,
75 _ => Method::Auto,
76 }
77 }
78
79 /// Everything on, quiet off — the pre-#5041 behavior, and the effective
80 /// policy until the first [`settings`] call installs the configured gate.
81 const GATE_DEFAULT_BITS: u8 = 0b0111_1110;
82
83 /// Process-wide gate, packed to one byte so reads on the emission path are
84 /// a single atomic load.
85 static NOTIFICATION_GATE: AtomicU8 = AtomicU8::new(GATE_DEFAULT_BITS);
86
87 static ATTENTION_CONDITION: AtomicU8 = AtomicU8::new(AttentionCondition::Unfocused as u8);
88 static UNFOCUSED_SINCE_MS: AtomicU64 = AtomicU64::new(0);
89
90 fn attention_clock_ms() -> u64 {
91 static STARTED_AT: OnceLock<std::time::Instant> = OnceLock::new();
92 // Reserve zero for "no observed focus loss".
93 STARTED_AT
94 .get_or_init(std::time::Instant::now)
95 .elapsed()
96 .as_millis()
97 .saturating_add(1) as u64
98 }
99
100 fn install_attention_condition(condition: AttentionCondition) {
101 ATTENTION_CONDITION.store(condition as u8, Ordering::SeqCst);
102 }
103
104 fn current_attention_condition() -> AttentionCondition {
105 match ATTENTION_CONDITION.load(Ordering::SeqCst) {
106 0 => AttentionCondition::Always,
107 2 => AttentionCondition::Never,
108 _ => AttentionCondition::Unfocused,
109 }
110 }
111
112 #[must_use]
113 fn attention_delivery_allowed() -> bool {
114 attention_delivery_allowed_at(
115 current_attention_condition(),
116 TERMINAL_FOCUSED.load(Ordering::SeqCst),
117 UNFOCUSED_SINCE_MS.load(Ordering::SeqCst),
118 attention_clock_ms(),
119 )
120 }
121
122 /// Install `gate` as the process-wide notification policy.
123 pub fn install_notification_gate(gate: NotificationGate) {
124 NOTIFICATION_GATE.store(gate.to_bits(), Ordering::SeqCst);
125 }
126
127 /// The currently installed process-wide notification gate.
128 #[must_use]
129 pub fn current_notification_gate() -> NotificationGate {
130 NotificationGate::from_bits(NOTIFICATION_GATE.load(Ordering::SeqCst))
131 }
132
133 /// Emit a notification to `sink` if the elapsed time meets or exceeds
134 /// `threshold`, `method` is not `Off`, and `gate` allows the payload's
135 /// category.
136 ///
137 /// This variant takes a `W: Write` sink and an explicit gate for
138 /// testability; production callers go through [`notify_done`], which
139 /// loads the installed process-wide gate.
140 #[cfg(test)]
141 pub fn notify_done_to<W: Write>(
142 method: Method,
143 in_tmux: bool,
144 payload: &NotificationPayload,
145 threshold: Duration,
146 elapsed: Duration,
147 gate: NotificationGate,
148 sink: &mut W,
149 ) -> DeliveryOutcome {
150 let mut policy = codewhale_notify::sound_policy::EventSoundPolicy::default();
151 notify_with_sinks(
152 method,
153 in_tmux,
154 payload,
155 threshold,
156 elapsed,
157 gate,
158 true,
159 sink,
160 &mut |kind, bell| {
161 policy.decide(
162 codewhale_notify::sound_policy::event_for_kind(kind),
163 0,
164 bell,
165 )
166 },
167 &mut codewhale_notify::audio::emit_terminal,
168 &mut |_| DeliveryOutcome::UnsupportedTransport,
169 )
170 }
171
172 /// Emit a notification to **stdout** if `elapsed >= threshold`.
173 ///
174 /// With `method = Auto`, selects the best protocol for the current terminal
175 /// (OSC 9, Kitty OSC 99, Ghostty OSC 777, or macOS). Unknown terminals
176 /// remain unsupported; explicit method Off suppresses audio and banners.
177 /// See [`codewhale_notify::delivery::resolve_method`] for the canonical resolution table. Pass
178 /// `in_tmux = true` (i.e. `$TMUX` is non-empty at runtime) to wrap OSC
179 /// sequences in a DCS passthrough.
180 pub fn notify_done(
181 method: Method,
182 in_tmux: bool,
183 payload: &NotificationPayload,
184 threshold: Duration,
185 elapsed: Duration,
186 ) -> DeliveryOutcome {
187 let reserved = std::cell::Cell::new(None);
188 notify_with_sinks(
189 method,
190 in_tmux,
191 payload,
192 threshold,
193 elapsed,
194 current_notification_gate(),
195 attention_delivery_allowed(),
196 &mut io::stdout(),
197 &mut |kind, bell| {
198 let now_ms = codewhale_notify::sound_policy::epoch_millis_now();
199 let decision = codewhale_notify::sound_policy::decide(kind, now_ms, bell);
200 if matches!(
201 decision,
202 codewhale_notify::sound_policy::SoundDecision::Play(_)
203 ) {
204 reserved.set(Some((kind, now_ms)));
205 }
206 decision
207 },
208 &mut |cue, sink| {
209 let outcome = codewhale_notify::audio::dispatch(cue, sink);
210 // A cue that never played must not spend the category's repeat
211 // window: the next notification may try again (U06-m3).
212 if matches!(
213 outcome,
214 codewhale_notify::audio::AudioOutcome::Busy
215 | codewhale_notify::audio::AudioOutcome::Unsupported
216 | codewhale_notify::audio::AudioOutcome::Failed
217 ) && let Some((kind, reserved_ms)) = reserved.take()
218 {
219 codewhale_notify::sound_policy::release(kind, reserved_ms);
220 }
221 outcome
222 },
223 &mut dispatch_native,
224 )
225 }
226
227 /// The `notify` tool's delivery: a typed model-notify payload through the
228 /// configured method, installed gate and attention policy, threshold zero.
229 pub(crate) fn notify_model(title: &str, body: Option<&str>) -> &'static str {
230 // #4834: model-authored text is the least trusted input that can reach
231 // Notification Center, so it goes through the typed payload like every
232 // other event kind: bounded, control-byte-stripped, and redacted for
233 // credentials, absolute paths, and raw tool JSON.
234 let payload = NotificationPayload::model_notify(title, body);
235 let in_tmux = std::env::var("TMUX").is_ok_and(|v| !v.is_empty());
236 notify_done(
237 configured_method(),
238 in_tmux,
239 &payload,
240 Duration::ZERO,
241 Duration::from_secs(1),
242 )
243 .receipt()
244 }
245
246 /// Set the terminal taskbar progress state via OSC 9 ; 4.
247 ///
248 /// Windows Terminal supports this to show progress on the taskbar icon:
249 /// - `state = 0` — no progress (clear)
250 /// - `state = 1` — indeterminate (cycling green)
251 /// - `state = 2` — normal (0-100, requires progress param)
252 /// - `state = 3` — error (red)
253 /// - `state = 4` — paused (yellow)
254 ///
255 /// Other terminals (iTerm2, WezTerm) ignore the sequence silently.
256 /// Best-effort — write failures are ignored.
257 /// Build the OSC 9;4 taskbar-progress sequence. Split from the write so the
258 /// bytes can be asserted without depending on whether the test runner owns a
259 /// terminal.
260 #[must_use]
261 fn taskbar_progress_sequence(state: u8, progress: Option<u8>) -> String {
262 match progress {
263 Some(pct) => format!("\x1b]9;4;{state};{pct}\x07"),
264 None => format!("\x1b]9;4;{state}\x07"),
265 }
266 }
267
268 const MAX_TERMINAL_TITLE_CHARS: usize = 160;
269
270 /// Build a bounded OSC 0 window-title sequence. User-controlled session names
271 /// can reach this boundary, so control and bidi-format characters are removed
272 /// before the title is embedded in a terminal escape sequence.
273 #[must_use]
274 fn terminal_title_sequence(title: &str) -> String {
275 let safe: String = codewhale_engine::session_manager::sanitize_session_title(title)
276 .chars()
277 .take(MAX_TERMINAL_TITLE_CHARS)
278 .collect();
279 format!("\x1b]0;{safe}\x07")
280 }
281
282 /// Whether raw terminal control sequences may be written to stdout.
283 ///
284 /// OSC 9;4 (taskbar progress) and OSC 0 (window title) are *control* bytes,
285 /// not content. A terminal that understands them renders nothing visible; a
286 /// pipe, a file, or a CI log renders them literally, so `cargo test` output
287 /// and redirected sessions pick up stray `]9;4;1]0;` noise. Gate on stdout
288 /// actually being a TTY — there is no one to control otherwise.
289 fn stdout_accepts_control_sequences() -> bool {
290 use std::io::IsTerminal;
291 io::stdout().is_terminal()
292 }
293
294 pub fn set_taskbar_progress(state: u8, progress: Option<u8>) {
295 if !stdout_accepts_control_sequences() {
296 return;
297 }
298 let seq = taskbar_progress_sequence(state, progress);
299 let mut stdout = io::stdout();
300 let _ = stdout.write_all(seq.as_bytes());
301 let _ = stdout.flush();
302 }
303
304 /// Set taskbar progress to indeterminate (cycling) — call at turn start.
305 pub fn set_taskbar_progress_busy() {
306 set_taskbar_progress(1, None);
307 }
308
309 /// Clear taskbar progress — call at turn end.
310 pub fn clear_taskbar_progress() {
311 set_taskbar_progress(0, None);
312 }
313
314 /// User-configured window-title prefix, rendered as `[prefix] …` in front of
315 /// every terminal window title. Empty means no prefix — the historical
316 /// byte-for-byte behavior. Set via the `/title` command (session level) or
317 /// the `title` config key (default level); the render loop syncs it here
318 /// through [`set_title_prefix`].
319 static TITLE_PREFIX: OnceLock<Mutex<String>> = OnceLock::new();
320
321 pub(crate) fn title_prefix_slot() -> &'static Mutex<String> {
322 TITLE_PREFIX.get_or_init(|| Mutex::new(String::new()))
323 }
324
325 /// Serialise tests that touch the process-global title prefix so parallel
326 /// threads cannot leak a prefix into an unrelated assertion. Also used by
327 /// `underwater` tests that drive [`set_title_prefix`] through the render
328 /// loop.
329 #[cfg(test)]
330 pub(crate) fn title_prefix_test_lock() -> std::sync::MutexGuard<'static, ()> {
331 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
332 LOCK.get_or_init(|| Mutex::new(()))
333 .lock()
334 .unwrap_or_else(|poisoned| poisoned.into_inner())
335 }
336
337 /// Set the `[prefix] …` window-title prefix, or clear it with `None`/empty.
338 ///
339 /// Change detection keeps the per-frame render-loop sync free when the title
340 /// did not move; on an actual change the running title is redrawn immediately
341 /// so alt-tabbed sessions pick up the new identity without waiting for the
342 /// next activity-verb update.
343 pub fn set_title_prefix(prefix: Option<&str>) {
344 let prefix = prefix.unwrap_or_default().trim();
345 let changed = {
346 let mut slot = title_prefix_slot()
347 .lock()
348 .unwrap_or_else(|poisoned| poisoned.into_inner());
349 if slot.as_str() == prefix {
350 false
351 } else {
352 slot.clear();
353 slot.push_str(prefix);
354 true
355 }
356 };
357 // Redraw only after the prefix lock is released: the title render path
358 // re-locks [`title_prefix_slot`] through `decorate_title`, and a `Mutex`
359 // is not reentrant — drawing while holding it would deadlock the
360 // render loop on the first `/title` during an active turn.
361 if !changed {
362 return;
363 }
364 if TITLE_ANIMATION_RUNNING.load(Ordering::SeqCst) {
365 let base = title_animation_base()
366 .lock()
367 .map_or_else(|_| "codewhale".to_string(), |base| base.clone());
368 let motion = TITLE_MOTION_ENABLED.load(Ordering::SeqCst);
369 set_terminal_title(&title_activity_label(
370 &base,
371 Duration::ZERO,
372 TERMINAL_FOCUSED.load(Ordering::SeqCst),
373 motion,
374 ));
375 } else {
376 // At rest nothing else repaints OSC 0 until the next turn starts, so
377 // `/title` or `/rename` between turns must redraw the resting title
378 // itself — otherwise the tab keeps the old name while the command
379 // already reported success.
380 set_terminal_title(&decorate_title(resting_title_body()));
381 }
382 }
383
384 /// The undecorated title body shown between turns: the completion marker
385 /// while it is still on display, otherwise the plain product name.
386 fn resting_title_body() -> &'static str {
387 if COMPLETION_MARKER_SHOWN.load(Ordering::SeqCst) {
388 "✓ done"
389 } else {
390 "codewhale"
391 }
392 }
393
394 /// Shared flag controlling the title activity marker. Set to `true` by
395 /// `start_title_animation()`, cleared by `stop_title_animation()`.
396 static TITLE_ANIMATION_RUNNING: AtomicBool = AtomicBool::new(false);
397 /// Focus reporting starts enabled before the event loop begins, so treating
398 /// the terminal as focused is the safe default: never flood window chrome
399 /// unless the terminal has explicitly reported `FocusLost` or motion is on.
400 static TERMINAL_FOCUSED: AtomicBool = AtomicBool::new(true);
401 /// When false, the title keeps a static whale + state (reduced motion /
402 /// status animation off) instead of cycling frames.
403 static TITLE_MOTION_ENABLED: AtomicBool = AtomicBool::new(true);
404 /// Invalidates a previous animation worker when a new turn starts or ends.
405 static TITLE_ANIMATION_GENERATION: AtomicU64 = AtomicU64::new(0);
406 static TITLE_ANIMATION_BASE: OnceLock<Mutex<String>> = OnceLock::new();
407 static TITLE_ACTIVITY_VERB: OnceLock<Mutex<String>> = OnceLock::new();
408 /// Whale frames restored from #1871 (`cd357de0c`). Cycle slowly so the
409 /// terminal title communicates life without competing with in-app spinners.
410 const TITLE_FRAME_HOLD: Duration = Duration::from_millis(800);
411 const TITLE_WHALE_FRAMES: &[&str] = &["🐳", "🐋", "🐳", "🐋"];
412
413 fn title_animation_base() -> &'static Mutex<String> {
414 TITLE_ANIMATION_BASE.get_or_init(|| Mutex::new("codewhale".to_string()))
415 }
416
417 fn title_activity_verb() -> &'static Mutex<String> {
418 TITLE_ACTIVITY_VERB.get_or_init(|| Mutex::new("in the current…".to_string()))
419 }
420
421 /// Configure whether the title whale cycles frames.
422 ///
423 /// Call once at startup (and whenever motion settings change). Reduced motion
424 /// and `status_indicator = "off"` both freeze the title to a single whale.
425 pub fn set_title_motion_enabled(enabled: bool) {
426 TITLE_MOTION_ENABLED.store(enabled, Ordering::SeqCst);
427 }
428
429 /// Update the truthful activity verb shown next to the title whale
430 /// (`in the current…`, `reasoning…`, `using tool…`, `verifying…`, `waiting on you…`).
431 pub fn set_title_activity_verb(verb: &str) {
432 let verb = verb.trim();
433 if verb.is_empty() {
434 return;
435 }
436 if let Ok(mut slot) = title_activity_verb().lock() {
437 if slot.as_str() == verb {
438 return;
439 }
440 verb.clone_into(&mut *slot);
441 }
442 if !TITLE_ANIMATION_RUNNING.load(Ordering::SeqCst) {
443 return;
444 }
445 let base = title_animation_base()
446 .lock()
447 .map_or_else(|_| "codewhale".to_string(), |base| base.clone());
448 set_terminal_title(&title_activity_label(
449 &base,
450 Duration::ZERO,
451 TERMINAL_FOCUSED.load(Ordering::SeqCst),
452 TITLE_MOTION_ENABLED.load(Ordering::SeqCst),
453 ));
454 }
455
456 #[must_use]
457 fn title_activity_label(base: &str, elapsed: Duration, focused: bool, motion: bool) -> String {
458 let verb = title_activity_verb()
459 .lock()
460 .map_or_else(|_| "in the current…".to_string(), |v| v.clone());
461 let body = if verb.is_empty() {
462 base.to_string()
463 } else {
464 verb
465 };
466 // Static title when motion is off or the window is focused: one whale +
467 // state, no competing spinner in the focused app chrome.
468 if !motion || focused {
469 return decorate_title(&format!("🐳 {body}"));
470 }
471 let frame = TITLE_WHALE_FRAMES
472 [(elapsed.as_millis() / TITLE_FRAME_HOLD.as_millis()) as usize % TITLE_WHALE_FRAMES.len()];
473 decorate_title(&format!("{frame} {body}"))
474 }
475
476 /// Apply the `[prefix] ` decoration to a raw window-title body.
477 ///
478 /// With no configured prefix this returns the input unchanged, so existing
479 /// installs keep the exact titles they had before this feature landed.
480 fn decorate_title(raw: &str) -> String {
481 let prefix = title_prefix_slot()
482 .lock()
483 .map_or_else(|_| String::new(), |prefix| prefix.clone());
484 if prefix.is_empty() {
485 raw.to_string()
486 } else {
487 format!("[{prefix}] {raw}")
488 }
489 }
490
491 /// Write OSC 0 (set window title) sequence.
492 fn set_terminal_title(title: &str) {
493 if !stdout_accepts_control_sequences() {
494 return;
495 }
496 let seq = terminal_title_sequence(title);
497 let mut stdout = io::stdout();
498 let _ = stdout.write_all(seq.as_bytes());
499 let _ = stdout.flush();
500 }
501
502 /// Tracks whether the completion marker was set, so
503 /// `reset_title_on_interaction()` can skip redundant writes.
504 static COMPLETION_MARKER_SHOWN: AtomicBool = AtomicBool::new(false);
505
506 /// Mark the terminal title as active with the animated whale + state verb.
507 ///
508 /// While focused (or under reduced motion), the title stays a static whale
509 /// with the current verb. After `FocusLost` with motion enabled, the whale
510 /// frames cycle so alt-tabbed sessions still communicate progress.
511 pub fn start_title_animation(original: &str) {
512 if let Ok(mut base) = title_animation_base().lock() {
513 original.clone_into(&mut base);
514 }
515 if let Ok(mut verb) = title_activity_verb().lock()
516 && verb.is_empty()
517 {
518 "in the current…".clone_into(&mut *verb);
519 }
520 COMPLETION_MARKER_SHOWN.store(false, Ordering::SeqCst);
521 TITLE_ANIMATION_RUNNING.store(true, Ordering::SeqCst);
522 let generation = TITLE_ANIMATION_GENERATION
523 .fetch_add(1, Ordering::SeqCst)
524 .saturating_add(1);
525 let focused = TERMINAL_FOCUSED.load(Ordering::SeqCst);
526 let motion = TITLE_MOTION_ENABLED.load(Ordering::SeqCst);
527 set_terminal_title(&title_activity_label(
528 original,
529 Duration::ZERO,
530 focused,
531 motion,
532 ));
533
534 let base = original.to_string();
535 std::thread::spawn(move || {
536 let started_at = std::time::Instant::now();
537 loop {
538 std::thread::sleep(TITLE_FRAME_HOLD);
539 if !TITLE_ANIMATION_RUNNING.load(Ordering::SeqCst)
540 || TITLE_ANIMATION_GENERATION.load(Ordering::SeqCst) != generation
541 {
542 break;
543 }
544 let motion = TITLE_MOTION_ENABLED.load(Ordering::SeqCst);
545 // Only advance frames when unfocused + motion is on. Focused
546 // windows keep the static whale so the title is not a second
547 // spinner competing with in-app activity chrome.
548 if motion && !TERMINAL_FOCUSED.load(Ordering::SeqCst) {
549 set_terminal_title(&title_activity_label(
550 &base,
551 started_at.elapsed(),
552 false,
553 true,
554 ));
555 }
556 }
557 });
558 }
559
560 /// Update the focus gate used by the title activity signal.
561 ///
562 /// Focus gain immediately restores the steady whale + verb. Focus loss emits
563 /// the first animation frame immediately, then the worker advances it at the
564 /// debounced whale cadence.
565 pub fn set_terminal_focused(focused: bool) {
566 let was_focused = TERMINAL_FOCUSED.swap(focused, Ordering::SeqCst);
567 if focused {
568 UNFOCUSED_SINCE_MS.store(0, Ordering::SeqCst);
569 } else if was_focused {
570 // Only a real focused -> unfocused transition starts the grace period;
571 // duplicate FocusLost reports must not keep postponing delivery.
572 UNFOCUSED_SINCE_MS.store(attention_clock_ms(), Ordering::SeqCst);
573 }
574 if !TITLE_ANIMATION_RUNNING.load(Ordering::SeqCst) {
575 return;
576 }
577 let base = title_animation_base()
578 .lock()
579 .map_or_else(|_| "codewhale".to_string(), |base| base.clone());
580 let motion = TITLE_MOTION_ENABLED.load(Ordering::SeqCst);
581 set_terminal_title(&title_activity_label(
582 &base,
583 Duration::ZERO,
584 focused,
585 motion,
586 ));
587 }
588
589 /// Stop the title animation and show a completion marker.
590 ///
591 /// Sets the title to `✓ done` so alt-tabbed users see at a glance that
592 /// processing finished. The marker is overwritten on the next turn by
593 /// [`start_title_animation`].
594 pub fn stop_title_animation() {
595 stop_title_animation_with(set_terminal_title);
596 }
597
598 fn stop_title_animation_with(set_title: impl FnOnce(&str)) {
599 TITLE_ANIMATION_RUNNING.store(false, Ordering::SeqCst);
600 TITLE_ANIMATION_GENERATION.fetch_add(1, Ordering::SeqCst);
601 // Always show the completion marker so quiet-sound modes still communicate
602 // finish state in the window title; interaction clears it.
603 COMPLETION_MARKER_SHOWN.store(true, Ordering::SeqCst);
604 set_title(&decorate_title("✓ done"));
605 }
606
607 /// Stop the title animation without playing the completion sound.
608 ///
609 /// Cancellation and failed turns should return the terminal title to rest
610 /// without presenting them as completed work.
611 pub fn stop_title_animation_quietly() {
612 TITLE_ANIMATION_RUNNING.store(false, Ordering::SeqCst);
613 TITLE_ANIMATION_GENERATION.fetch_add(1, Ordering::SeqCst);
614 COMPLETION_MARKER_SHOWN.store(false, Ordering::SeqCst);
615 set_terminal_title(&decorate_title("codewhale"));
616 }
617
618 /// Clear the completion marker from the title when the user interacts.
619 ///
620 /// Call this on every user input event (key press, mouse click) so the
621 /// marker doesn't persist once the user is back at the terminal.
622 pub fn reset_title_on_interaction() {
623 if COMPLETION_MARKER_SHOWN.swap(false, Ordering::SeqCst) {
624 set_terminal_title(&decorate_title("codewhale"));
625 }
626 }
627
628 /// Show a macOS Notification Center alert via `osascript`.
629 ///
630 /// Runs on a dedicated background thread so the caller is not blocked.
631 ///
632 /// The notification includes:
633 /// - **Title**: "Codewhale"
634 /// - **Subtitle**: [`NotificationPayload::headline`] (≤ 80 chars)
635 /// - **Body**: [`NotificationPayload::body`] (≤ 322 chars: a ≤ 120-char
636 /// detail, a separator, and a ≤ 200-char preview)
637 /// - **Sound**: none in the AppleScript; the unified notification decision
638 /// dispatches the selected audio cue.
639 ///
640 /// Both fields arrive already sanitized, redacted, and character-bounded
641 /// by [`NotificationPayload`]; this function does not re-derive them from
642 /// free-form text (#4834).
643 ///
644 /// **Security**: The message is passed to `osascript` as a command-line
645 /// argument via `ARGV`, never embedded inline in the AppleScript source.
646 /// AppleScript does not treat backslash as an escape inside double-quoted
647 /// string literals, so the previous `\"` approach would terminate the
648 /// string at the `"` and leave any text between unbalanced quotes
649 /// evaluated as raw AppleScript code — a code-injection vector for
650 /// AI-generated notification text. Passing via `ARGV` avoids this
651 /// entirely because the message is never parsed as AppleScript syntax.
652 /// Keep it that way.
653 ///
654 /// **Attribution**: the banner is posted on behalf of `osascript`, which
655 /// is unbundled, so macOS attributes it to `com.apple.ScriptEditor2`. See
656 /// [`Method::MacOS`] — that is not fixable from here.
657 ///
658 /// This is best-effort: if `osascript` is not available (e.g. headless SSH
659 /// session) the error is logged via `tracing::warn!` instead of silently
660 /// swallowed.
661 #[cfg(target_os = "macos")]
662 const MACOS_DISPLAY_NOTIFICATION_SCRIPT: &str =
663 "display notification theBody with title \"Codewhale\" subtitle theSubtitle";
664
665 #[cfg(all(target_os = "macos", not(test)))]
666 fn macos_display_notification(payload: &NotificationPayload) -> DeliveryOutcome {
667 let (subtitle, body) = macos_notification_parts(payload);
668
669 // Spawn on a background thread so we don't block the caller.
670 // osascript itself is fast (~50 ms), but spawning a subprocess
671 // synchronously from an async context steals a tokio thread.
672 let result = std::thread::Builder::new()
673 .name("osascript-notif".into())
674 .spawn(move || {
675 // Build AppleScript that receives the message via ARGV
676 // instead of inline string interpolation. AppleScript does
677 // not treat backslash as an escape inside double-quoted
678 // string literals, so `\"` would terminate the string at
679 // the `"` and leave a dangling `\`. Passing the message as
680 // a command-line argument avoids any injection risk.
681 let args = [
682 "-e".to_string(),
683 "on run argv".to_string(),
684 "-e".to_string(),
685 "set theBody to item 1 of argv".to_string(),
686 "-e".to_string(),
687 "set theSubtitle to item 2 of argv".to_string(),
688 "-e".to_string(),
689 MACOS_DISPLAY_NOTIFICATION_SCRIPT.to_string(),
690 "-e".to_string(),
691 "end run".to_string(),
692 "--".to_string(),
693 body,
694 subtitle,
695 ];
696
697 match std::process::Command::new("/usr/bin/osascript")
698 .args(&args)
699 .output()
700 {
701 Ok(output) if !output.status.success() => {
702 tracing::warn!("osascript notification failed");
703 }
704 Err(e) => {
705 tracing::warn!(error = %e, "osascript notification error");
706 }
707 _ => {}
708 }
709 });
710 if result.is_ok() {
711 DeliveryOutcome::Dispatched(Method::MacOS)
712 } else {
713 DeliveryOutcome::DeliveryFailed
714 }
715 }
716
717 fn dispatch_native(payload: &NotificationPayload) -> DeliveryOutcome {
718 #[cfg(all(target_os = "macos", not(test)))]
719 {
720 macos_display_notification(payload)
721 }
722 #[cfg(any(not(target_os = "macos"), test))]
723 {
724 let _ = payload;
725 DeliveryOutcome::UnsupportedTransport
726 }
727 }
728
729 /// Split a payload into the `(subtitle, body)` pair `display notification`
730 /// wants. Both halves are already bounded and redacted by the payload
731 /// constructors, so this is a projection, not a sanitizer.
732 #[cfg(target_os = "macos")]
733 fn macos_notification_parts(payload: &NotificationPayload) -> (String, String) {
734 (payload.headline().to_string(), payload.body())
735 }
736
737 // ── Per-turn notification composition ────────────────────────────────
738 //
739 // The helpers below decide *whether* to notify on a completed turn and
740 // *what message* to put in the body. The low-level dispatcher is
741 // `notify_done`; everything in this block sits in front of it.
742
743 use crate::tui::app::App;
744 use codewhale_engine::tools::subagent::SubAgentStatus;
745 use codewhale_localization::{Locale, MessageId, tr};
746 use codewhale_models::{ContentBlock, Message};
747
748 pub fn settings(config: &codewhale_runtime::config::Config) -> Option<(Method, Duration, bool)> {
749 apply_settings(&config.notifications_config())
750 }
751
752 /// Install the process-wide method, gate, sound policy and attention
753 /// condition from `[notifications]`; returns the resolved projection.
754 pub(crate) fn apply_settings(
755 notif: &codewhale_config::notifications::NotificationsConfig,
756 ) -> Option<(Method, Duration, bool)> {
757 // Install the category/quiet gate (#5041) so `notify_done` honors
758 // `[notifications].quiet` and `[notifications.events]`.
759 install_notification_gate(NotificationGate::from_config(notif));
760 codewhale_notify::sound_policy::reconfigure(
761 codewhale_notify::sound_policy::EventSoundPolicy::from_config(notif),
762 );
763 let projection = settings_projection(notif);
764 let method = projection.map_or(Method::Off, |(method, _, _)| method);
765 install_configured_method(method);
766
767 let condition = notif
768 .condition
769 .unwrap_or(codewhale_config::notifications::NotificationCondition::Unfocused);
770 match condition {
771 codewhale_config::notifications::NotificationCondition::Always => {
772 install_attention_condition(AttentionCondition::Always);
773 }
774 codewhale_config::notifications::NotificationCondition::Unfocused => {
775 install_attention_condition(AttentionCondition::Unfocused);
776 }
777 codewhale_config::notifications::NotificationCondition::Never => {
778 install_attention_condition(AttentionCondition::Never);
779 }
780 }
781
782 projection
783 }
784
785 /// Build the notification payload for a completed turn. Prefers the live
786 /// streaming text the user just saw; falls back to the latest assistant
787 /// message in `api_messages` if streaming text is empty (for example, the
788 /// turn finished entirely through tool output). When `include_summary` is
789 /// true, an elapsed/cost suffix is appended to the headline.
790 ///
791 /// The assistant text becomes the payload's *preview*, which means it is
792 /// redacted and capped at 200 characters before it can reach the OS.
793 pub fn completed_turn_payload(
794 app: &App,
795 current_streaming_text: &str,
796 include_summary: bool,
797 turn_elapsed: Duration,
798 turn_cost: Option<codewhale_engine::pricing::CostEstimate>,
799 ) -> NotificationPayload {
800 let headline = completion_status(
801 &tr(app.ui_locale, MessageId::NotificationTurnComplete),
802 include_summary,
803 turn_elapsed,
804 turn_cost.map(|cost| app.format_cost_estimate(cost)),
805 );
806
807 let preview =
808 text_summary(current_streaming_text).or_else(|| latest_assistant_text(&app.api_messages));
809
810 NotificationPayload::turn_complete(&headline).with_preview(preview.as_deref())
811 }
812
813 pub(crate) fn subagent_terminal_label(status: &SubAgentStatus) -> MessageId {
814 match status {
815 SubAgentStatus::Completed => MessageId::NotificationSubagentComplete,
816 SubAgentStatus::Failed(_) => MessageId::NotificationSubagentFailed,
817 SubAgentStatus::Interrupted(_) => MessageId::NotificationSubagentInterrupted,
818 SubAgentStatus::Cancelled => MessageId::NotificationSubagentCancelled,
819 SubAgentStatus::BudgetExhausted => MessageId::NotificationSubagentBudgetExhausted,
820 SubAgentStatus::Running => MessageId::SubagentsStatusRunning,
821 }
822 }
823
824 /// Action-first approval banner (#5041): leads with the decision the user
825 /// must make and names the tool it concerns. The tool *description* — the
826 /// pending command — intentionally stays in the terminal (#4834).
827 #[must_use]
828 pub fn approval_needed_payload(locale: Locale, tool_name: &str) -> NotificationPayload {
829 NotificationPayload::approval_needed(
830 &tr(locale, MessageId::NotificationApprovalNeeded).replace("{tool}", tool_name),
831 tool_name,
832 )
833 }
834
835 /// Action-first blocked-on-input banner (#5041): says what to do and
836 /// where. The question text itself never leaves the terminal (#4834).
837 #[must_use]
838 pub fn input_needed_payload(locale: Locale) -> NotificationPayload {
839 NotificationPayload::input_needed(&tr(locale, MessageId::NotificationInputNeeded))
840 }
841
842 /// Action-first sandbox-elevation banner (#5041): leads with the decision
843 /// and names the blocked tool; the denial reason rides in the body.
844 #[must_use]
845 pub fn elevation_needed_payload(
846 locale: Locale,
847 tool_name: &str,
848 denial_reason: &str,
849 ) -> NotificationPayload {
850 NotificationPayload::elevation_needed(
851 &tr(locale, MessageId::NotificationElevationNeeded).replace("{tool}", tool_name),
852 tool_name,
853 denial_reason,
854 )
855 }
856
857 pub(crate) fn completion_status(
858 label: &str,
859 include_summary: bool,
860 elapsed: Duration,
861 cost: Option<String>,
862 ) -> String {
863 if !include_summary {
864 return label.to_string();
865 }
866
867 let human = codewhale_command_contract::elapsed::format_elapsed_secs(elapsed.as_secs());
868 match cost {
869 Some(cost) => format!("{label} ({human}, {cost})"),
870 None => format!("{label} ({human})"),
871 }
872 }
873
874 /// Find the latest assistant message in `messages` and return a
875 /// notification-ready summary of its `Text` content. Thinking blocks,
876 /// tool calls, and tool results are skipped — only the user-visible
877 /// reply contributes to the body.
878 pub fn latest_assistant_text(messages: &[Message]) -> Option<String> {
879 messages
880 .iter()
881 .rev()
882 .find(|message| {
883 message.role == "assistant"
884 || message.role == codewhale_models::INTERRUPTED_ASSISTANT_ROLE
885 })
886 .and_then(|message| {
887 let text = message
888 .content
889 .iter()
890 .filter_map(|block| match block {
891 ContentBlock::Text { text, .. } => Some(text.as_str()),
892 ContentBlock::Thinking { .. }
893 | ContentBlock::ToolUse { .. }
894 | ContentBlock::ToolResult { .. }
895 | ContentBlock::ServerToolUse { .. }
896 | ContentBlock::ToolSearchToolResult { .. }
897 | ContentBlock::CodeExecutionToolResult { .. }
898 | ContentBlock::WebSearchToolResult { .. }
899 | ContentBlock::WebFetchToolResult { .. }
900 | ContentBlock::WebSearchCall { .. }
901 | ContentBlock::ServerToolCalls { .. }
902 | ContentBlock::File { .. } => None,
903 ContentBlock::ImageUrl { .. } => None,
904 })
905 .collect::<Vec<_>>()
906 .join("\n");
907 text_summary(&text)
908 })
909 }
910
911 /// Sanitize + collapse + truncate streaming text into something fit to
912 /// hand the OS notification system. Returns `None` when nothing
913 /// useful remains after sanitization.
914 pub fn text_summary(text: &str) -> Option<String> {
915 const MAX_CHARS: usize = 360;
916
917 let sanitized = codewhale_sanitize::sanitize::sanitize_stream_chunk(text);
918 let collapsed = sanitized
919 .lines()
920 .map(str::trim)
921 .filter(|line: &&str| !line.is_empty())
922 .collect::<Vec<_>>()
923 .join("\n");
924 let trimmed = collapsed.trim();
925 if trimmed.is_empty() {
926 return None;
927 }
928
929 if let Some((idx, _)) = trimmed.char_indices().nth(MAX_CHARS) {
930 let mut s = String::with_capacity(idx + 3);
931 s.push_str(&trimmed[..idx]);
932 s.push_str("...");
933 Some(s)
934 } else {
935 Some(trimmed.to_string())
936 }
937 }
938
939 #[cfg(test)]
940 mod tests {
941
942 use super::*;
943 use codewhale_notify::DEFAULT_UNFOCUSED_GRACE;
944
945 /// Moved from `tools::notify`: the `notify` tool's emission chain, where
946 /// the installed method decides suppression before any sink write.
947 #[test]
948 fn configured_method_off_silences_the_tool_emission() {
949 let _lock = env_lock();
950 let _restore = ConfiguredMethodRestore::capture();
951 install_configured_method(Method::Off);
952
953 // The emission chain `execute` drives: the installed method decides
954 // suppression before any sink write, with the gate loaded from the
955 // process-wide state.
956 let payload = NotificationPayload::model_notify("done", None);
957 let mut sink = Vec::new();
958 notify_done_to(
959 configured_method(),
960 false,
961 &payload,
962 std::time::Duration::ZERO,
963 std::time::Duration::from_secs(1),
964 current_notification_gate(),
965 &mut sink,
966 );
967 assert!(
968 sink.is_empty(),
969 "configured method=off must silence the notify tool path"
970 );
971 }
972
973 /// The function the host port calls for the `notify` tool must read the
974 /// installed method: `[notifications] method = "off"` silences the tool
975 /// and the receipt says so. A `notify_model` that ignored
976 /// `configured_method()` would pass the test above but fail this one.
977 #[test]
978 fn notify_model_honors_the_installed_off_method() {
979 let _lock = env_lock();
980 let _method_restore = ConfiguredMethodRestore::capture();
981 let _gate_restore = NotificationGateRestore::capture();
982 let previous_condition = current_attention_condition();
983 // `condition = "always"` so the attention policy (checked first) lets
984 // the call reach the method check whatever the test runner's focus.
985 let off: codewhale_runtime::config::Config = toml::from_str(
986 r#"
987 [notifications]
988 method = "off"
989 condition = "always"
990 "#,
991 )
992 .expect("method=off config should parse");
993 let _ = settings(&off);
994
995 let receipt = notify_model("done", Some("all tests pass"));
996
997 install_attention_condition(previous_condition);
998 assert_eq!(receipt, DeliveryOutcome::SuppressedByMethod.receipt());
999 }
1000
1001 #[test]
1002 fn title_whale_is_static_when_focused_or_motion_disabled() {
1003 let _guard = prefix_lock();
1004 if let Ok(mut verb) = title_activity_verb().lock() {
1005 "in the current…".clone_into(&mut *verb);
1006 }
1007 assert_eq!(
1008 title_activity_label("codewhale", Duration::ZERO, true, true),
1009 "🐳 in the current…"
1010 );
1011 assert_eq!(
1012 title_activity_label("codewhale", Duration::ZERO, false, false),
1013 "🐳 in the current…"
1014 );
1015 assert_eq!(
1016 title_activity_label("codewhale", Duration::ZERO, false, true),
1017 "🐳 in the current…"
1018 );
1019 assert_eq!(
1020 title_activity_label("codewhale", Duration::from_millis(800), false, true),
1021 "🐋 in the current…"
1022 );
1023 }
1024
1025 #[test]
1026 fn title_whale_frames_are_the_restored_emoji_pair() {
1027 assert_eq!(TITLE_WHALE_FRAMES, &["🐳", "🐋", "🐳", "🐋"]);
1028 assert_eq!(TITLE_FRAME_HOLD, Duration::from_millis(800));
1029 }
1030
1031 /// Serialise tests that touch the process-global title prefix so parallel
1032 /// threads cannot leak a prefix into an unrelated assertion.
1033 fn prefix_lock() -> std::sync::MutexGuard<'static, ()> {
1034 title_prefix_test_lock()
1035 }
1036
1037 #[test]
1038 fn title_prefix_decorates_activity_label() {
1039 let _guard = prefix_lock();
1040 set_title_prefix(Some("task-7"));
1041 if let Ok(mut verb) = title_activity_verb().lock() {
1042 "reasoning…".clone_into(&mut *verb);
1043 }
1044 assert_eq!(
1045 title_activity_label("codewhale", Duration::ZERO, true, true),
1046 "[task-7] 🐳 reasoning…"
1047 );
1048 assert_eq!(
1049 title_activity_label("codewhale", Duration::ZERO, false, true),
1050 "[task-7] 🐳 reasoning…"
1051 );
1052 set_title_prefix(None);
1053 assert_eq!(
1054 title_activity_label("codewhale", Duration::ZERO, true, true),
1055 "🐳 reasoning…"
1056 );
1057 }
1058
1059 #[test]
1060 fn title_prefix_decorates_rest_and_completion_titles() {
1061 let _guard = prefix_lock();
1062 set_title_prefix(Some("feature/x"));
1063 assert_eq!(decorate_title("codewhale"), "[feature/x] codewhale");
1064 assert_eq!(decorate_title("✓ done"), "[feature/x] ✓ done");
1065 set_title_prefix(None);
1066 assert_eq!(decorate_title("codewhale"), "codewhale");
1067 assert_eq!(decorate_title("✓ done"), "✓ done");
1068 // Empty/whitespace prefixes behave exactly like `None`.
1069 set_title_prefix(Some(" "));
1070 assert_eq!(decorate_title("codewhale"), "codewhale");
1071 set_title_prefix(None);
1072 }
1073
1074 #[test]
1075 fn title_prefix_change_detection_skips_redundant_writes() {
1076 let _guard = prefix_lock();
1077 set_title_prefix(Some("alpha"));
1078 assert_eq!(title_prefix_slot().lock().unwrap().as_str(), "alpha");
1079 // Setting the same prefix again must not clear the stored value.
1080 set_title_prefix(Some("alpha"));
1081 assert_eq!(title_prefix_slot().lock().unwrap().as_str(), "alpha");
1082 set_title_prefix(Some("beta"));
1083 assert_eq!(title_prefix_slot().lock().unwrap().as_str(), "beta");
1084 set_title_prefix(None);
1085 assert_eq!(title_prefix_slot().lock().unwrap().as_str(), "");
1086 }
1087
1088 #[test]
1089 fn set_title_prefix_redraws_without_deadlocking_while_animating() {
1090 // Regression: `set_title_prefix` used to redraw the title while still
1091 // holding the prefix lock. The redraw path (`title_activity_label` →
1092 // `decorate_title`) re-locks the same `Mutex`, and `Mutex` is not
1093 // reentrant — the first `/title` during an active turn froze the
1094 // whole render loop. Exercise the exact path: prefix change while
1095 // the animation worker is running.
1096 let _guard = prefix_lock();
1097 start_title_animation("codewhale");
1098 assert!(TITLE_ANIMATION_RUNNING.load(Ordering::SeqCst));
1099 set_title_prefix(Some("task-7"));
1100 assert_eq!(title_prefix_slot().lock().unwrap().as_str(), "task-7");
1101 set_title_prefix(None);
1102 assert_eq!(title_prefix_slot().lock().unwrap().as_str(), "");
1103 stop_title_animation_quietly();
1104 assert!(!TITLE_ANIMATION_RUNNING.load(Ordering::SeqCst));
1105 }
1106
1107 /// Serialise tests that mutate process-global environment or notification
1108 /// sound state while the test harness runs them in parallel threads.
1109 fn env_lock() -> crate::test_support::TestEnvLock {
1110 crate::test_support::lock_test_env()
1111 }
1112
1113 struct NotificationGateRestore(NotificationGate);
1114
1115 impl NotificationGateRestore {
1116 fn capture() -> Self {
1117 Self(current_notification_gate())
1118 }
1119 }
1120
1121 impl Drop for NotificationGateRestore {
1122 fn drop(&mut self) {
1123 install_notification_gate(self.0);
1124 }
1125 }
1126
1127 /// Escape-protocol tests care about the bytes, not the composition
1128 /// policy, so they go through the least-privileged constructor.
1129 fn capture(
1130 method: Method,
1131 in_tmux: bool,
1132 msg: &str,
1133 threshold_secs: u64,
1134 elapsed_secs: u64,
1135 ) -> Vec<u8> {
1136 let mut buf = Vec::new();
1137 notify_done_to(
1138 method,
1139 in_tmux,
1140 &NotificationPayload::input_needed(msg),
1141 Duration::from_secs(threshold_secs),
1142 Duration::from_secs(elapsed_secs),
1143 NotificationGate::default(),
1144 &mut buf,
1145 );
1146 buf
1147 }
1148
1149 /// Emit `payload` through OSC 9 under an explicit `gate`, returning the
1150 /// bytes. The gate is passed by value, so these tests never touch the
1151 /// process-wide gate and cannot race the other capture tests.
1152 fn capture_gated(payload: &NotificationPayload, gate: NotificationGate) -> Vec<u8> {
1153 let mut buf = Vec::new();
1154 notify_done_to(
1155 Method::Osc9,
1156 false,
1157 payload,
1158 Duration::ZERO,
1159 Duration::from_secs(1),
1160 gate,
1161 &mut buf,
1162 );
1163 buf
1164 }
1165
1166 #[test]
1167 fn gate_defaults_allow_every_kind() {
1168 let gate = NotificationGate::default();
1169 for kind in [
1170 NotificationKind::TurnComplete,
1171 NotificationKind::SubagentTerminal,
1172 NotificationKind::BackgroundTerminal,
1173 NotificationKind::ApprovalNeeded,
1174 NotificationKind::InputNeeded,
1175 NotificationKind::ElevationNeeded,
1176 NotificationKind::ModelNotify,
1177 ] {
1178 assert!(gate.allows(kind), "default gate must allow {kind:?}");
1179 }
1180 }
1181
1182 #[test]
1183 fn quiet_gate_suppresses_every_kind() {
1184 let gate = NotificationGate {
1185 quiet: true,
1186 ..NotificationGate::default()
1187 };
1188 for kind in [
1189 NotificationKind::TurnComplete,
1190 NotificationKind::SubagentTerminal,
1191 NotificationKind::BackgroundTerminal,
1192 NotificationKind::ApprovalNeeded,
1193 NotificationKind::InputNeeded,
1194 NotificationKind::ElevationNeeded,
1195 NotificationKind::ModelNotify,
1196 ] {
1197 assert!(!gate.allows(kind), "quiet gate must suppress {kind:?}");
1198 }
1199 }
1200
1201 #[test]
1202 fn disabled_category_suppresses_only_that_kind() {
1203 let gate = NotificationGate {
1204 approval_needed: false,
1205 ..NotificationGate::default()
1206 };
1207 assert!(!gate.allows(NotificationKind::ApprovalNeeded));
1208 assert!(gate.allows(NotificationKind::TurnComplete));
1209 assert!(gate.allows(NotificationKind::InputNeeded));
1210 assert!(gate.allows(NotificationKind::ModelNotify));
1211 }
1212
1213 #[test]
1214 fn gate_bits_roundtrip_and_default_constant_agree() {
1215 assert_eq!(NotificationGate::default().to_bits(), GATE_DEFAULT_BITS);
1216 let odd = NotificationGate {
1217 quiet: true,
1218 turn_complete: false,
1219 subagent_terminal: true,
1220 approval_needed: false,
1221 input_needed: true,
1222 elevation_needed: false,
1223 model_notify: true,
1224 };
1225 assert_eq!(NotificationGate::from_bits(odd.to_bits()), odd);
1226 }
1227
1228 #[test]
1229 fn background_attention_waits_for_a_real_focus_loss() {
1230 let grace_ms = DEFAULT_UNFOCUSED_GRACE.as_millis() as u64;
1231
1232 assert!(!attention_delivery_allowed_at(
1233 AttentionCondition::Unfocused,
1234 true,
1235 0,
1236 grace_ms + 10,
1237 ));
1238 assert!(!attention_delivery_allowed_at(
1239 AttentionCondition::Unfocused,
1240 false,
1241 0,
1242 grace_ms + 10,
1243 ));
1244 assert!(!attention_delivery_allowed_at(
1245 AttentionCondition::Unfocused,
1246 false,
1247 100,
1248 100 + grace_ms - 1,
1249 ));
1250 assert!(attention_delivery_allowed_at(
1251 AttentionCondition::Unfocused,
1252 false,
1253 100,
1254 100 + grace_ms,
1255 ));
1256 }
1257
1258 #[test]
1259 fn explicit_attention_conditions_override_focus() {
1260 assert!(attention_delivery_allowed_at(
1261 AttentionCondition::Always,
1262 true,
1263 0,
1264 0,
1265 ));
1266 assert!(!attention_delivery_allowed_at(
1267 AttentionCondition::Never,
1268 false,
1269 1,
1270 u64::MAX,
1271 ));
1272 }
1273
1274 #[test]
1275 fn duplicate_focus_lost_does_not_restart_attention_grace() {
1276 let _lock = env_lock();
1277 set_terminal_focused(true);
1278 set_terminal_focused(false);
1279 let first = UNFOCUSED_SINCE_MS.load(Ordering::SeqCst);
1280 assert!(first > 0);
1281
1282 set_terminal_focused(false);
1283 let duplicate = UNFOCUSED_SINCE_MS.load(Ordering::SeqCst);
1284 assert_eq!(duplicate, first);
1285
1286 set_terminal_focused(true);
1287 }
1288
1289 /// The gate acts on the emission path itself: a suppressed category
1290 /// produces zero bytes on every protocol entry point, not just a
1291 /// filtered list somewhere upstream.
1292 #[test]
1293 fn gated_emission_produces_no_bytes() {
1294 let payload = approval_needed_payload(Locale::En, "bash");
1295
1296 let quiet = NotificationGate {
1297 quiet: true,
1298 ..NotificationGate::default()
1299 };
1300 assert!(capture_gated(&payload, quiet).is_empty());
1301
1302 let no_approvals = NotificationGate {
1303 approval_needed: false,
1304 ..NotificationGate::default()
1305 };
1306 assert!(capture_gated(&payload, no_approvals).is_empty());
1307
1308 let out = capture_gated(&payload, NotificationGate::default());
1309 assert!(!out.is_empty(), "enabled category must still emit");
1310 }
1311
1312 #[test]
1313 fn delivery_outcome_reports_why_nothing_was_sent() {
1314 let payload = input_needed_payload(Locale::En);
1315 let mut out = Vec::new();
1316 assert_eq!(
1317 DeliveryOutcome::SuppressedByAttention.receipt(),
1318 "notification not sent: attention policy blocked it"
1319 );
1320 assert_eq!(
1321 notify_done_to(
1322 Method::Off,
1323 false,
1324 &payload,
1325 Duration::ZERO,
1326 Duration::ZERO,
1327 NotificationGate::default(),
1328 &mut out,
1329 ),
1330 DeliveryOutcome::SuppressedByMethod
1331 );
1332 assert_eq!(
1333 DeliveryOutcome::SuppressedByMethod.receipt(),
1334 "notification not sent: notifications are off"
1335 );
1336
1337 assert_eq!(
1338 notify_done_to(
1339 Method::Osc9,
1340 false,
1341 &payload,
1342 Duration::from_secs(30),
1343 Duration::ZERO,
1344 NotificationGate::default(),
1345 &mut out,
1346 ),
1347 DeliveryOutcome::SuppressedByThreshold
1348 );
1349
1350 assert_eq!(
1351 notify_done_to(
1352 Method::Osc9,
1353 false,
1354 &payload,
1355 Duration::ZERO,
1356 Duration::ZERO,
1357 NotificationGate {
1358 quiet: true,
1359 ..NotificationGate::default()
1360 },
1361 &mut out,
1362 ),
1363 DeliveryOutcome::SuppressedByGate
1364 );
1365 assert!(out.is_empty());
1366 }
1367
1368 /// `settings()` is the single place config reaches the emission path;
1369 /// it must install the configured gate for `notify_done` to load.
1370 #[test]
1371 fn settings_installs_gate_from_config() {
1372 let _lock = env_lock();
1373 let _gate_restore = NotificationGateRestore::capture();
1374 let config: codewhale_runtime::config::Config = toml::from_str(
1375 r#"
1376 [notifications]
1377 quiet = true
1378
1379 [notifications.events]
1380 approval-needed = false
1381 "#,
1382 )
1383 .expect("gated notifications config should parse");
1384
1385 let _ = settings(&config);
1386
1387 let gate = current_notification_gate();
1388 assert!(gate.quiet);
1389 assert!(!gate.approval_needed);
1390 assert!(gate.turn_complete);
1391 }
1392
1393 /// Restores the process-wide configured method after a test mutates it.
1394 struct ConfiguredMethodRestore(Method);
1395
1396 impl ConfiguredMethodRestore {
1397 fn capture() -> Self {
1398 Self(configured_method())
1399 }
1400 }
1401
1402 impl Drop for ConfiguredMethodRestore {
1403 fn drop(&mut self) {
1404 install_configured_method(self.0);
1405 }
1406 }
1407
1408 /// Same single-place contract as the gate: `settings()` must install the
1409 /// configured `[notifications].method` so the `notify` tool (which has
1410 /// no method of its own) honors it — including `off` (#1322 promise).
1411 #[test]
1412 fn settings_installs_configured_method_from_config() {
1413 let _lock = env_lock();
1414 let _method_restore = ConfiguredMethodRestore::capture();
1415 let off: codewhale_runtime::config::Config = toml::from_str(
1416 r#"
1417 [notifications]
1418 method = "off"
1419 "#,
1420 )
1421 .expect("method=off config should parse");
1422 let _ = settings(&off);
1423 assert_eq!(configured_method(), Method::Off);
1424
1425 let osc9: codewhale_runtime::config::Config = toml::from_str(
1426 r#"
1427 [notifications]
1428 method = "osc9"
1429 "#,
1430 )
1431 .expect("method=osc9 config should parse");
1432 let _ = settings(&osc9);
1433 assert_eq!(configured_method(), Method::Osc9);
1434 }
1435
1436 /// The installed encoding must round-trip every method so an install/read
1437 /// pair can never silently fall back to `Auto`.
1438 #[test]
1439 fn configured_method_round_trips_every_variant() {
1440 // Serialized with the tests that deliver through the installed method.
1441 let _lock = env_lock();
1442 let _restore = ConfiguredMethodRestore::capture();
1443 for method in [
1444 Method::Auto,
1445 Method::Osc9,
1446 Method::Bel,
1447 Method::MacOS,
1448 Method::Kitty,
1449 Method::Ghostty,
1450 Method::Off,
1451 ] {
1452 install_configured_method(method);
1453 assert_eq!(configured_method(), method);
1454 }
1455 }
1456
1457 /// #5041 copy contract: interactive banners lead with the action and
1458 /// name the subject, instead of a bare "Approval needed".
1459 #[test]
1460 fn interactive_banners_are_action_first_and_name_the_subject() {
1461 let approval = approval_needed_payload(Locale::En, "bash");
1462 assert_eq!(approval.headline(), "Approve or deny 'bash' to continue");
1463
1464 let input = input_needed_payload(Locale::En);
1465 assert_eq!(
1466 input.headline(),
1467 "Answer the question in the terminal to continue"
1468 );
1469
1470 let elevation = elevation_needed_payload(Locale::En, "bash", "network blocked");
1471 assert_eq!(
1472 elevation.headline(),
1473 "Allow or deny elevated access for 'bash'"
1474 );
1475 assert!(elevation.body().contains("network blocked"));
1476 }
1477
1478 #[test]
1479 fn interactive_notification_locales_keep_action_severity_independent_of_tool_text() {
1480 use crate::tui::app::{StatusToast, StatusToastLevel};
1481 let _guard = crate::test_support::lock_test_env();
1482 for &locale in Locale::shipped_complete() {
1483 let mut app = App::new(
1484 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
1485 &codewhale_runtime::config::Config::default(),
1486 );
1487 app.ui_locale = locale;
1488 let tool = "failed";
1489 let payloads = [
1490 (
1491 approval_needed_payload(locale, tool),
1492 MessageId::NotificationApprovalNeeded,
1493 ),
1494 (
1495 input_needed_payload(locale),
1496 MessageId::NotificationInputNeeded,
1497 ),
1498 (
1499 elevation_needed_payload(locale, tool, "network-policy"),
1500 MessageId::NotificationElevationNeeded,
1501 ),
1502 ];
1503 for (index, (payload, key)) in payloads.into_iter().enumerate() {
1504 assert_eq!(payload.headline(), tr(locale, key).replace("{tool}", tool));
1505 app.push_status_toast_record(
1506 StatusToast::new(payload.headline(), StatusToastLevel::Warning, Some(12_000))
1507 .for_action(format!("request-{index}")),
1508 );
1509 app.report_engine_status(payload.headline().into());
1510
1511 assert_eq!(app.status_toasts.len(), index + 1);
1512 let toast = app.status_toasts.back().unwrap();
1513 assert_eq!(toast.level, StatusToastLevel::Warning);
1514 assert_eq!(toast.ttl_ms, Some(12_000));
1515 assert!(app.sticky_status.is_none());
1516 let facts = crate::tui::phase_strip::tideline_footer_from_app(&mut app, 500);
1517 assert_eq!(
1518 facts.right,
1519 Some((
1520 payload.headline().into(),
1521 codewhale_palette::ChromeInk::Attention
1522 ))
1523 );
1524 }
1525 }
1526 }
1527
1528 #[test]
1529 fn osc9_body_format() {
1530 let out = capture(Method::Osc9, false, "codewhale: done", 0, 1);
1531 assert_eq!(out, b"\x1b]9;codewhale: done\x07");
1532 }
1533
1534 #[test]
1535 fn bel_emits_exactly_one_byte() {
1536 let out = capture(Method::Bel, false, "ignored", 0, 1);
1537 assert_eq!(out, b"\x07");
1538 }
1539
1540 #[test]
1541 fn off_mode_emits_nothing() {
1542 let out = capture(Method::Off, false, "ignored", 0, 9999);
1543 assert!(out.is_empty());
1544 }
1545
1546 /// #4847 follow-up: OSC 9;4 and OSC 0 are *control* bytes, not content.
1547 /// A terminal renders nothing visible; a pipe, a file, or a CI log renders
1548 /// them literally — which is why `cargo test` output carried stray
1549 /// `]9;4;1]0;` noise. The write is now gated on stdout being a TTY; these
1550 /// assertions pin the bytes themselves so the gate cannot be "fixed" by
1551 /// quietly changing what gets emitted.
1552 #[test]
1553 fn control_sequences_have_the_exact_documented_bytes() {
1554 assert_eq!(taskbar_progress_sequence(1, None), "\x1b]9;4;1\x07");
1555 assert_eq!(taskbar_progress_sequence(1, Some(42)), "\x1b]9;4;1;42\x07");
1556 assert_eq!(taskbar_progress_sequence(0, None), "\x1b]9;4;0\x07");
1557 assert_eq!(
1558 terminal_title_sequence("🐳 in the current…"),
1559 "\x1b]0;🐳 in the current…\x07"
1560 );
1561 }
1562
1563 #[test]
1564 fn terminal_title_sequence_strips_control_and_bidi_injection() {
1565 assert_eq!(
1566 terminal_title_sequence("safe\u{1b}]2;owned\u{7}\u{202e}title"),
1567 "\x1b]0;safe]2;ownedtitle\x07"
1568 );
1569 let oversized = "x".repeat(MAX_TERMINAL_TITLE_CHARS + 20);
1570 assert_eq!(
1571 terminal_title_sequence(&oversized),
1572 format!("\x1b]0;{}\x07", "x".repeat(MAX_TERMINAL_TITLE_CHARS))
1573 );
1574 }
1575
1576 #[test]
1577 fn terminal_title_sequence_strips_zero_width_and_bidi_marks_but_keeps_cjk() {
1578 // C1 controls (0x9C ST, 0x9D OSC), zero-width joiners/spaces, bidi
1579 // marks and isolates, BOM, soft hyphen, and line separators are all
1580 // dropped; CJK, emoji, and ordinary punctuation survive untouched.
1581 assert_eq!(
1582 terminal_title_sequence(
1583 "会\u{9d}0;議\u{9c}\u{200b}A\u{200f}B\u{061c}C\u{2066}D\u{2069}\u{feff}E\u{00ad}F\u{2028}G 🐳!"
1584 ),
1585 "\x1b]0;会0;議ABCDEFG 🐳!\x07"
1586 );
1587 // Length is bounded by chars, so a CJK title keeps whole characters.
1588 let cjk = "漢".repeat(MAX_TERMINAL_TITLE_CHARS + 5);
1589 assert_eq!(
1590 terminal_title_sequence(&cjk),
1591 format!("\x1b]0;{}\x07", "漢".repeat(MAX_TERMINAL_TITLE_CHARS))
1592 );
1593 }
1594
1595 #[test]
1596 fn title_prefix_change_at_rest_repaints_the_resting_title() {
1597 let _guard = prefix_lock();
1598 TITLE_ANIMATION_RUNNING.store(false, Ordering::SeqCst);
1599 COMPLETION_MARKER_SHOWN.store(false, Ordering::SeqCst);
1600 set_title_prefix(Some("Alpha"));
1601 assert_eq!(decorate_title(resting_title_body()), "[Alpha] codewhale");
1602 COMPLETION_MARKER_SHOWN.store(true, Ordering::SeqCst);
1603 assert_eq!(decorate_title(resting_title_body()), "[Alpha] ✓ done");
1604 COMPLETION_MARKER_SHOWN.store(false, Ordering::SeqCst);
1605 set_title_prefix(None);
1606 assert_eq!(decorate_title(resting_title_body()), "codewhale");
1607 }
1608
1609 #[test]
1610 fn kitty_escape_uses_st_terminator() {
1611 let out = capture(Method::Kitty, false, "done", 0, 1);
1612 let s = String::from_utf8(out).unwrap();
1613 assert!(s.contains("99;"), "should have kitty OSC 99");
1614 assert!(s.contains("\x1b\\"), "kitty uses ST terminator");
1615 assert!(!s.contains("\x07"), "kitty should NOT use BEL");
1616 }
1617
1618 #[test]
1619 fn ghostty_escape_format() {
1620 let out = capture(Method::Ghostty, false, "done", 0, 1);
1621 let s = String::from_utf8(out).unwrap();
1622 assert!(
1623 s.contains("777;notify;codewhale;done"),
1624 "should have ghostty seq"
1625 );
1626 }
1627
1628 #[test]
1629 fn kitty_tmux_dcs_passthrough() {
1630 let out = capture(Method::Kitty, true, "hello", 0, 1);
1631 let s = String::from_utf8(out).unwrap();
1632 assert!(s.starts_with("\x1bPtmux;"), "should start with DCS");
1633 assert!(s.ends_with("\x1b\\"), "should end with ST");
1634 }
1635
1636 #[test]
1637 fn ghostty_tmux_dcs_passthrough() {
1638 let out = capture(Method::Ghostty, true, "hello", 0, 1);
1639 let s = String::from_utf8(out).unwrap();
1640 assert!(s.starts_with("\x1bPtmux;"), "should start with DCS");
1641 assert!(s.ends_with("\x1b\\"), "should end with ST");
1642 }
1643
1644 #[test]
1645 fn below_threshold_emits_nothing() {
1646 let out = capture(Method::Osc9, false, "msg", 30, 29);
1647 assert!(out.is_empty());
1648 }
1649
1650 #[test]
1651 fn at_threshold_emits() {
1652 let out = capture(Method::Osc9, false, "msg", 30, 30);
1653 assert!(!out.is_empty());
1654 }
1655
1656 /// The subtitle is the localized status headline and the body is
1657 /// everything else. Previously this was re-derived by splitting a
1658 /// free-form string on its first newline; now it is a projection of
1659 /// the typed payload, so the split cannot drift from what the
1660 /// composer intended (#4834).
1661 #[cfg(target_os = "macos")]
1662 #[test]
1663 fn macos_notification_keeps_localized_status_as_subtitle() {
1664 let payload = NotificationPayload::turn_complete("ターン完了 (1m 5s)")
1665 .with_preview(Some("完了しました。"));
1666
1667 let (subtitle, body) = macos_notification_parts(&payload);
1668
1669 assert_eq!(subtitle, "ターン完了 (1m 5s)");
1670 assert_eq!(body, "完了しました。");
1671 }
1672
1673 #[cfg(target_os = "macos")]
1674 #[test]
1675 fn macos_banner_does_not_smuggle_in_an_independent_sound() {
1676 assert!(!MACOS_DISPLAY_NOTIFICATION_SCRIPT.contains("sound name"));
1677 assert_eq!(
1678 MACOS_DISPLAY_NOTIFICATION_SCRIPT,
1679 "display notification theBody with title \"Codewhale\" subtitle theSubtitle"
1680 );
1681 }
1682
1683 /// The preview is capped at `PREVIEW_MAX_CHARS` *inclusive* of the
1684 /// ellipsis, so the string handed to `osascript` never exceeds the
1685 /// declared bound.
1686 #[cfg(target_os = "macos")]
1687 #[test]
1688 fn macos_notification_truncates_preview() {
1689 let payload = NotificationPayload::turn_complete("Turn complete")
1690 .with_preview(Some(&"assistant preview ".repeat(40)));
1691
1692 let (subtitle, body) = macos_notification_parts(&payload);
1693
1694 assert_eq!(subtitle, "Turn complete");
1695 assert!(body.starts_with("assistant preview"));
1696 assert!(body.ends_with("..."));
1697 assert_eq!(
1698 body.chars().count(),
1699 codewhale_notify::payload::PREVIEW_MAX_CHARS
1700 );
1701 }
1702
1703 /// #4834: an approval banner is the one place a raw shell command
1704 /// used to reach Notification Center. Pin the macOS projection, not
1705 /// just the payload, so a future refactor of either half is caught.
1706 #[cfg(target_os = "macos")]
1707 #[test]
1708 fn macos_approval_notification_never_carries_the_command() {
1709 let payload = NotificationPayload::approval_needed("Approval needed", "bash");
1710
1711 let (subtitle, body) = macos_notification_parts(&payload);
1712
1713 assert_eq!(subtitle, "Approval needed");
1714 assert_eq!(body, "bash");
1715 }
1716
1717 #[test]
1718 fn tmux_dcs_passthrough_wraps_osc9() {
1719 let out = capture(Method::Osc9, true, "hello", 0, 1);
1720 let s = String::from_utf8(out).unwrap();
1721 assert!(
1722 s.starts_with("\x1bPtmux;"),
1723 "should start with DCS passthrough"
1724 );
1725 assert!(s.ends_with("\x1b\\"), "should end with ST");
1726 assert!(s.contains("hello"), "should contain message");
1727 }
1728
1729 #[test]
1730 fn auto_detect_picks_osc9_for_iterm() {
1731 let _lock = env_lock();
1732 let prev = std::env::var_os("TERM_PROGRAM");
1733 // SAFETY: test-only; serialised by env_lock().
1734 unsafe { std::env::set_var("TERM_PROGRAM", "iTerm.app") };
1735 let resolved = resolve_method();
1736 // Restore previous value.
1737 // SAFETY: test-only; serialised by env_lock().
1738 unsafe {
1739 match prev {
1740 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1741 None => std::env::remove_var("TERM_PROGRAM"),
1742 }
1743 }
1744 assert_eq!(resolved, Method::Osc9);
1745 }
1746
1747 /// Cmux in typical configurations does not set `TERM_PROGRAM`; it sets
1748 /// `LC_TERMINAL=Cmux` instead. Verify the `LC_TERMINAL` fallback probe
1749 /// correctly resolves to `Osc9`.
1750 #[test]
1751 fn auto_detect_picks_osc9_for_cmux_via_lc_terminal() {
1752 let _lock = env_lock();
1753 let prev_tp = std::env::var_os("TERM_PROGRAM");
1754 let prev_lc = std::env::var_os("LC_TERMINAL");
1755 // SAFETY: test-only; serialised by env_lock().
1756 unsafe {
1757 std::env::remove_var("TERM_PROGRAM");
1758 std::env::set_var("LC_TERMINAL", "Cmux");
1759 }
1760 let resolved = resolve_method();
1761 // SAFETY: test-only; serialised by env_lock().
1762 unsafe {
1763 match prev_tp {
1764 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1765 None => std::env::remove_var("TERM_PROGRAM"),
1766 }
1767 match prev_lc {
1768 Some(v) => std::env::set_var("LC_TERMINAL", v),
1769 None => std::env::remove_var("LC_TERMINAL"),
1770 }
1771 }
1772 assert_eq!(resolved, Method::Osc9);
1773 }
1774
1775 /// `LC_TERMINAL` should also match other OSC-9 capable terminals in case
1776 /// they set it in addition to or instead of `TERM_PROGRAM`.
1777 #[test]
1778 fn auto_detect_picks_osc9_for_wezterm_via_lc_terminal() {
1779 let _lock = env_lock();
1780 let prev_tp = std::env::var_os("TERM_PROGRAM");
1781 let prev_lc = std::env::var_os("LC_TERMINAL");
1782 // SAFETY: test-only; serialised by env_lock().
1783 unsafe {
1784 std::env::remove_var("TERM_PROGRAM");
1785 std::env::set_var("LC_TERMINAL", "WezTerm");
1786 }
1787 let resolved = resolve_method();
1788 // SAFETY: test-only; serialised by env_lock().
1789 unsafe {
1790 match prev_tp {
1791 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1792 None => std::env::remove_var("TERM_PROGRAM"),
1793 }
1794 match prev_lc {
1795 Some(v) => std::env::set_var("LC_TERMINAL", v),
1796 None => std::env::remove_var("LC_TERMINAL"),
1797 }
1798 }
1799 assert_eq!(resolved, Method::Osc9);
1800 }
1801
1802 #[test]
1803 #[cfg(not(any(target_os = "windows", target_os = "macos")))]
1804 fn auto_detect_stays_silent_for_unknown_on_unix() {
1805 let _lock = env_lock();
1806 let prev_tp = std::env::var_os("TERM_PROGRAM");
1807 let prev_lc = std::env::var_os("LC_TERMINAL");
1808 let prev_term = std::env::var_os("TERM");
1809 // SAFETY: test-only; serialised by env_lock().
1810 // Clear LC_TERMINAL and TERM so the fallback probes don't
1811 // accidentally pick up an OSC-9 / Kitty / Ghostty capable
1812 // terminal from the test runner environment.
1813 unsafe {
1814 std::env::set_var("TERM_PROGRAM", "xterm-256color");
1815 std::env::remove_var("LC_TERMINAL");
1816 std::env::set_var("TERM", "xterm-256color");
1817 }
1818 let resolved = resolve_method();
1819 // SAFETY: test-only; serialised by env_lock().
1820 unsafe {
1821 match prev_tp {
1822 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1823 None => std::env::remove_var("TERM_PROGRAM"),
1824 }
1825 match prev_lc {
1826 Some(v) => std::env::set_var("LC_TERMINAL", v),
1827 None => std::env::remove_var("LC_TERMINAL"),
1828 }
1829 match prev_term {
1830 Some(v) => std::env::set_var("TERM", v),
1831 None => std::env::remove_var("TERM"),
1832 }
1833 }
1834 assert_eq!(resolved, Method::Off);
1835 }
1836
1837 /// Unknown Windows terminals must not turn an automatic banner request
1838 /// into an audible system sound.
1839 #[test]
1840 #[cfg(target_os = "windows")]
1841 fn auto_detect_stays_silent_for_unknown_on_windows() {
1842 let _lock = env_lock();
1843 let prev = std::env::var_os("TERM_PROGRAM");
1844 // SAFETY: test-only; serialised by env_lock().
1845 unsafe { std::env::set_var("TERM_PROGRAM", "Windows Terminal") };
1846 let resolved = resolve_method();
1847 // SAFETY: test-only; serialised by env_lock().
1848 unsafe {
1849 match prev {
1850 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1851 None => std::env::remove_var("TERM_PROGRAM"),
1852 }
1853 }
1854 assert_eq!(resolved, Method::Off);
1855 }
1856
1857 /// #583: known OSC-9 terminals must still resolve to `Osc9` on
1858 /// Windows — the off-fallback only applies to unrecognised
1859 /// `TERM_PROGRAM`. The cross-platform iTerm test above is a thin
1860 /// proxy because iTerm itself only runs on macOS; if the WezTerm
1861 /// arm of the match silently disappeared, that test would still
1862 /// pass on the Windows runner and we'd lose the WezTerm-on-Windows
1863 /// compatibility guarantee. Pin it directly.
1864 #[test]
1865 #[cfg(target_os = "windows")]
1866 fn auto_detect_picks_osc9_for_wezterm_on_windows() {
1867 let _lock = env_lock();
1868 let prev = std::env::var_os("TERM_PROGRAM");
1869 // SAFETY: test-only; serialised by env_lock().
1870 unsafe { std::env::set_var("TERM_PROGRAM", "WezTerm") };
1871 let resolved = resolve_method();
1872 // SAFETY: test-only; serialised by env_lock().
1873 unsafe {
1874 match prev {
1875 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1876 None => std::env::remove_var("TERM_PROGRAM"),
1877 }
1878 }
1879 assert_eq!(resolved, Method::Osc9);
1880 }
1881
1882 /// Ghostty-based terminals (cmux, etc.) may not set
1883 /// `TERM_PROGRAM` but do set `TERM=xterm-ghostty`. The `$TERM`
1884 /// fallback should catch them.
1885 #[test]
1886 #[cfg(not(any(target_os = "windows", target_os = "macos")))]
1887 fn auto_detect_picks_osc9_for_xterm_ghostty_term_fallback() {
1888 let _lock = env_lock();
1889 let prev_tp = std::env::var_os("TERM_PROGRAM");
1890 let prev_lc = std::env::var_os("LC_TERMINAL");
1891 let prev_term = std::env::var_os("TERM");
1892 // Simulate a Ghostty-based terminal that only sets TERM.
1893 // SAFETY: test-only; serialised by env_lock().
1894 unsafe {
1895 std::env::remove_var("TERM_PROGRAM");
1896 std::env::remove_var("LC_TERMINAL");
1897 std::env::set_var("TERM", "xterm-ghostty");
1898 }
1899 let resolved = resolve_method();
1900 // SAFETY: test-only; serialised by env_lock().
1901 unsafe {
1902 match prev_tp {
1903 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1904 None => std::env::remove_var("TERM_PROGRAM"),
1905 }
1906 match prev_lc {
1907 Some(v) => std::env::set_var("LC_TERMINAL", v),
1908 None => std::env::remove_var("LC_TERMINAL"),
1909 }
1910 match prev_term {
1911 Some(v) => std::env::set_var("TERM", v),
1912 None => std::env::remove_var("TERM"),
1913 }
1914 }
1915 assert_eq!(resolved, Method::Osc9);
1916 }
1917
1918 /// Ghostty now has its own protocol (OSC 777).
1919 #[test]
1920 fn auto_detect_picks_ghostty_from_term_program() {
1921 let _lock = env_lock();
1922 let prev = std::env::var_os("TERM_PROGRAM");
1923 // SAFETY: test-only; serialised by env_lock().
1924 unsafe { std::env::set_var("TERM_PROGRAM", "Ghostty") };
1925 let resolved = resolve_method();
1926 // SAFETY: test-only; serialised by env_lock().
1927 unsafe {
1928 match prev {
1929 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1930 None => std::env::remove_var("TERM_PROGRAM"),
1931 }
1932 }
1933 assert_eq!(resolved, Method::Ghostty);
1934 }
1935
1936 #[test]
1937 fn auto_detect_picks_kitty_from_term_program() {
1938 let _lock = env_lock();
1939 let prev = std::env::var_os("TERM_PROGRAM");
1940 // SAFETY: test-only; serialised by env_lock().
1941 unsafe { std::env::set_var("TERM_PROGRAM", "kitty") };
1942 let resolved = resolve_method();
1943 // SAFETY: test-only; serialised by env_lock().
1944 unsafe {
1945 match prev {
1946 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1947 None => std::env::remove_var("TERM_PROGRAM"),
1948 }
1949 }
1950 assert_eq!(resolved, Method::Kitty);
1951 }
1952
1953 #[test]
1954 #[cfg(not(any(target_os = "windows", target_os = "macos")))]
1955 fn auto_detect_picks_kitty_from_term_fallback() {
1956 let _lock = env_lock();
1957 let prev_tp = std::env::var_os("TERM_PROGRAM");
1958 let prev_lc = std::env::var_os("LC_TERMINAL");
1959 let prev_term = std::env::var_os("TERM");
1960 // SAFETY: test-only; serialised by env_lock().
1961 unsafe {
1962 std::env::remove_var("TERM_PROGRAM");
1963 std::env::remove_var("LC_TERMINAL");
1964 std::env::set_var("TERM", "xterm-kitty");
1965 }
1966 let resolved = resolve_method();
1967 // SAFETY: test-only; serialised by env_lock().
1968 unsafe {
1969 match prev_tp {
1970 Some(v) => std::env::set_var("TERM_PROGRAM", v),
1971 None => std::env::remove_var("TERM_PROGRAM"),
1972 }
1973 match prev_lc {
1974 Some(v) => std::env::set_var("LC_TERMINAL", v),
1975 None => std::env::remove_var("LC_TERMINAL"),
1976 }
1977 match prev_term {
1978 Some(v) => std::env::set_var("TERM", v),
1979 None => std::env::remove_var("TERM"),
1980 }
1981 }
1982 assert_eq!(resolved, Method::Kitty);
1983 }
1984
1985 /// When neither `TERM_PROGRAM` nor `TERM` suggests a known capable
1986 /// terminal, automatic delivery fails closed rather than ringing BEL.
1987 ///
1988 /// On macOS the `MacOS` method takes priority, so this test is
1989 /// excluded there.
1990 #[test]
1991 #[cfg(not(any(target_os = "windows", target_os = "macos")))]
1992 fn auto_detect_falls_back_to_off_for_unrelated_term() {
1993 let _lock = env_lock();
1994 let prev_tp = std::env::var_os("TERM_PROGRAM");
1995 let prev_lc = std::env::var_os("LC_TERMINAL");
1996 let prev_term = std::env::var_os("TERM");
1997 // SAFETY: test-only; serialised by env_lock().
1998 unsafe {
1999 std::env::remove_var("TERM_PROGRAM");
2000 std::env::remove_var("LC_TERMINAL");
2001 std::env::set_var("TERM", "xterm-256color");
2002 }
2003 let resolved = resolve_method();
2004 // SAFETY: test-only; serialised by env_lock().
2005 unsafe {
2006 match prev_tp {
2007 Some(v) => std::env::set_var("TERM_PROGRAM", v),
2008 None => std::env::remove_var("TERM_PROGRAM"),
2009 }
2010 match prev_lc {
2011 Some(v) => std::env::set_var("LC_TERMINAL", v),
2012 None => std::env::remove_var("LC_TERMINAL"),
2013 }
2014 match prev_term {
2015 Some(v) => std::env::set_var("TERM", v),
2016 None => std::env::remove_var("TERM"),
2017 }
2018 }
2019 assert_eq!(resolved, Method::Off);
2020 }
2021 }
2022
2023 // ---------------------------------------------------------------------------
2024 // Tideline notifications inbox (spec §5a "Notifications inbox"): the
2025 // attention surface that replaces the toast soup. Records are typed — the
2026 // same `NotificationKind` disclosure policy the desktop payloads use — and
2027 // the unread mark is the sanctioned gold ◆. Translation scaffolding in the
2028 // topbar mold: a pure deterministic widget over injected records (`App`
2029 // projects `status_toasts`/`sticky_status` into it at the landing slice);
2030 // not wired into `ui/frame.rs` (#5698 gate).
2031
2032 #[cfg(test)]
2033 use ratatui::{
2034 buffer::Buffer,
2035 layout::Rect,
2036 style::{Modifier, Style},
2037 };
2038 #[cfg(test)]
2039 use unicode_width::UnicodeWidthStr;
2040
2041 #[cfg(test)]
2042 use codewhale_palette::{ChromeInk, UiTheme, chrome_style};
2043
2044 /// One attention record: a typed projection of a status toast / sticky
2045 /// status / desktop payload. `at` is an injected clock string so renders
2046 /// stay deterministic (spec §5a: caller owns the wall clock).
2047 #[derive(Debug, Clone)]
2048 #[cfg(test)] // translation scaffolding: wired by the landing slice
2049 pub struct TidelineInboxRecord {
2050 pub kind: NotificationKind,
2051 pub title: String,
2052 /// One-line body, already disclosure-approved per kind.
2053 pub body: Option<String>,
2054 /// Wall-clock label, e.g. `14:42`.
2055 pub at: String,
2056 pub read: bool,
2057 }
2058
2059 #[cfg(test)]
2060 impl TidelineInboxRecord {
2061 /// Kind word — a noun, never "Error" (spec §7 failure microcopy rule).
2062 #[must_use]
2063 pub fn kind_word(&self) -> &'static str {
2064 match self.kind {
2065 NotificationKind::TurnComplete => "turn done",
2066 NotificationKind::SubagentTerminal => "whale done",
2067 NotificationKind::BackgroundTerminal => "work done",
2068 NotificationKind::ApprovalNeeded => "approval",
2069 NotificationKind::InputNeeded => "question",
2070 NotificationKind::ElevationNeeded => "sandbox",
2071 NotificationKind::ModelNotify => "notify",
2072 }
2073 }
2074
2075 /// Per-kind ink per the §5d table: interactive asks read as cognition
2076 /// (permission family), completions as outcome, terminal whales as info.
2077 #[must_use]
2078 pub fn kind_ink(&self) -> ChromeInk {
2079 match self.kind {
2080 NotificationKind::TurnComplete => ChromeInk::Outcome,
2081 NotificationKind::SubagentTerminal | NotificationKind::BackgroundTerminal => {
2082 ChromeInk::Info
2083 }
2084 NotificationKind::ApprovalNeeded | NotificationKind::InputNeeded => {
2085 ChromeInk::PermissionAsk
2086 }
2087 NotificationKind::ElevationNeeded => ChromeInk::PermissionFullAccess,
2088 NotificationKind::ModelNotify => ChromeInk::MetadataValue,
2089 }
2090 }
2091 }
2092
2093 /// What the caller owes the inbox render.
2094 #[cfg(test)] // translation scaffolding: wired by the landing slice
2095 pub struct TidelineInbox<'a> {
2096 pub theme: &'a UiTheme,
2097 pub records: &'a [TidelineInboxRecord],
2098 /// Selected row (Enter inspects, `r` marks read, Esc backs out).
2099 pub selected: usize,
2100 pub ascii_safe: bool,
2101 }
2102
2103 #[cfg(test)] // translation scaffolding: builder methods feed tests + the landing slice
2104 impl<'a> TidelineInbox<'a> {
2105 #[must_use]
2106 pub fn new(theme: &'a UiTheme, records: &'a [TidelineInboxRecord]) -> Self {
2107 Self {
2108 theme,
2109 records,
2110 selected: 0,
2111 ascii_safe: false,
2112 }
2113 }
2114
2115 #[must_use]
2116 pub fn selected(mut self, selected: usize) -> Self {
2117 self.selected = selected;
2118 self
2119 }
2120
2121 #[must_use]
2122 pub fn ascii_safe(mut self, ascii_safe: bool) -> Self {
2123 self.ascii_safe = ascii_safe;
2124 self
2125 }
2126
2127 fn sym(&self, glyph: &str) -> String {
2128 if !self.ascii_safe {
2129 return glyph.to_string();
2130 }
2131 if let Some(fb) = codewhale_tui_kit::glyphs::ascii_fallback(glyph) {
2132 return fb.to_string();
2133 }
2134 glyph
2135 .chars()
2136 .map(|c| {
2137 codewhale_tui_kit::glyphs::ascii_fallback(&c.to_string())
2138 .map(str::to_string)
2139 .unwrap_or_else(|| c.to_string())
2140 })
2141 .collect()
2142 }
2143 }
2144
2145 #[cfg(test)]
2146 fn chrome(theme: &UiTheme, ink: ChromeInk) -> Style {
2147 chrome_style(theme, ink)
2148 }
2149
2150 #[cfg(test)]
2151 fn put(buf: &mut Buffer, x: u16, y: u16, text: &str, style: Style) {
2152 buf.set_stringn(x, y, text, text.width(), style);
2153 }
2154
2155 /// Paint the notifications inbox: header row (count of unread), then one
2156 /// row per record — unread gold ◆, read hollow ○, selected `▸`, kind word,
2157 /// title, injected time. Truncates, never wraps.
2158 #[cfg(test)] // translation scaffolding: wired by the landing slice
2159 pub fn render_tideline_inbox(area: Rect, buf: &mut Buffer, inbox: &TidelineInbox<'_>) {
2160 if area.width < 8 || area.height < 2 {
2161 return;
2162 }
2163 let theme = inbox.theme;
2164 let unread = inbox.records.iter().filter(|record| !record.read).count();
2165 let header = if unread == 0 {
2166 "NOTIFICATIONS".to_string()
2167 } else {
2168 format!("NOTIFICATIONS · {unread} unread")
2169 };
2170 put(
2171 buf,
2172 area.x,
2173 area.y,
2174 &header,
2175 chrome(theme, ChromeInk::Metadata).add_modifier(Modifier::BOLD),
2176 );
2177
2178 if inbox.records.is_empty() {
2179 put(
2180 buf,
2181 area.x,
2182 area.y + 1,
2183 "quiet water — nothing needs you",
2184 chrome(theme, ChromeInk::MetadataHint),
2185 );
2186 return;
2187 }
2188
2189 let width = area.width as usize;
2190 let mut y = area.y + 1;
2191 for (index, record) in inbox.records.iter().enumerate() {
2192 if y >= area.y + area.height {
2193 break;
2194 }
2195 let selected = inbox.selected == index;
2196 let marker = if selected { "▸ " } else { " " };
2197 let mark = if record.read { "○" } else { "◆" };
2198 let mark_ink = if record.read {
2199 ChromeInk::MetadataDim
2200 } else {
2201 ChromeInk::Attention
2202 };
2203 let row = format!("{} {} — {}", record.kind_word(), record.title, record.at);
2204 let row = truncate_to_width_owned(&inbox.sym(&row), width.saturating_sub(6));
2205 put(
2206 buf,
2207 area.x + 2,
2208 y,
2209 &inbox.sym(marker),
2210 chrome(theme, ChromeInk::Identity),
2211 );
2212 put(
2213 buf,
2214 area.x + 4,
2215 y,
2216 &inbox.sym(mark),
2217 chrome(theme, mark_ink),
2218 );
2219 let mut style = chrome(theme, record.kind_ink());
2220 if record.read {
2221 style = chrome(theme, ChromeInk::MetadataDim);
2222 }
2223 if selected {
2224 style = style.add_modifier(Modifier::BOLD);
2225 }
2226 put(buf, area.x + 6, y, &row, style);
2227 // The selected record's approved body earns its own indented row —
2228 // the inspect affordance; other bodies stay collapsed.
2229 if selected
2230 && let Some(body) = record.body.as_deref()
2231 && y + 1 < area.y + area.height
2232 {
2233 put(
2234 buf,
2235 area.x + 8,
2236 y + 1,
2237 &truncate_to_width_owned(&inbox.sym(body), width.saturating_sub(10)),
2238 chrome(theme, ChromeInk::MetadataHint),
2239 );
2240 y += 1;
2241 }
2242 y += 1;
2243 }
2244 }
2245
2246 #[cfg(test)]
2247 fn truncate_to_width_owned(text: &str, width: usize) -> String {
2248 let mut out = String::new();
2249 let mut used = 0;
2250 for ch in text.chars() {
2251 let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
2252 if used + w > width {
2253 break;
2254 }
2255 out.push(ch);
2256 used += w;
2257 }
2258 out
2259 }
2260
2261 /// Row hitboxes for one render (spec §6): one rect per record, matching the
2262 /// painted rows exactly — the selected record's body row belongs to its
2263 /// rect. Must be called with the same inputs as [`render_tideline_inbox`].
2264 #[must_use]
2265 #[cfg(test)] // translation scaffolding: wired by the landing slice
2266 pub fn tideline_inbox_hitboxes(area: Rect, inbox: &TidelineInbox<'_>) -> Vec<Rect> {
2267 let mut out = Vec::new();
2268 if area.width < 8 || area.height < 2 {
2269 return out;
2270 }
2271 let mut y = area.y + 1;
2272 for (index, record) in inbox.records.iter().enumerate() {
2273 let mut height = 1;
2274 if inbox.selected == index && record.body.is_some() {
2275 height = 2;
2276 }
2277 if y + height > area.y + area.height {
2278 break;
2279 }
2280 out.push(Rect {
2281 x: area.x + 2,
2282 y,
2283 width: area.width.saturating_sub(2),
2284 height,
2285 });
2286 y += height;
2287 }
2288 out
2289 }
2290
2291 #[cfg(test)]
2292 mod tideline_tests;
2293
2294 #[cfg(test)]
2295 mod unified_audio_tests {
2296 use super::*;
2297 use codewhale_config::notifications::{
2298 CompletionSound, NotificationConfigUpdate, NotificationsConfig,
2299 };
2300 use codewhale_notify::audio::AudioOutcome;
2301 use codewhale_notify::sound_policy::{self, EventSoundPolicy, SoundCue, SoundDecision};
2302
2303 fn payloads() -> [NotificationPayload; 6] {
2304 [
2305 NotificationPayload::turn_complete("done"),
2306 NotificationPayload::subagent_terminal("done", "a"),
2307 NotificationPayload::approval_needed("approve", "shell"),
2308 NotificationPayload::input_needed("answer"),
2309 NotificationPayload::elevation_needed("access", "shell", "denied"),
2310 NotificationPayload::model_notify("notice", None),
2311 ]
2312 }
2313
2314 #[test]
2315 fn every_gate_blocks_terminal_native_audio_and_the_repeat_clock() {
2316 for payload in payloads() {
2317 let mut disabled = NotificationsConfig::default();
2318 disabled
2319 .apply_update(NotificationConfigUpdate::Event(
2320 sound_policy::event_for_kind(payload.kind()),
2321 false,
2322 ))
2323 .unwrap();
2324 for method in [Method::Kitty, Method::MacOS, Method::Bel] {
2325 for (selected, gate, attention, threshold, expected) in [
2326 (
2327 Method::Off,
2328 NotificationGate::default(),
2329 true,
2330 Duration::ZERO,
2331 DeliveryOutcome::SuppressedByMethod,
2332 ),
2333 (
2334 method,
2335 NotificationGate {
2336 quiet: true,
2337 ..Default::default()
2338 },
2339 true,
2340 Duration::ZERO,
2341 DeliveryOutcome::SuppressedByGate,
2342 ),
2343 (
2344 method,
2345 NotificationGate::from_config(&disabled),
2346 true,
2347 Duration::ZERO,
2348 DeliveryOutcome::SuppressedByGate,
2349 ),
2350 (
2351 method,
2352 NotificationGate::default(),
2353 false,
2354 Duration::ZERO,
2355 DeliveryOutcome::SuppressedByAttention,
2356 ),
2357 (
2358 method,
2359 NotificationGate::default(),
2360 true,
2361 Duration::from_secs(2),
2362 DeliveryOutcome::SuppressedByThreshold,
2363 ),
2364 ] {
2365 let mut out = Vec::new();
2366 let result = notify_with_sinks(
2367 selected,
2368 false,
2369 &payload,
2370 threshold,
2371 Duration::from_secs(1),
2372 gate,
2373 attention,
2374 &mut out,
2375 &mut |_, _| panic!("suppressed event reached sound decision"),
2376 &mut |_, _| panic!("suppressed event reached audio"),
2377 &mut |_| panic!("suppressed event reached native banner"),
2378 );
2379 assert_eq!(result, expected);
2380 assert!(out.is_empty());
2381 }
2382 }
2383 }
2384 }
2385
2386 #[test]
2387 fn explicit_bell_transport_and_selected_whale_emit_only_one_cue() {
2388 for payload in payloads() {
2389 let mut policy = EventSoundPolicy::from_config(&NotificationsConfig {
2390 sound: Some(CompletionSound::Whale),
2391 ..Default::default()
2392 });
2393 let mut out = Vec::new();
2394 let mut cues = Vec::new();
2395 let result = notify_with_sinks(
2396 Method::Bel,
2397 false,
2398 &payload,
2399 Duration::ZERO,
2400 Duration::ZERO,
2401 NotificationGate::default(),
2402 true,
2403 &mut out,
2404 &mut |kind, bell| policy.decide(sound_policy::event_for_kind(kind), 0, bell),
2405 &mut |cue, _| {
2406 cues.push(cue.clone());
2407 AudioOutcome::Dispatched
2408 },
2409 &mut |_| panic!("audio-only transport reached native banner"),
2410 );
2411 assert_eq!(result, DeliveryOutcome::Dispatched(Method::Bel));
2412 assert_eq!(cues, [SoundCue::Whale]);
2413 assert!(out.is_empty(), "no second transport BEL");
2414 }
2415 }
2416
2417 #[test]
2418 fn audio_off_keeps_banner_but_silences_bell_transport() {
2419 for method in [Method::Kitty, Method::Bel] {
2420 let mut policy = EventSoundPolicy::from_config(&NotificationsConfig {
2421 sound: Some(CompletionSound::Off),
2422 completion_sound: CompletionSound::Bell,
2423 ..Default::default()
2424 });
2425 let mut out = Vec::new();
2426 let result = notify_with_sinks(
2427 method,
2428 false,
2429 &NotificationPayload::turn_complete("done"),
2430 Duration::ZERO,
2431 Duration::ZERO,
2432 NotificationGate::default(),
2433 true,
2434 &mut out,
2435 &mut |kind, bell| policy.decide(sound_policy::event_for_kind(kind), 0, bell),
2436 &mut |_, _| panic!("off reached audio"),
2437 &mut |_| panic!("unexpected native"),
2438 );
2439 assert_eq!(
2440 result,
2441 if method == Method::Bel {
2442 DeliveryOutcome::SuppressedBySound
2443 } else {
2444 DeliveryOutcome::Delivered(method)
2445 }
2446 );
2447 assert!(!out.contains(&7));
2448 }
2449 }
2450
2451 #[test]
2452 fn unsupported_failed_and_busy_audio_have_truthful_receipts_without_fallback() {
2453 for (audio_result, expected) in [
2454 (
2455 AudioOutcome::Unsupported,
2456 DeliveryOutcome::UnsupportedTransport,
2457 ),
2458 (AudioOutcome::Failed, DeliveryOutcome::DeliveryFailed),
2459 (AudioOutcome::Busy, DeliveryOutcome::SuppressedBySound),
2460 ] {
2461 let mut out = Vec::new();
2462 let mut count = 0;
2463 let result = notify_with_sinks(
2464 Method::Bel,
2465 false,
2466 &NotificationPayload::input_needed("answer"),
2467 Duration::ZERO,
2468 Duration::ZERO,
2469 NotificationGate::default(),
2470 true,
2471 &mut out,
2472 &mut |_, _| SoundDecision::Play(SoundCue::Whale),
2473 &mut |_, _| {
2474 count += 1;
2475 audio_result
2476 },
2477 &mut |_| panic!("unexpected native"),
2478 );
2479 assert_eq!(result, expected);
2480 assert_eq!(count, 1);
2481 assert!(out.is_empty());
2482 }
2483 }
2484
2485 #[test]
2486 fn native_failure_and_terminal_failure_do_not_trigger_orphan_audio() {
2487 struct Broken;
2488 impl Write for Broken {
2489 fn write(&mut self, _: &[u8]) -> io::Result<usize> {
2490 Err(io::Error::other("injected"))
2491 }
2492 fn flush(&mut self) -> io::Result<()> {
2493 Ok(())
2494 }
2495 }
2496 for method in [Method::Kitty, Method::MacOS] {
2497 let result = notify_with_sinks(
2498 method,
2499 false,
2500 &NotificationPayload::input_needed("answer"),
2501 Duration::ZERO,
2502 Duration::ZERO,
2503 NotificationGate::default(),
2504 true,
2505 &mut Broken,
2506 &mut |_, _| panic!("failed delivery reached policy"),
2507 &mut |_, _| panic!("failed delivery reached audio"),
2508 &mut |_| DeliveryOutcome::DeliveryFailed,
2509 );
2510 assert_eq!(result, DeliveryOutcome::DeliveryFailed);
2511 }
2512 }
2513
2514 #[test]
2515 fn native_worker_receipt_does_not_claim_os_acceptance() {
2516 let mut out = Vec::new();
2517 let mut cues = 0;
2518 let result = notify_with_sinks(
2519 Method::MacOS,
2520 false,
2521 &NotificationPayload::input_needed("answer"),
2522 Duration::ZERO,
2523 Duration::ZERO,
2524 NotificationGate::default(),
2525 true,
2526 &mut out,
2527 &mut |_, _| SoundDecision::Play(SoundCue::Whale),
2528 &mut |_, _| {
2529 cues += 1;
2530 AudioOutcome::Dispatched
2531 },
2532 &mut |_| DeliveryOutcome::Dispatched(Method::MacOS),
2533 );
2534 assert_eq!(result.receipt(), "notification dispatch attempted");
2535 assert_eq!(cues, 1);
2536 assert!(out.is_empty());
2537 }
2538
2539 #[test]
2540 fn failed_audio_never_upgrades_native_dispatch_evidence() {
2541 let mut out = Vec::new();
2542 let result = notify_with_sinks(
2543 Method::MacOS,
2544 false,
2545 &NotificationPayload::input_needed("answer"),
2546 Duration::ZERO,
2547 Duration::ZERO,
2548 NotificationGate::default(),
2549 true,
2550 &mut out,
2551 &mut |_, _| SoundDecision::Play(SoundCue::Whale),
2552 &mut |_, _| AudioOutcome::Failed,
2553 &mut |_| DeliveryOutcome::Dispatched(Method::MacOS),
2554 );
2555 assert_eq!(
2556 result.receipt(),
2557 "notification dispatch attempted; sound unavailable"
2558 );
2559 }
2560
2561 #[test]
2562 fn title_completion_is_only_a_visual_marker_and_cannot_consume_audio() {
2563 let _guard = crate::test_support::lock_test_env();
2564 sound_policy::configure(EventSoundPolicy::from_config(&NotificationsConfig {
2565 sound: Some(CompletionSound::Whale),
2566 ..Default::default()
2567 }));
2568 let mut title = String::new();
2569 stop_title_animation_with(|value| title = value.to_string());
2570 assert!(title.contains("✓ done"));
2571 assert_eq!(
2572 sound_policy::decide(NotificationKind::TurnComplete, 0, false),
2573 SoundDecision::Play(SoundCue::Whale)
2574 );
2575 sound_policy::configure(EventSoundPolicy::default());
2576 COMPLETION_MARKER_SHOWN.store(false, Ordering::SeqCst);
2577 }
2578 }
2579
2579 lines RUST