返回 CodeWhale
behavioral_tips.rs
根目录 / crates / tui / src / tui / behavioral_tips.rs
1 //! Quiet, action-triggered product guidance.
2 //!
3 //! These tips are deliberately event-driven rather than timer-driven. The
4 //! session gate keeps the TUI calm, while persisted impression counts prevent
5 //! a useful first-run hint from becoming permanent chrome.
6
7 use std::collections::{HashMap, HashSet};
8 use std::hash::{DefaultHasher, Hash, Hasher};
9
10 use crate::tui::app::{App, StatusToast, StatusToastKind, StatusToastLevel};
11 use codewhale_localization::{Locale, MessageId, tr};
12 use codewhale_runtime::settings::Settings;
13
14 const MAX_TIPS_PER_SESSION: u8 = 1;
15 const MAX_LIFETIME_IMPRESSIONS: u8 = 2;
16 const MAX_TRACKED_MANUAL_COMMANDS: usize = 128;
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19 pub enum BehavioralTip {
20 BackgroundJobReceipt,
21 ClearedInputRestore,
22 McpValidation,
23 RepeatedCommandHotbar,
24 DurableStateWritten,
25 }
26
27 impl BehavioralTip {
28 const fn key(self) -> &'static str {
29 match self {
30 Self::BackgroundJobReceipt => "background_job_receipt",
31 Self::ClearedInputRestore => "cleared_input_restore",
32 Self::McpValidation => "mcp_validation",
33 Self::RepeatedCommandHotbar => "repeated_command_hotbar",
34 Self::DurableStateWritten => "durable_state_written",
35 }
36 }
37
38 const fn message_id(self) -> MessageId {
39 match self {
40 Self::BackgroundJobReceipt => MessageId::BehavioralTipBackgroundReceipt,
41 Self::ClearedInputRestore => MessageId::BehavioralTipClearedInput,
42 Self::McpValidation => MessageId::BehavioralTipMcpValidation,
43 Self::RepeatedCommandHotbar => MessageId::BehavioralTipRepeatedCommand,
44 Self::DurableStateWritten => MessageId::BehavioralTipDurableStateWritten,
45 }
46 }
47
48 fn message(self, locale: Locale) -> String {
49 let template = tr(locale, self.message_id());
50 match self {
51 Self::BackgroundJobReceipt => template.replace("{key}", "Enter"),
52 Self::ClearedInputRestore => template.replace("{chord}", "Ctrl+Z"),
53 Self::McpValidation => template.replace("{command}", "codewhale mcp validate"),
54 Self::RepeatedCommandHotbar => template.replace("{command}", "/hotbar"),
55 Self::DurableStateWritten => template.replace("{command}", "/memory"),
56 }
57 }
58 }
59
60 #[derive(Debug)]
61 pub struct BehavioralTipState {
62 enabled: bool,
63 shown_this_session: HashSet<BehavioralTip>,
64 session_impressions: u8,
65 manual_command_counts: HashMap<u64, u8>,
66 }
67
68 impl Default for BehavioralTipState {
69 fn default() -> Self {
70 Self::new(true)
71 }
72 }
73
74 impl BehavioralTipState {
75 pub fn new(enabled: bool) -> Self {
76 Self {
77 enabled,
78 shown_this_session: HashSet::new(),
79 session_impressions: 0,
80 manual_command_counts: HashMap::new(),
81 }
82 }
83
84 pub fn enabled(&self) -> bool {
85 self.enabled
86 }
87
88 pub(crate) fn guidance_available(&self) -> bool {
89 self.enabled && self.session_impressions < MAX_TIPS_PER_SESSION
90 }
91
92 fn eligible_in_session(&self, tip: BehavioralTip) -> bool {
93 self.guidance_available() && !self.shown_this_session.contains(&tip)
94 }
95
96 fn eligible(&self, tip: BehavioralTip, lifetime_impressions: u8) -> bool {
97 self.eligible_in_session(tip) && lifetime_impressions < MAX_LIFETIME_IMPRESSIONS
98 }
99
100 fn record_impression(&mut self, tip: BehavioralTip) {
101 self.shown_this_session.insert(tip);
102 self.record_guidance_impression();
103 }
104
105 pub(crate) fn record_guidance_impression(&mut self) {
106 self.session_impressions = self.session_impressions.saturating_add(1);
107 }
108
109 fn note_manual_command(&mut self, input: &str) -> bool {
110 let Some(fingerprint) = manual_command_fingerprint(input) else {
111 return false;
112 };
113 if self.manual_command_counts.len() >= MAX_TRACKED_MANUAL_COMMANDS
114 && !self.manual_command_counts.contains_key(&fingerprint)
115 {
116 return false;
117 }
118 let count = self.manual_command_counts.entry(fingerprint).or_default();
119 *count = count.saturating_add(1);
120 *count == 3
121 }
122 }
123
124 impl App {
125 /// A preference change never acknowledges errors, approvals, or recovery
126 /// notices. Keep impression caps intact when tips are enabled again.
127 pub fn set_contextual_tips_enabled(&mut self, enabled: bool) {
128 self.behavioral_tips.enabled = enabled;
129 if !enabled {
130 self.status_toasts.retain(|toast| {
131 !matches!(
132 toast.kind,
133 StatusToastKind::BehavioralTip(_) | StatusToastKind::PluginSuggestion
134 )
135 });
136 // One switch governs every plugin offer, the review row included.
137 self.plugin_cta.phase = crate::tui::plugin_suggestions::PluginCtaPhase::Hidden;
138 }
139 self.needs_redraw = true;
140 }
141
142 /// Show a behavioral tip when both the quiet session cap and the persisted
143 /// lifetime cap allow it. Persistence is best-effort: a read-only home
144 /// must not make a useful in-session hint fail closed.
145 pub fn maybe_show_behavioral_tip(&mut self, tip: BehavioralTip) -> bool {
146 // Clear-input hooks are hot paths. Once the in-memory session gate is
147 // closed, avoid touching the settings file for every later keypress.
148 if !self.behavioral_tips.eligible_in_session(tip) {
149 return false;
150 }
151 // Tests never touch the settings file here, so the eligibility read uses
152 // in-memory defaults. Outside tests the read and the increment are one
153 // transaction: a read-modify-write on an impression counter is exactly
154 // what another whole-file writer would otherwise revert.
155 if cfg!(test) {
156 // No settings file is read or written, so the lifetime count is
157 // whatever `Settings::default()` carries: nothing.
158 if !self.behavioral_tips.eligible(tip, 0) {
159 return false;
160 }
161 self.behavioral_tips.record_impression(tip);
162 } else {
163 let eligible = Settings::transact_opt(|settings| {
164 let lifetime_impressions = settings
165 .behavioral_tip_impressions
166 .get(tip.key())
167 .copied()
168 .unwrap_or(0);
169 if !self.behavioral_tips.eligible(tip, lifetime_impressions) {
170 return Ok(None);
171 }
172 settings.behavioral_tip_impressions.insert(
173 tip.key().to_string(),
174 lifetime_impressions.saturating_add(1),
175 );
176 Ok(Some(()))
177 });
178 match eligible {
179 Ok(None) => return false,
180 Ok(Some(())) => {}
181 Err(err) => {
182 tracing::warn!(tip = tip.key(), error = %err, "behavioral tip impression was not persisted");
183 }
184 }
185 self.behavioral_tips.record_impression(tip);
186 }
187 let mut toast = StatusToast::new(
188 tip.message(self.ui_locale),
189 StatusToastLevel::Info,
190 Some(8_000),
191 );
192 toast.kind = StatusToastKind::BehavioralTip(tip);
193 self.push_status_toast_record(toast);
194 true
195 }
196
197 pub fn note_manual_command_for_tip(&mut self, input: &str) -> bool {
198 self.behavioral_tips.enabled
199 && self.behavioral_tips.note_manual_command(input)
200 && self.maybe_show_behavioral_tip(BehavioralTip::RepeatedCommandHotbar)
201 }
202 }
203
204 fn manual_command_fingerprint(input: &str) -> Option<u64> {
205 let parts = input.split_whitespace().collect::<Vec<_>>();
206 let command = parts.first()?;
207 if !command.starts_with('/') || command.eq_ignore_ascii_case("/hotbar") {
208 return None;
209 }
210 let normalized = parts.join(" ");
211 let mut hasher = DefaultHasher::new();
212 normalized.hash(&mut hasher);
213 Some(hasher.finish())
214 }
215
216 #[cfg(test)]
217 mod tests {
218 use super::*;
219
220 #[test]
221 fn session_and_lifetime_caps_keep_tips_quiet() {
222 let mut state = BehavioralTipState::default();
223 assert!(state.eligible(BehavioralTip::McpValidation, 0));
224 state.record_impression(BehavioralTip::McpValidation);
225 assert!(!state.eligible(BehavioralTip::McpValidation, 0));
226 assert!(!state.eligible(BehavioralTip::BackgroundJobReceipt, 0));
227
228 let fresh_session = BehavioralTipState::default();
229 assert!(fresh_session.eligible(BehavioralTip::McpValidation, 1));
230 assert!(!fresh_session.eligible(BehavioralTip::McpValidation, MAX_LIFETIME_IMPRESSIONS));
231 }
232
233 #[test]
234 fn third_matching_manual_command_triggers_once() {
235 let mut state = BehavioralTipState::default();
236 assert!(!state.note_manual_command("/model one"));
237 assert!(!state.note_manual_command("/model two"));
238 assert!(!state.note_manual_command(" /model one "));
239 assert!(state.note_manual_command("/model one"));
240 assert!(!state.note_manual_command("/model one"));
241 assert!(!state.note_manual_command("/hotbar"));
242 assert!(!state.note_manual_command("ordinary prompt"));
243 }
244
245 #[test]
246 fn every_complete_locale_renders_tips_with_code_owned_controls() {
247 let tips = [
248 BehavioralTip::BackgroundJobReceipt,
249 BehavioralTip::ClearedInputRestore,
250 BehavioralTip::McpValidation,
251 BehavioralTip::RepeatedCommandHotbar,
252 BehavioralTip::DurableStateWritten,
253 ];
254 for locale in Locale::shipped_complete() {
255 for tip in tips {
256 let message = tip.message(*locale);
257 assert!(!message.contains('{'), "unexpanded placeholder: {message}");
258 }
259 }
260
261 assert_eq!(
262 BehavioralTip::BackgroundJobReceipt.message(Locale::En),
263 "Receipts live in the Work panel — Enter opens the inspector"
264 );
265 assert_eq!(
266 BehavioralTip::ClearedInputRestore.message(Locale::En),
267 "Cleared · Ctrl+Z restores"
268 );
269 assert_eq!(
270 BehavioralTip::McpValidation.message(Locale::En),
271 "codewhale mcp validate starts servers and shows why"
272 );
273 assert_eq!(
274 BehavioralTip::RepeatedCommandHotbar.message(Locale::En),
275 "/hotbar can pin this"
276 );
277 assert_eq!(
278 BehavioralTip::DurableStateWritten.message(Locale::En),
279 "Saved · /memory to inspect"
280 );
281 }
282 }
283
283 lines RUST