返回 CodeWhale
status.rs
根目录 / crates / tui / src / tui / app / status.rs
1 use super::*;
2
3 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4 pub enum StatusToastLevel {
5 Info,
6 Success,
7 Warning,
8 Error,
9 }
10
11 impl StatusToastLevel {
12 fn feedback_ttl_ms(self) -> u64 {
13 match self {
14 Self::Info => 4_000,
15 Self::Success | Self::Warning => 5_000,
16 Self::Error => App::STICKY_ERROR_TTL_MS,
17 }
18 }
19
20 /// Resolve every toast surface through the same semantic theme slots.
21 pub(crate) fn ink(self) -> codewhale_palette::ChromeInk {
22 use codewhale_palette::ChromeInk;
23 match self {
24 Self::Info => ChromeInk::Info,
25 Self::Success => ChromeInk::Outcome,
26 Self::Warning => ChromeInk::Attention,
27 Self::Error => ChromeInk::Failure,
28 }
29 }
30 }
31
32 #[derive(Debug, Clone)]
33 pub struct StatusToast {
34 pub text: String,
35 pub(crate) fallback_texts: Vec<String>,
36 pub level: StatusToastLevel,
37 pub created_at: Instant,
38 pub ttl_ms: Option<u64>,
39 pub(crate) kind: StatusToastKind,
40 event_id: Option<String>,
41 }
42
43 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
44 pub(crate) enum StatusToastKind {
45 Ordinary,
46 InputHint,
47 CopyReceipt,
48 ExternalAgent,
49 VoiceCapture,
50 ExtensionCommand,
51 SessionResume,
52 HotbarSettings,
53 PermissionRule,
54 RemoteMirror,
55 Onboarding,
56 ProviderRoute,
57 DeferredInitialPrompt,
58 /// An explicit command result stays visible over a completed turn.
59 CommandReceipt,
60 ActionRequired,
61 RedactionGate(RedactionGateNotice),
62 BehavioralTip(crate::tui::behavioral_tips::BehavioralTip),
63 PluginSuggestion,
64 ContextPressure(codewhale_runtime::context_budget::PressureLevel),
65 /// A condition that holds until its owner retires it by event id (a
66 /// session save that keeps failing). It never times out: expiring it
67 /// would report recovery that has not happened.
68 Standing,
69 }
70
71 impl StatusToast {
72 fn is_setup_notice(&self) -> bool {
73 matches!(
74 self.kind,
75 StatusToastKind::Onboarding | StatusToastKind::ProviderRoute
76 )
77 }
78
79 #[must_use]
80 pub fn new(text: impl Into<String>, level: StatusToastLevel, ttl_ms: Option<u64>) -> Self {
81 Self {
82 text: text.into(),
83 fallback_texts: Vec::new(),
84 level,
85 created_at: Instant::now(),
86 ttl_ms,
87 kind: StatusToastKind::Ordinary,
88 event_id: None,
89 }
90 }
91
92 pub(crate) fn with_fallbacks(mut self, fallbacks: Vec<String>) -> Self {
93 self.fallback_texts = fallbacks;
94 self
95 }
96
97 pub(crate) fn for_event(mut self, event_id: impl Into<String>) -> Self {
98 self.event_id = Some(event_id.into());
99 self
100 }
101
102 /// A notice for a standing condition, withdrawn only through
103 /// [`App::retire_event_notices`]`(event_id)` once the condition clears.
104 #[must_use]
105 pub(crate) fn standing(
106 text: impl Into<String>,
107 level: StatusToastLevel,
108 event_id: impl Into<String>,
109 ) -> Self {
110 Self {
111 text: text.into(),
112 fallback_texts: Vec::new(),
113 level,
114 created_at: Instant::now(),
115 ttl_ms: None,
116 kind: StatusToastKind::Standing,
117 event_id: Some(event_id.into()),
118 }
119 }
120
121 pub(crate) fn for_action(mut self, request_id: impl Into<String>) -> Self {
122 self.kind = StatusToastKind::ActionRequired;
123 self.event_id = Some(request_id.into());
124 self
125 }
126
127 pub(crate) fn for_command_receipt(mut self) -> Self {
128 self.kind = StatusToastKind::CommandReceipt;
129 self
130 }
131
132 pub(crate) fn for_redaction_gate(mut self, notice: RedactionGateNotice) -> Self {
133 self.kind = StatusToastKind::RedactionGate(notice);
134 self
135 }
136
137 #[must_use]
138 pub(crate) fn context_pressure(
139 text: impl Into<String>,
140 level: codewhale_runtime::context_budget::PressureLevel,
141 ) -> Self {
142 Self {
143 text: text.into(),
144 fallback_texts: Vec::new(),
145 level: StatusToastLevel::Warning,
146 created_at: Instant::now(),
147 ttl_ms: None,
148 kind: StatusToastKind::ContextPressure(level),
149 event_id: None,
150 }
151 }
152
153 #[must_use]
154 pub fn is_expired(&self, now: Instant) -> bool {
155 self.ttl_ms.is_some_and(|ttl| {
156 now.saturating_duration_since(self.created_at).as_millis() >= u128::from(ttl)
157 })
158 }
159 }
160
161 impl App {
162 pub(crate) fn show_owned_command_result(
163 &mut self,
164 kind: StatusToastKind,
165 text: impl Into<String>,
166 level: StatusToastLevel,
167 ) {
168 self.retire_progress_notice(kind);
169 let mut notice = StatusToast::new(text, level, Some(level.feedback_ttl_ms()));
170 notice.kind = kind;
171 self.push_status_toast_record(notice);
172 }
173
174 pub(crate) fn show_command_result(&mut self, text: impl Into<String>, level: StatusToastLevel) {
175 let receipt =
176 StatusToast::new(text, level, Some(level.feedback_ttl_ms())).for_command_receipt();
177 self.publish_recent_notice(receipt);
178 }
179
180 fn publish_recent_notice(&mut self, mut receipt: StatusToast) {
181 if let Some(previous) = self.status_toasts.iter().position(|notice| {
182 notice.kind == receipt.kind
183 && notice.event_id.is_none()
184 && notice.level == receipt.level
185 && notice.text == receipt.text
186 }) && let Some(previous) = self.status_toasts.remove(previous)
187 && !previous.is_expired(receipt.created_at)
188 {
189 receipt.created_at = previous.created_at;
190 }
191 self.push_status_toast_record(receipt);
192 }
193
194 pub(crate) fn defer_initial_prompt_notice(&mut self, text: &str) {
195 if self
196 .status_toasts
197 .iter()
198 .any(|notice| notice.kind == StatusToastKind::DeferredInitialPrompt)
199 {
200 return;
201 }
202 let mut notice = StatusToast::new(text, StatusToastLevel::Info, None);
203 notice.kind = StatusToastKind::DeferredInitialPrompt;
204 self.push_status_toast_record(notice);
205 }
206
207 pub(crate) fn retire_deferred_prompt_notice(&mut self) {
208 let before = self.status_toasts.len();
209 self.status_toasts
210 .retain(|notice| notice.kind != StatusToastKind::DeferredInitialPrompt);
211 self.needs_redraw |= self.status_toasts.len() != before;
212 }
213
214 pub(crate) fn setup_notice(&self) -> Option<&StatusToast> {
215 self.status_toasts
216 .iter()
217 .rev()
218 .find(|notice| notice.is_setup_notice())
219 }
220
221 pub(crate) fn route_receipt(&self) -> Option<&StatusToast> {
222 self.setup_notice()
223 .filter(|notice| notice.kind == StatusToastKind::ProviderRoute)
224 }
225
226 pub(crate) fn clear_setup_notice(&mut self) {
227 let previous = self.status_toasts.len();
228 self.status_toasts
229 .retain(|notice| !notice.is_setup_notice());
230 self.needs_redraw |= self.status_toasts.len() != previous;
231 }
232
233 pub(crate) fn show_onboarding_notice(
234 &mut self,
235 text: impl Into<String>,
236 level: StatusToastLevel,
237 ) {
238 self.show_setup_notice(text, level, StatusToastKind::Onboarding);
239 }
240
241 pub(crate) fn show_route_receipt(&mut self, text: impl Into<String>, level: StatusToastLevel) {
242 self.show_setup_notice(text, level, StatusToastKind::ProviderRoute);
243 }
244
245 pub(crate) fn finish_route_step(&mut self, text: String, level: StatusToastLevel) {
246 let (text, level) = match self.route_receipt() {
247 Some(prior)
248 if matches!(
249 prior.level,
250 StatusToastLevel::Warning | StatusToastLevel::Error
251 ) =>
252 {
253 let severity =
254 if level == StatusToastLevel::Error || prior.level == StatusToastLevel::Error {
255 StatusToastLevel::Error
256 } else {
257 StatusToastLevel::Warning
258 };
259 (format!("{} · {text}", prior.text), severity)
260 }
261 _ => (text, level),
262 };
263 self.show_route_receipt(text, level);
264 }
265
266 fn show_setup_notice(
267 &mut self,
268 text: impl Into<String>,
269 level: StatusToastLevel,
270 kind: StatusToastKind,
271 ) {
272 self.clear_setup_notice();
273 let mut notice = StatusToast::new(text, level, Some(level.feedback_ttl_ms()));
274 notice.kind = kind;
275 self.push_status_toast_record(notice);
276 }
277
278 pub(crate) fn show_event_notice(&mut self, text: impl Into<String>, level: StatusToastLevel) {
279 self.publish_recent_notice(StatusToast::new(text, level, Some(level.feedback_ttl_ms())));
280 }
281
282 pub(crate) fn replace_progress_notice(
283 &mut self,
284 kind: StatusToastKind,
285 text: impl Into<String>,
286 ) {
287 let mut notice = StatusToast::new(text, StatusToastLevel::Info, Some(4_000));
288 notice.kind = kind;
289 if let Some(previous) = self.status_toasts.iter().find(|prior| {
290 prior.kind == kind && prior.text == notice.text && !prior.is_expired(notice.created_at)
291 }) {
292 notice.created_at = previous.created_at;
293 }
294 self.retire_progress_notice(kind);
295 self.push_status_toast_record(notice);
296 }
297
298 pub(crate) fn retire_progress_notice(&mut self, kind: StatusToastKind) {
299 let before = self.status_toasts.len();
300 self.status_toasts.retain(|notice| notice.kind != kind);
301 self.needs_redraw |= self.status_toasts.len() != before;
302 }
303
304 pub(crate) fn show_input_hint(&mut self, text: impl Into<String>) {
305 self.show_input_feedback(text, StatusToastLevel::Info, 4_000);
306 }
307
308 pub(crate) fn show_input_feedback(
309 &mut self,
310 text: impl Into<String>,
311 level: StatusToastLevel,
312 ttl_ms: u64,
313 ) {
314 let mut hint = StatusToast::new(text, level, Some(ttl_ms));
315 hint.kind = StatusToastKind::InputHint;
316 if let Some(previous) = self.status_toasts.iter().find(|notice| {
317 notice.kind == hint.kind
318 && !notice.is_expired(hint.created_at)
319 && notice.text == hint.text
320 && notice.level == level
321 }) {
322 hint.created_at = previous.created_at;
323 }
324 self.status_toasts.retain(|notice| notice.kind != hint.kind);
325 self.push_status_toast_record(hint);
326 }
327
328 pub(crate) fn show_copy_notice(
329 &mut self,
330 text: impl Into<String>,
331 level: StatusToastLevel,
332 ttl_ms: u64,
333 ) {
334 let mut receipt = StatusToast::new(text, level, Some(ttl_ms));
335 receipt.kind = StatusToastKind::CopyReceipt;
336 self.status_toasts
337 .retain(|notice| notice.kind != receipt.kind);
338 self.push_status_toast_record(receipt);
339 }
340
341 pub fn push_status_toast(
342 &mut self,
343 text: impl Into<String>,
344 level: StatusToastLevel,
345 ttl_ms: Option<u64>,
346 ) {
347 self.push_status_toast_record(StatusToast::new(text, level, ttl_ms));
348 }
349
350 /// Coalesce a still-visible duplicate without renewing its first expiry.
351 /// Decision identities keep otherwise identical requests independent.
352 pub(crate) fn push_status_toast_record(&mut self, mut toast: StatusToast) {
353 // An omitted lifetime used to leave routine notices in the queue
354 // forever, resurfacing after newer notices expired. Pending actions
355 // and safety gates have explicit kinds and keep their own lifecycle.
356 if toast.kind == StatusToastKind::Ordinary && toast.ttl_ms.is_none() {
357 toast.ttl_ms = Some(Self::STICKY_ERROR_TTL_MS);
358 }
359 self.prune_expired_status_toasts(toast.created_at);
360 if self.status_toasts.iter().any(|existing| {
361 existing.level == toast.level
362 && existing.text == toast.text
363 && existing.kind == toast.kind
364 && existing.event_id == toast.event_id
365 }) {
366 return;
367 }
368 self.status_toasts.push_back(toast);
369 // Overflow drops the oldest notice that is not a standing condition;
370 // those leave only when their condition clears.
371 while self.status_toasts.len() > 24 {
372 let oldest = self
373 .status_toasts
374 .iter()
375 .position(|toast| {
376 !(toast.kind == StatusToastKind::Standing
377 || (toast.kind == StatusToastKind::RemoteMirror && toast.ttl_ms.is_none()))
378 && !(self.onboarding != OnboardingState::None && toast.is_setup_notice())
379 })
380 .unwrap_or(0);
381 self.status_toasts.remove(oldest);
382 }
383 self.needs_redraw = true;
384 }
385
386 /// Retire requests, never their denial/error outcomes. `None` settles
387 /// requests for the whole finished/cancelled turn.
388 pub(crate) fn retire_action_notices(&mut self, request_id: Option<&str>) {
389 let before = self.status_toasts.len();
390 self.status_toasts.retain(|toast| {
391 toast.kind != StatusToastKind::ActionRequired
392 || request_id.is_some_and(|id| toast.event_id.as_deref() != Some(id))
393 });
394 self.needs_redraw |= self.status_toasts.len() != before;
395 }
396
397 /// Retire the notices pushed with [`StatusToast::for_event`]`(event_id)`.
398 pub(crate) fn retire_event_notices(&mut self, event_id: &str) {
399 let before = self.status_toasts.len();
400 self.status_toasts
401 .retain(|toast| toast.event_id.as_deref() != Some(event_id));
402 self.needs_redraw |= self.status_toasts.len() != before;
403 }
404
405 /// Gate transitions retire their own guidance or failed-write receipt,
406 /// independently of translated text and unrelated requests/errors.
407 pub(crate) fn retire_redaction_gate_notice(&mut self, notice: RedactionGateNotice) {
408 let before = self.status_toasts.len();
409 self.status_toasts
410 .retain(|toast| toast.kind != StatusToastKind::RedactionGate(notice));
411 self.needs_redraw |= self.status_toasts.len() != before;
412 }
413
414 /// Default lifetime for sticky error toasts. Long enough to read, short
415 /// enough that a failed workflow does not permanently occupy footer chrome.
416 pub const STICKY_ERROR_TTL_MS: u64 = 8_000;
417
418 pub fn set_sticky_status(
419 &mut self,
420 text: impl Into<String>,
421 level: StatusToastLevel,
422 ttl_ms: Option<u64>,
423 ) {
424 let text = text.into();
425 if self.sticky_status.as_ref().is_some_and(|existing| {
426 existing.text == text
427 && existing.level == level
428 && existing.kind == StatusToastKind::Ordinary
429 && !existing.is_expired(Instant::now())
430 }) {
431 return;
432 }
433 // Cap sticky errors so a missing TTL never becomes permanent chrome.
434 // Explicit shorter TTLs still win; longer/None fall back to the default.
435 let ttl_ms = match level {
436 StatusToastLevel::Error => Some(
437 ttl_ms
438 .unwrap_or(Self::STICKY_ERROR_TTL_MS)
439 .min(Self::STICKY_ERROR_TTL_MS),
440 ),
441 _ => ttl_ms.or(Some(Self::STICKY_ERROR_TTL_MS)),
442 };
443 self.sticky_status = Some(StatusToast::new(text, level, ttl_ms));
444 self.needs_redraw = true;
445 }
446
447 pub fn clear_sticky_status(&mut self) {
448 if self.sticky_status.take().is_some() {
449 self.needs_redraw = true;
450 }
451 }
452
453 pub(crate) fn clear_context_pressure_sticky_status(&mut self) {
454 if self
455 .sticky_status
456 .as_ref()
457 .is_some_and(|status| matches!(status.kind, StatusToastKind::ContextPressure(_)))
458 {
459 self.clear_sticky_status();
460 }
461 self.context_pressure_warning_dismissed = None;
462 }
463
464 /// Dismiss the persistent context-pressure warning without dismissing
465 /// unrelated error/status chrome. Returns whether anything was cleared.
466 pub fn dismiss_context_pressure_warning(&mut self) -> bool {
467 let is_context_pressure = self
468 .sticky_status
469 .as_ref()
470 .is_some_and(|status| matches!(status.kind, StatusToastKind::ContextPressure(_)));
471 if is_context_pressure {
472 if let Some(StatusToastKind::ContextPressure(level)) =
473 self.sticky_status.as_ref().map(|status| status.kind)
474 {
475 self.context_pressure_warning_dismissed = Some(level);
476 }
477 self.clear_sticky_status();
478 return true;
479 }
480 false
481 }
482
483 /// Drop sticky error chrome when the user resumes typing so a prior
484 /// workflow/provider failure does not linger over the next draft.
485 pub fn acknowledge_sticky_on_composer_activity(&mut self) {
486 let before = self.status_toasts.len();
487 self.status_toasts.retain(|notice| {
488 !matches!(
489 notice.kind,
490 StatusToastKind::CopyReceipt
491 | StatusToastKind::CommandReceipt
492 | StatusToastKind::HotbarSettings
493 | StatusToastKind::PermissionRule
494 ) || notice.level != StatusToastLevel::Error
495 });
496 self.needs_redraw |= self.status_toasts.len() != before;
497 if self
498 .sticky_status
499 .as_ref()
500 .is_some_and(|toast| matches!(toast.level, StatusToastLevel::Error))
501 {
502 self.clear_sticky_status();
503 }
504 }
505
506 pub(super) fn classify_engine_status(text: &str) -> (StatusToastLevel, Option<u64>, bool) {
507 let lower = text.to_ascii_lowercase();
508 let has = |needle: &str| lower.contains(needle);
509
510 if has("offline mode") || has("context critical") {
511 return (StatusToastLevel::Warning, None, true);
512 }
513 if has("error")
514 || has("failed")
515 || has("denied")
516 || has("timeout")
517 || has("aborted")
518 || has("critical")
519 {
520 return (
521 StatusToastLevel::Error,
522 Some(Self::STICKY_ERROR_TTL_MS),
523 true,
524 );
525 }
526 // A success keyword under a negation ("not saved", "no longer
527 // found", "could not enable") is a failure the coarse keyword match
528 // would otherwise paint green. Guard it: negated success degrades to
529 // a neutral Info toast rather than a misleading Success.
530 let negated = has("not ")
531 || has("no longer")
532 || has("no ")
533 || has("could not")
534 || has("couldn't")
535 || has("cannot")
536 || has("can't")
537 || has("unable");
538 if !negated
539 && (has("saved")
540 || has("loaded")
541 || has("queued")
542 || has("found")
543 || has("enabled")
544 || has("completed"))
545 {
546 return (StatusToastLevel::Success, Some(5_000), false);
547 }
548 if has("cancelled") || has("canceled") || has("warning") {
549 return (StatusToastLevel::Warning, Some(5_000), false);
550 }
551 (StatusToastLevel::Info, Some(4_000), false)
552 }
553
554 pub(crate) fn report_engine_status(&mut self, message: String) {
555 if message.trim().is_empty()
556 || (message.starts_with("Switched to ") && message.ends_with(" mode"))
557 {
558 return;
559 }
560 let now = Instant::now();
561 if self
562 .status_toasts
563 .iter()
564 .chain(self.sticky_status.iter())
565 .any(|notice| notice.text == message && !notice.is_expired(now))
566 {
567 return;
568 }
569 let (level, ttl_ms, sticky) = Self::classify_engine_status(&message);
570 if sticky {
571 self.set_sticky_status(message, level, ttl_ms);
572 } else {
573 self.push_status_toast(message, level, ttl_ms);
574 }
575 }
576
577 pub(crate) fn prune_expired_status_toasts(&mut self, now: Instant) {
578 let queued_before = self.status_toasts.len();
579 self.status_toasts.retain(|toast| {
580 !toast.is_expired(now)
581 || (self.onboarding != OnboardingState::None && toast.is_setup_notice())
582 });
583 let queued_removed = self.status_toasts.len() != queued_before;
584 let sticky_removed = self
585 .sticky_status
586 .as_ref()
587 .is_some_and(|toast| toast.is_expired(now));
588 if sticky_removed {
589 self.sticky_status = None;
590 }
591 if queued_removed || sticky_removed {
592 self.needs_redraw = true;
593 }
594 }
595
596 #[cfg(test)]
597 pub(crate) fn visible_notice_text(&mut self) -> Option<String> {
598 self.active_status_toast(crate::tui::underwater::ShellPhase::Typing)
599 .map(|notice| notice.text)
600 }
601
602 pub fn active_status_toast(
603 &mut self,
604 phase: crate::tui::underwater::ShellPhase,
605 ) -> Option<StatusToast> {
606 let now = Instant::now();
607 self.prune_expired_status_toasts(now);
608
609 let eligible = |toast: &&StatusToast| {
610 if toast.is_expired(now) {
611 return false;
612 }
613 phase != crate::tui::underwater::ShellPhase::Done
614 || matches!(
615 toast.kind,
616 StatusToastKind::CommandReceipt
617 | StatusToastKind::HotbarSettings
618 | StatusToastKind::VoiceCapture
619 | StatusToastKind::PermissionRule
620 | StatusToastKind::CopyReceipt
621 | StatusToastKind::ProviderRoute
622 )
623 || matches!(
624 toast.level,
625 StatusToastLevel::Warning | StatusToastLevel::Error
626 )
627 };
628 let sticky = self.sticky_status.as_ref().filter(eligible).cloned();
629 let latest = self.status_toasts.iter().rev().find(eligible).cloned();
630 match (sticky, latest) {
631 (Some(sticky), Some(latest))
632 if matches!(
633 sticky.kind,
634 StatusToastKind::ContextPressure(
635 codewhale_runtime::context_budget::PressureLevel::High
636 ) | StatusToastKind::ContextPressure(
637 codewhale_runtime::context_budget::PressureLevel::Medium
638 )
639 ) =>
640 {
641 Some(latest)
642 }
643 (Some(sticky), _) => Some(sticky),
644 (None, latest) => latest,
645 }
646 }
647 }
648
649 #[cfg(test)]
650 mod tests {
651 use super::*;
652 use std::time::Duration;
653
654 fn app() -> App {
655 App::new(
656 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
657 &codewhale_runtime::config::Config::default(),
658 )
659 }
660
661 #[test]
662 fn live_toast_duplicates_keep_first_expiry_and_distinct_decisions() {
663 let mut app = app();
664 let now = Instant::now();
665 let record = |id: &str, at: Instant| {
666 let mut toast = StatusToast::new(
667 "Review this request",
668 StatusToastLevel::Warning,
669 Some(2_000),
670 )
671 .for_action(id);
672 toast.created_at = at;
673 toast
674 };
675 app.push_status_toast_record(record("a", now));
676 app.push_status_toast_record(record("a", now + Duration::from_millis(1_000)));
677 assert_eq!(app.status_toasts.len(), 1);
678 assert_eq!(app.status_toasts[0].created_at, now);
679 app.push_status_toast_record(record("b", now + Duration::from_millis(1_000)));
680 assert_eq!(app.status_toasts.len(), 2);
681 app.push_status_toast_record(record("a", now + Duration::from_millis(2_000)));
682 assert_eq!(
683 app.status_toasts.len(),
684 2,
685 "expired a is replaced; independent b survives"
686 );
687 assert_eq!(
688 app.status_toasts.back().unwrap().created_at,
689 now + Duration::from_millis(2_000)
690 );
691 }
692
693 #[test]
694 fn routine_notices_expire_without_dismissing_pending_actions_or_safety_gates() {
695 let mut app = app();
696 let now = Instant::now();
697 app.push_status_toast("Temporary warning", StatusToastLevel::Warning, None);
698 app.push_status_toast("Copied", StatusToastLevel::Info, None);
699 app.set_sticky_status("Offline mode", StatusToastLevel::Warning, None);
700 app.push_status_toast_record(
701 StatusToast::new("Review request", StatusToastLevel::Warning, None)
702 .for_action("pending"),
703 );
704 app.push_status_toast_record(
705 StatusToast::new("Review redaction", StatusToastLevel::Warning, None)
706 .for_redaction_gate(RedactionGateNotice::WriteFailure),
707 );
708 app.prune_expired_status_toasts(now + Duration::from_secs(10));
709 assert!(app.sticky_status.is_none());
710 assert_eq!(app.status_toasts.len(), 2);
711 assert_eq!(app.status_toasts[0].kind, StatusToastKind::ActionRequired);
712 assert_eq!(
713 app.status_toasts[1].kind,
714 StatusToastKind::RedactionGate(RedactionGateNotice::WriteFailure)
715 );
716 }
717
718 #[test]
719 fn onboarding_receipt_outlives_its_footer_and_only_route_actions_supply_route_text() {
720 let mut app = app();
721 app.onboarding = OnboardingState::Provider;
722 app.show_route_receipt("Selected route", StatusToastLevel::Success);
723 let expired_at = Instant::now() - Duration::from_secs(30);
724 app.status_toasts.back_mut().unwrap().created_at = expired_at;
725 for n in 0..32 {
726 app.show_copy_notice(format!("Copy {n}"), StatusToastLevel::Info, 4_000);
727 app.push_status_toast(format!("Progress {n}"), StatusToastLevel::Info, Some(4_000));
728 }
729 assert_eq!(app.route_receipt().unwrap().text, "Selected route");
730 assert_ne!(
731 app.active_status_toast(crate::tui::underwater::ShellPhase::Typing)
732 .unwrap()
733 .text,
734 "Selected route"
735 );
736 app.show_route_receipt("Could not save setup progress", StatusToastLevel::Warning);
737 app.finish_route_step("Thinking unchanged".to_owned(), StatusToastLevel::Info);
738 app.finish_route_step("Startup route saved".to_owned(), StatusToastLevel::Success);
739 let partial = app.route_receipt().unwrap();
740 assert_eq!(partial.level, StatusToastLevel::Warning);
741 assert!(partial.text.contains("Could not save setup progress"));
742 assert!(partial.text.contains("Startup route saved"));
743 app.show_onboarding_notice("Trust required", StatusToastLevel::Warning);
744 assert!(app.route_receipt().is_none());
745 app.clear_setup_notice();
746 assert!(app.setup_notice().is_none());
747 assert!(!app.status_toasts.is_empty());
748 }
749
750 #[test]
751 fn input_hint_preserves_pending_notice_order_and_ignores_error_words_in_filenames() {
752 use crate::tui::underwater::ShellPhase;
753 let mut app = app();
754 app.onboarding = OnboardingState::None;
755 app.push_status_toast_record(
756 StatusToast::new("Decision", StatusToastLevel::Warning, None).for_action("input-hint"),
757 );
758 app.show_event_notice("Older progress", StatusToastLevel::Info);
759 app.show_input_hint("Attached @failed-error.log");
760 let hint = app.active_status_toast(ShellPhase::Typing).unwrap();
761 assert_eq!(hint.text, "Attached @failed-error.log");
762 assert_eq!(hint.level, StatusToastLevel::Info);
763 assert_eq!(hint.kind, StatusToastKind::InputHint);
764 assert_eq!(hint.ttl_ms, Some(4_000));
765 assert!(app.sticky_status.is_none());
766 app.show_input_hint("Attached @failed-error.log");
767 assert_eq!(
768 app.status_toasts.back().unwrap().created_at,
769 hint.created_at
770 );
771 app.show_input_hint("Composer focused");
772 assert!(
773 app.status_toasts
774 .iter()
775 .all(|notice| notice.text != hint.text)
776 );
777 let latest = app.status_toasts.back().unwrap().created_at;
778 app.prune_expired_status_toasts(latest + Duration::from_secs(4));
779 assert_eq!(
780 app.active_status_toast(ShellPhase::Typing).unwrap().text,
781 "Decision"
782 );
783 app.show_event_notice("Older progress", StatusToastLevel::Info);
784 assert_eq!(
785 app.active_status_toast(ShellPhase::Typing).unwrap().text,
786 "Older progress"
787 );
788 app.show_input_hint("Composer focused");
789 app.show_event_notice("Older progress", StatusToastLevel::Info);
790 assert_eq!(
791 app.active_status_toast(ShellPhase::Typing).unwrap().text,
792 "Older progress"
793 );
794 }
795
796 #[test]
797 fn engine_status_does_not_reclassify_a_typed_notice_or_repeat_a_live_notice() {
798 let mut app = app();
799 let text = "承認してください · failed-tool";
800 app.push_status_toast(text, StatusToastLevel::Warning, Some(12_000));
801 let first = app.status_toasts[0].created_at;
802 for message in [text, "another status", text] {
803 app.report_engine_status(message.into());
804 }
805 assert_eq!(app.status_toasts.len(), 2);
806 assert_eq!(app.status_toasts[0].level, StatusToastLevel::Warning);
807 assert_eq!(app.status_toasts[0].created_at, first);
808 assert!(
809 app.sticky_status.is_none(),
810 "tool data must not create an inferred error"
811 );
812 }
813
814 #[test]
815 fn repeated_sticky_error_does_not_renew_its_expiry() {
816 let mut app = app();
817 app.set_sticky_status("same failure", StatusToastLevel::Error, None);
818 let created_at = app.sticky_status.as_ref().unwrap().created_at;
819 app.set_sticky_status("same failure", StatusToastLevel::Error, None);
820 assert_eq!(app.sticky_status.as_ref().unwrap().created_at, created_at);
821 app.sticky_status.as_mut().unwrap().created_at = created_at - Duration::from_secs(10);
822 app.set_sticky_status("same failure", StatusToastLevel::Error, None);
823 assert!(app.sticky_status.as_ref().unwrap().created_at >= created_at);
824 }
825
826 #[test]
827 fn retiring_action_notices_preserves_other_requests_and_outcome_receipts() {
828 let mut app = app();
829 for id in ["a", "b"] {
830 app.push_status_toast_record(
831 StatusToast::new("Review", StatusToastLevel::Warning, None).for_action(id),
832 );
833 }
834 app.push_status_toast_record(
835 StatusToast::new("Denied", StatusToastLevel::Warning, None).for_event("a"),
836 );
837 app.retire_action_notices(Some("a"));
838 assert_eq!(app.status_toasts.len(), 2);
839 assert_eq!(app.status_toasts[0].event_id.as_deref(), Some("b"));
840 app.retire_action_notices(None);
841 assert_eq!(app.status_toasts.len(), 1);
842 assert_eq!(app.status_toasts[0].text, "Denied");
843 }
844
845 #[test]
846 fn redaction_gate_cleanup_preserves_failed_writes_until_settled_and_unrelated_notices() {
847 let mut app = app();
848 // Deliberately equal translated text: identity must own cleanup.
849 for notice in [
850 RedactionGateNotice::EnterGuidance,
851 RedactionGateNotice::WriteFailure,
852 ] {
853 app.push_status_toast_record(
854 StatusToast::new("確認してください", StatusToastLevel::Warning, None)
855 .for_redaction_gate(notice),
856 );
857 }
858 app.push_status_toast("確認してください", StatusToastLevel::Warning, None);
859 app.push_status_toast_record(
860 StatusToast::new("Review", StatusToastLevel::Warning, None).for_action("request"),
861 );
862 app.set_sticky_status("Unrelated failure", StatusToastLevel::Error, None);
863 app.needs_redraw = false;
864 app.retire_redaction_gate_notice(RedactionGateNotice::EnterGuidance);
865 assert!(app.needs_redraw);
866 assert_eq!(app.status_toasts.len(), 3);
867 assert_eq!(
868 app.status_toasts[0].kind,
869 StatusToastKind::RedactionGate(RedactionGateNotice::WriteFailure)
870 );
871 app.retire_redaction_gate_notice(RedactionGateNotice::WriteFailure);
872 assert_eq!(app.status_toasts.len(), 2);
873 assert_eq!(app.status_toasts[0].kind, StatusToastKind::Ordinary);
874 assert_eq!(app.status_toasts[1].kind, StatusToastKind::ActionRequired);
875 assert_eq!(
876 app.sticky_status.as_ref().unwrap().text,
877 "Unrelated failure"
878 );
879 }
880 }
881
881 lines RUST