| 1 | //! Cross-session composer input history (#366). |
| 2 | //! |
| 3 | //! Persists user-typed prompts to `~/.codewhale/composer_history.jsonl` |
| 4 | //! (using the legacy `~/.deepseek` root only when one already exists, |
| 5 | //! #3240) so pressing Up-arrow at the composer recalls |
| 6 | //! submissions from previous sessions, not just the current one. One entry |
| 7 | //! per JSON line, oldest first. Existing `composer_history.txt` files are |
| 8 | //! read verbatim on migration and left intact. The history is |
| 9 | //! capped at [`MAX_HISTORY_ENTRIES`] entries (older entries are pruned |
| 10 | //! at append time). Encoding every entry as a JSON string keeps multiline |
| 11 | //! prompts intact without mistaking old quoted prompts for encoded records. |
| 12 | //! |
| 13 | //! Slash commands are stored as well: recalling `/theme` or `/compact` |
| 14 | //! with Up-arrow is ordinary recall (#6006), and filtering on the `/` |
| 15 | //! prefix also dropped absolute paths like `cat /etc/fstab`. Empty / |
| 16 | //! whitespace-only inputs are still skipped. |
| 17 | //! |
| 18 | //! ## Off-thread writes (#1927) |
| 19 | //! |
| 20 | //! [`append_history`] used to block the caller for a read-then-atomic- |
| 21 | //! rewrite of the full file. That ran on the UI thread inside |
| 22 | //! `submit_input`, contributing a perceptible stall after Enter. The |
| 23 | //! public entry point now hands work to a dedicated writer thread via |
| 24 | //! [`writer_sender`] and returns immediately. Submissions stay serialised |
| 25 | //! in arrival order, so the on-disk file keeps its "oldest first" |
| 26 | //! invariant. |
| 27 | |
| 28 | use std::fs; |
| 29 | use std::io::{BufRead, BufReader}; |
| 30 | use std::path::{Path, PathBuf}; |
| 31 | use std::sync::OnceLock; |
| 32 | use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; |
| 33 | use std::time::Duration; |
| 34 | |
| 35 | /// Hard cap on persisted history. Keeps the file small (typical entries |
| 36 | /// are < 200 chars, so 1000 entries ≈ 200 KB) and bounds startup load |
| 37 | /// time. |
| 38 | pub const MAX_HISTORY_ENTRIES: usize = 1000; |
| 39 | |
| 40 | const HISTORY_FILE_NAME: &str = "composer_history.jsonl"; |
| 41 | const LEGACY_HISTORY_FILE_NAME: &str = "composer_history.txt"; |
| 42 | |
| 43 | fn default_history_path() -> Option<PathBuf> { |
| 44 | // Submitting a prompt in a UI test appends to the history; an unsealed test |
| 45 | // must not write the developer's real `~/.codewhale/composer_history.jsonl`. |
| 46 | #[cfg(test)] |
| 47 | if let Some(home) = crate::test_support::unsealed_state_dir(".") { |
| 48 | return history_path_with_home(Some(home)); |
| 49 | } |
| 50 | if codewhale_paths::codewhale_home_is_explicit() { |
| 51 | return codewhale_paths::codewhale_home() |
| 52 | .ok() |
| 53 | .flatten() |
| 54 | .map(|home| home.join(HISTORY_FILE_NAME)); |
| 55 | } |
| 56 | history_path_with_home(codewhale_paths::user_home()) |
| 57 | } |
| 58 | |
| 59 | /// Resolve the composer-history file under `home`, preferring the CodeWhale |
| 60 | /// root and only falling back to the legacy `.deepseek` root when a legacy |
| 61 | /// file already exists. |
| 62 | /// |
| 63 | /// On a fresh install (neither file present) this returns the `.codewhale` |
| 64 | /// path, so the writer never recreates `~/.deepseek/` at runtime (#3240), |
| 65 | /// while users who haven't migrated keep their existing history in that |
| 66 | /// root. Mirrors the primary/legacy resolution used by |
| 67 | /// `snapshot::paths` and `artifacts`. |
| 68 | fn history_path_with_home(home: Option<PathBuf>) -> Option<PathBuf> { |
| 69 | let home = home?; |
| 70 | let primary = home.join(".codewhale").join(HISTORY_FILE_NAME); |
| 71 | if primary.exists() || primary.with_file_name(LEGACY_HISTORY_FILE_NAME).exists() { |
| 72 | return Some(primary); |
| 73 | } |
| 74 | let legacy = home.join(".deepseek").join(HISTORY_FILE_NAME); |
| 75 | if legacy.exists() || legacy.with_file_name(LEGACY_HISTORY_FILE_NAME).exists() { |
| 76 | return Some(legacy); |
| 77 | } |
| 78 | Some(primary) |
| 79 | } |
| 80 | |
| 81 | /// Read the persisted history into memory. Returns an empty vec if the |
| 82 | /// file doesn't exist or can't be parsed — this is best-effort. |
| 83 | #[must_use] |
| 84 | pub fn load_history() -> Vec<String> { |
| 85 | let Some(path) = default_history_path() else { |
| 86 | return Vec::new(); |
| 87 | }; |
| 88 | load_history_from(&path) |
| 89 | } |
| 90 | |
| 91 | fn load_history_from(path: &Path) -> Vec<String> { |
| 92 | read_history_from(path).unwrap_or_else(|err| { |
| 93 | tracing::warn!( |
| 94 | "Failed to read composer history at {}: {err}", |
| 95 | path.display() |
| 96 | ); |
| 97 | Vec::new() |
| 98 | }) |
| 99 | } |
| 100 | |
| 101 | fn read_history_from(path: &Path) -> std::io::Result<Vec<String>> { |
| 102 | // A separate filename is the format discriminator: arbitrary legacy |
| 103 | // prompts can themselves be valid JSON strings (including escapes). |
| 104 | let (source, encoded) = if path.exists() { |
| 105 | (path.to_path_buf(), true) |
| 106 | } else { |
| 107 | (path.with_file_name(LEGACY_HISTORY_FILE_NAME), false) |
| 108 | }; |
| 109 | let file = match fs::File::open(&source) { |
| 110 | Ok(file) => file, |
| 111 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), |
| 112 | Err(err) => return Err(err), |
| 113 | }; |
| 114 | let mut entries = Vec::new(); |
| 115 | let mut reader = BufReader::new(file); |
| 116 | let mut raw = Vec::new(); |
| 117 | let mut line_number = 0usize; |
| 118 | loop { |
| 119 | raw.clear(); |
| 120 | let bytes_read = reader.read_until(b'\n', &mut raw)?; |
| 121 | if bytes_read == 0 { |
| 122 | break; |
| 123 | } |
| 124 | line_number += 1; |
| 125 | if raw.ends_with(b"\n") { |
| 126 | raw.pop(); |
| 127 | if raw.ends_with(b"\r") { |
| 128 | raw.pop(); |
| 129 | } |
| 130 | } |
| 131 | let Ok(line) = std::str::from_utf8(&raw) else { |
| 132 | tracing::warn!( |
| 133 | "Skipping invalid UTF-8 line {} in composer history at {}", |
| 134 | line_number, |
| 135 | source.display() |
| 136 | ); |
| 137 | continue; |
| 138 | }; |
| 139 | if line.trim().is_empty() { |
| 140 | continue; |
| 141 | } |
| 142 | entries.push(if encoded { |
| 143 | // Keep a malformed record as text rather than losing it on |
| 144 | // the next append/rewrite. |
| 145 | serde_json::from_str::<String>(line).unwrap_or_else(|_| line.to_string()) |
| 146 | } else { |
| 147 | line.to_string() |
| 148 | }); |
| 149 | } |
| 150 | Ok(entries) |
| 151 | } |
| 152 | |
| 153 | /// Append an entry to the persisted history, pruning old entries to |
| 154 | /// stay within [`MAX_HISTORY_ENTRIES`]. Prompts and slash commands are kept; |
| 155 | /// empty input is skipped. |
| 156 | /// |
| 157 | /// Best-effort and non-blocking — work is forwarded to a dedicated writer |
| 158 | /// thread so the caller (typically the UI submit handler) returns |
| 159 | /// immediately. See module docs for the rationale (#1927). Failures on |
| 160 | /// the writer thread are logged via `tracing` but not propagated. |
| 161 | pub fn append_history(entry: &str) { |
| 162 | let Some(path) = default_history_path() else { |
| 163 | return; |
| 164 | }; |
| 165 | append_history_dispatched(&path, entry); |
| 166 | } |
| 167 | |
| 168 | /// Path-injectable variant of [`append_history`] used by tests. Forwards |
| 169 | /// the work to the dedicated writer thread (or falls back to a synchronous |
| 170 | /// write if the channel send fails) so callers never block on disk I/O. |
| 171 | fn append_history_dispatched(path: &Path, entry: &str) { |
| 172 | let entry = entry.to_string(); |
| 173 | if let Err(err) = writer_sender().send(HistoryWrite::Append(path.to_path_buf(), entry)) { |
| 174 | match err.0 { |
| 175 | HistoryWrite::Append(path, entry) => append_history_to(&path, &entry), |
| 176 | #[cfg(test)] |
| 177 | HistoryWrite::Flush(_) => unreachable!("flush messages are only sent by tests"), |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | enum HistoryWrite { |
| 183 | Append(PathBuf, String), |
| 184 | #[cfg(test)] |
| 185 | Flush(Sender<()>), |
| 186 | } |
| 187 | |
| 188 | /// Lazy singleton sender for the dedicated composer-history writer |
| 189 | /// thread. Initialised on first use; the thread runs for the lifetime |
| 190 | /// of the process and drains queued writes in arrival order. |
| 191 | fn writer_sender() -> &'static Sender<HistoryWrite> { |
| 192 | static SENDER: OnceLock<Sender<HistoryWrite>> = OnceLock::new(); |
| 193 | SENDER.get_or_init(|| { |
| 194 | let (tx, rx) = channel::<HistoryWrite>(); |
| 195 | let spawn_result = std::thread::Builder::new() |
| 196 | .name("composer-history-writer".to_string()) |
| 197 | .spawn(move || { |
| 198 | // recv() returns Err when all senders have dropped, which |
| 199 | // only happens at process shutdown because the singleton |
| 200 | // sender lives in a static for the lifetime of the process. |
| 201 | while let Ok(message) = rx.recv() { |
| 202 | match message { |
| 203 | HistoryWrite::Append(path, entry) => { |
| 204 | append_history_batch(&rx, (path, entry)); |
| 205 | } |
| 206 | #[cfg(test)] |
| 207 | HistoryWrite::Flush(done) => { |
| 208 | let _ = done.send(()); |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | }); |
| 213 | if let Err(err) = spawn_result { |
| 214 | tracing::warn!("Failed to spawn composer-history-writer: {err}"); |
| 215 | } |
| 216 | tx |
| 217 | }) |
| 218 | } |
| 219 | |
| 220 | fn append_history_batch(rx: &Receiver<HistoryWrite>, first: (PathBuf, String)) { |
| 221 | let mut pending = vec![first]; |
| 222 | #[cfg(test)] |
| 223 | let mut flush = None; |
| 224 | |
| 225 | loop { |
| 226 | match rx.recv_timeout(Duration::from_millis(2)) { |
| 227 | Ok(HistoryWrite::Append(path, entry)) => pending.push((path, entry)), |
| 228 | #[cfg(test)] |
| 229 | Ok(HistoryWrite::Flush(done)) => { |
| 230 | flush = Some(done); |
| 231 | break; |
| 232 | } |
| 233 | Err(RecvTimeoutError::Timeout) => break, |
| 234 | Err(RecvTimeoutError::Disconnected) => break, |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | for (path, entries) in group_history_writes_by_path(pending) { |
| 239 | append_history_entries_to(&path, entries.iter().map(String::as_str)); |
| 240 | } |
| 241 | |
| 242 | #[cfg(test)] |
| 243 | if let Some(done) = flush { |
| 244 | let _ = done.send(()); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | fn group_history_writes_by_path(writes: Vec<(PathBuf, String)>) -> Vec<(PathBuf, Vec<String>)> { |
| 249 | let mut grouped: Vec<(PathBuf, Vec<String>)> = Vec::new(); |
| 250 | |
| 251 | for (path, entry) in writes { |
| 252 | if let Some((_, entries)) = grouped |
| 253 | .iter_mut() |
| 254 | .find(|(existing_path, _)| existing_path == &path) |
| 255 | { |
| 256 | entries.push(entry); |
| 257 | } else { |
| 258 | grouped.push((path, vec![entry])); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | grouped |
| 263 | } |
| 264 | |
| 265 | fn append_history_to(path: &Path, entry: &str) { |
| 266 | append_history_entries_to(path, std::iter::once(entry)); |
| 267 | } |
| 268 | |
| 269 | /// Keep immediate recall and persisted history on the same duplicate rule. |
| 270 | /// Callers choose whether to preserve the submitted whitespace in their copy. |
| 271 | pub(crate) fn push_history_entry(entries: &mut Vec<String>, entry: &str) -> bool { |
| 272 | let trimmed = entry.trim(); |
| 273 | if trimmed.is_empty() || entries.last().is_some_and(|last| last.trim() == trimmed) { |
| 274 | return false; |
| 275 | } |
| 276 | entries.push(entry.to_string()); |
| 277 | true |
| 278 | } |
| 279 | |
| 280 | fn append_history_entries_to<'a>( |
| 281 | path: &Path, |
| 282 | entries_to_append: impl IntoIterator<Item = &'a str>, |
| 283 | ) { |
| 284 | if let Some(parent) = path.parent() |
| 285 | && let Err(err) = fs::create_dir_all(parent) |
| 286 | { |
| 287 | tracing::warn!( |
| 288 | "Failed to create composer history dir {}: {err}", |
| 289 | parent.display() |
| 290 | ); |
| 291 | return; |
| 292 | } |
| 293 | |
| 294 | // Read existing entries, append the new ones, prune from the front |
| 295 | // until under the cap, then atomically rewrite. |
| 296 | let mut entries = match read_history_from(path) { |
| 297 | Ok(entries) => entries, |
| 298 | Err(err) => { |
| 299 | tracing::warn!( |
| 300 | "Not rewriting composer history at {}: reading it failed: {err}", |
| 301 | path.display() |
| 302 | ); |
| 303 | return; |
| 304 | } |
| 305 | }; |
| 306 | let mut changed = false; |
| 307 | for entry in entries_to_append { |
| 308 | changed |= push_history_entry(&mut entries, entry.trim()); |
| 309 | } |
| 310 | |
| 311 | if !changed { |
| 312 | return; |
| 313 | } |
| 314 | |
| 315 | if entries.len() > MAX_HISTORY_ENTRIES { |
| 316 | let excess = entries.len() - MAX_HISTORY_ENTRIES; |
| 317 | entries.drain(0..excess); |
| 318 | } |
| 319 | |
| 320 | let payload = entries |
| 321 | .iter() |
| 322 | .map(|entry| serde_json::to_string(entry).expect("serializing a string cannot fail")) |
| 323 | .collect::<Vec<_>>() |
| 324 | .join("\n") |
| 325 | + "\n"; |
| 326 | if let Err(err) = write_history_atomic(path, payload.as_bytes()) { |
| 327 | tracing::warn!( |
| 328 | "Failed to persist composer history at {}: {err}", |
| 329 | path.display() |
| 330 | ); |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | fn write_history_atomic(path: &Path, payload: &[u8]) -> std::io::Result<()> { |
| 335 | const RETRY_DELAYS: &[Duration] = &[ |
| 336 | Duration::from_millis(5), |
| 337 | Duration::from_millis(10), |
| 338 | Duration::from_millis(25), |
| 339 | Duration::from_millis(50), |
| 340 | Duration::from_millis(100), |
| 341 | Duration::from_millis(200), |
| 342 | Duration::from_millis(400), |
| 343 | ]; |
| 344 | |
| 345 | for (attempt, delay) in RETRY_DELAYS |
| 346 | .iter() |
| 347 | .map(Some) |
| 348 | .chain(std::iter::once(None)) |
| 349 | .enumerate() |
| 350 | { |
| 351 | match codewhale_util::utils::write_atomic(path, payload) { |
| 352 | Ok(()) => return Ok(()), |
| 353 | Err(err) if delay.is_some() => { |
| 354 | tracing::debug!( |
| 355 | "Retrying composer history write to {} after attempt {} failed: {err}", |
| 356 | path.display(), |
| 357 | attempt + 1 |
| 358 | ); |
| 359 | std::thread::sleep(*delay.expect("delay checked")); |
| 360 | } |
| 361 | Err(err) => return Err(err), |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | unreachable!("retry iterator always ends with a final write attempt") |
| 366 | } |
| 367 | |
| 368 | #[cfg(test)] |
| 369 | pub(crate) fn flush_history_writer_for_tests(timeout: Duration) { |
| 370 | let (done_tx, done_rx) = channel(); |
| 371 | writer_sender() |
| 372 | .send(HistoryWrite::Flush(done_tx)) |
| 373 | .expect("history writer accepts flush"); |
| 374 | done_rx |
| 375 | .recv_timeout(timeout) |
| 376 | .expect("history writer flush timed out"); |
| 377 | } |
| 378 | |
| 379 | #[cfg(test)] |
| 380 | mod tests { |
| 381 | use super::*; |
| 382 | use std::time::{Duration, Instant}; |
| 383 | |
| 384 | /// Tests use the path-injecting `*_from` / `*_to` helpers so they |
| 385 | /// don't have to mutate `HOME` (which is not honored by |
| 386 | /// `codewhale_paths::user_home()` on Windows — it reads `USERPROFILE` / |
| 387 | /// `SHGetKnownFolderPath` instead). This makes the suite portable |
| 388 | /// across all three CI runners without per-platform env juggling. |
| 389 | fn temp_history_path() -> (tempfile::TempDir, PathBuf) { |
| 390 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 391 | let path = tmp.path().join(HISTORY_FILE_NAME); |
| 392 | (tmp, path) |
| 393 | } |
| 394 | |
| 395 | // #3240: a fresh install must resolve the history file under `.codewhale`, |
| 396 | // never the legacy `.deepseek` dir, so normal use doesn't recreate it. |
| 397 | #[test] |
| 398 | fn fresh_install_uses_codewhale_not_legacy() { |
| 399 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 400 | let path = history_path_with_home(Some(tmp.path().to_path_buf())) |
| 401 | .expect("path resolves with a home dir"); |
| 402 | assert_eq!(path, tmp.path().join(".codewhale").join(HISTORY_FILE_NAME)); |
| 403 | assert!( |
| 404 | !path.starts_with(tmp.path().join(".deepseek")), |
| 405 | "fresh install must not target the legacy .deepseek dir: {path:?}" |
| 406 | ); |
| 407 | } |
| 408 | |
| 409 | // Migration care: an existing legacy text history keeps its root and |
| 410 | // survives the first JSONL write byte-for-byte. |
| 411 | #[test] |
| 412 | fn existing_legacy_history_is_still_used() { |
| 413 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 414 | let legacy = tmp.path().join(".deepseek").join(LEGACY_HISTORY_FILE_NAME); |
| 415 | fs::create_dir_all(legacy.parent().expect("legacy parent")).expect("mkdir legacy"); |
| 416 | fs::write(&legacy, "old entry\n").expect("seed legacy history"); |
| 417 | let path = history_path_with_home(Some(tmp.path().to_path_buf())).expect("path resolves"); |
| 418 | assert_eq!(path, legacy.with_file_name(HISTORY_FILE_NAME)); |
| 419 | assert_eq!(load_history_from(&path), ["old entry"]); |
| 420 | append_history_to(&path, "new\nentry"); |
| 421 | assert_eq!(load_history_from(&path), ["old entry", "new\nentry"]); |
| 422 | assert_eq!(fs::read_to_string(&legacy).unwrap(), "old entry\n"); |
| 423 | } |
| 424 | |
| 425 | // Once a `.codewhale` history exists it wins over either legacy format. |
| 426 | #[test] |
| 427 | fn codewhale_history_preferred_over_legacy() { |
| 428 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 429 | let primary = tmp.path().join(".codewhale").join(LEGACY_HISTORY_FILE_NAME); |
| 430 | let legacy = tmp.path().join(".deepseek").join(HISTORY_FILE_NAME); |
| 431 | for p in [&primary, &legacy] { |
| 432 | fs::create_dir_all(p.parent().expect("parent")).expect("mkdir"); |
| 433 | fs::write(p, "x\n").expect("seed"); |
| 434 | } |
| 435 | let path = history_path_with_home(Some(tmp.path().to_path_buf())).expect("path resolves"); |
| 436 | assert_eq!(path, primary.with_file_name(HISTORY_FILE_NAME)); |
| 437 | } |
| 438 | |
| 439 | #[test] |
| 440 | fn append_and_load_round_trip() { |
| 441 | let (_tmp, path) = temp_history_path(); |
| 442 | append_history_to(&path, "first"); |
| 443 | append_history_to(&path, "second"); |
| 444 | append_history_to(&path, "third"); |
| 445 | assert_eq!(load_history_from(&path), vec!["first", "second", "third"]); |
| 446 | } |
| 447 | |
| 448 | #[test] |
| 449 | fn slash_commands_and_absolute_paths_stored() { |
| 450 | let (_tmp, path) = temp_history_path(); |
| 451 | append_history_to(&path, "/help"); |
| 452 | append_history_to(&path, "real prompt"); |
| 453 | append_history_to(&path, "/cost"); |
| 454 | append_history_to(&path, "cat /etc/fstab"); |
| 455 | assert_eq!( |
| 456 | load_history_from(&path), |
| 457 | vec!["/help", "real prompt", "/cost", "cat /etc/fstab"] |
| 458 | ); |
| 459 | } |
| 460 | |
| 461 | #[test] |
| 462 | fn multi_line_entries_round_trip_as_one_entry() { |
| 463 | let (_tmp, path) = temp_history_path(); |
| 464 | append_history_to(&path, "first"); |
| 465 | append_history_to(&path, "fn main() {\n run();\n}"); |
| 466 | append_history_to(&path, "\"quoted\" start"); |
| 467 | append_history_to(&path, "last"); |
| 468 | assert_eq!( |
| 469 | load_history_from(&path), |
| 470 | vec![ |
| 471 | "first", |
| 472 | "fn main() {\n run();\n}", |
| 473 | "\"quoted\" start", |
| 474 | "last" |
| 475 | ] |
| 476 | ); |
| 477 | // The same multi-line prompt twice is still one consecutive duplicate. |
| 478 | append_history_to(&path, "a\nb"); |
| 479 | append_history_to(&path, "a\nb"); |
| 480 | assert_eq!(load_history_from(&path).len(), 5); |
| 481 | } |
| 482 | |
| 483 | #[test] |
| 484 | fn legacy_plain_quoted_lines_keep_their_quotes() { |
| 485 | let (_tmp, path) = temp_history_path(); |
| 486 | // Older writers trimmed entries and stored every remaining byte raw. |
| 487 | // JSON-looking strings are user text, even when decoding and encoding |
| 488 | // them would round-trip: the escapes must not turn into control chars. |
| 489 | let legacy = [r#""yes""#, r#""a" and "b""#, r#""a\nb""#, r#""\"quoted\"""#]; |
| 490 | let legacy_path = path.with_file_name(LEGACY_HISTORY_FILE_NAME); |
| 491 | let original = legacy.join("\n") + "\n"; |
| 492 | fs::write(&legacy_path, &original).expect("seed legacy file"); |
| 493 | assert_eq!(load_history_from(&path), legacy); |
| 494 | // Rewriting on the next append must preserve every legacy prompt. |
| 495 | append_history_to(&path, "next\nline"); |
| 496 | let expected: Vec<String> = legacy |
| 497 | .into_iter() |
| 498 | .chain(["next\nline"]) |
| 499 | .map(str::to_string) |
| 500 | .collect(); |
| 501 | assert_eq!(load_history_from(&path), expected); |
| 502 | assert_eq!(fs::read_to_string(&legacy_path).unwrap(), original); |
| 503 | } |
| 504 | |
| 505 | #[test] |
| 506 | fn malformed_json_records_stay_literal() { |
| 507 | let (_tmp, path) = temp_history_path(); |
| 508 | fs::write(&path, "malformed record").expect("seed malformed record"); |
| 509 | assert_eq!(load_history_from(&path), ["malformed record"]); |
| 510 | append_history_to(&path, "next"); |
| 511 | assert_eq!(load_history_from(&path), ["malformed record", "next"]); |
| 512 | } |
| 513 | |
| 514 | #[test] |
| 515 | fn consecutive_duplicate_commands_deduped() { |
| 516 | let (_tmp, path) = temp_history_path(); |
| 517 | append_history_to(&path, "/theme"); |
| 518 | append_history_to(&path, "/theme"); |
| 519 | append_history_to(&path, "/theme"); |
| 520 | assert_eq!(load_history_from(&path), vec!["/theme"]); |
| 521 | } |
| 522 | |
| 523 | #[test] |
| 524 | fn empty_and_whitespace_skipped() { |
| 525 | let (_tmp, path) = temp_history_path(); |
| 526 | append_history_to(&path, ""); |
| 527 | append_history_to(&path, " "); |
| 528 | append_history_to(&path, "\n\t"); |
| 529 | append_history_to(&path, "real"); |
| 530 | assert_eq!(load_history_from(&path), vec!["real"]); |
| 531 | } |
| 532 | |
| 533 | #[test] |
| 534 | fn consecutive_duplicates_deduped() { |
| 535 | let (_tmp, path) = temp_history_path(); |
| 536 | append_history_to(&path, "same"); |
| 537 | append_history_to(&path, "same"); |
| 538 | append_history_to(&path, "same"); |
| 539 | append_history_to(&path, "different"); |
| 540 | append_history_to(&path, "same"); |
| 541 | assert_eq!(load_history_from(&path), vec!["same", "different", "same"]); |
| 542 | } |
| 543 | |
| 544 | #[test] |
| 545 | fn pruned_to_cap_at_append_time() { |
| 546 | let (_tmp, path) = temp_history_path(); |
| 547 | // One batched rewrite — a per-entry loop would fsync 1000+ times. |
| 548 | let entries: Vec<String> = (0..(MAX_HISTORY_ENTRIES + 50)) |
| 549 | .map(|i| format!("entry {i}")) |
| 550 | .collect(); |
| 551 | append_history_entries_to(&path, entries.iter().map(String::as_str)); |
| 552 | let history = load_history_from(&path); |
| 553 | assert_eq!(history.len(), MAX_HISTORY_ENTRIES); |
| 554 | // Newest entries survive; oldest 50 were pruned. |
| 555 | assert_eq!(history.first().map(String::as_str), Some("entry 50")); |
| 556 | assert_eq!( |
| 557 | history.last().map(String::as_str), |
| 558 | Some(format!("entry {}", MAX_HISTORY_ENTRIES + 49)).as_deref() |
| 559 | ); |
| 560 | |
| 561 | // Keep a cheap boundary check on the singleton production wrapper: |
| 562 | // seed to one below the cap in one write, then cross it with only two |
| 563 | // fsyncing appends. The second append must prune exactly the oldest |
| 564 | // entry rather than only enforcing the cap for batched callers. |
| 565 | let (_boundary_tmp, boundary_path) = temp_history_path(); |
| 566 | let seeded: Vec<String> = (0..(MAX_HISTORY_ENTRIES - 1)) |
| 567 | .map(|i| format!("entry {i}")) |
| 568 | .collect(); |
| 569 | append_history_entries_to(&boundary_path, seeded.iter().map(String::as_str)); |
| 570 | append_history_to( |
| 571 | &boundary_path, |
| 572 | &format!("entry {}", MAX_HISTORY_ENTRIES - 1), |
| 573 | ); |
| 574 | append_history_to(&boundary_path, &format!("entry {MAX_HISTORY_ENTRIES}")); |
| 575 | let boundary = load_history_from(&boundary_path); |
| 576 | assert_eq!(boundary.len(), MAX_HISTORY_ENTRIES); |
| 577 | assert_eq!(boundary.first().map(String::as_str), Some("entry 1")); |
| 578 | assert_eq!( |
| 579 | boundary.last().map(String::as_str), |
| 580 | Some(format!("entry {MAX_HISTORY_ENTRIES}")).as_deref() |
| 581 | ); |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn missing_file_loads_empty() { |
| 586 | let (_tmp, path) = temp_history_path(); |
| 587 | assert!(load_history_from(&path).is_empty()); |
| 588 | } |
| 589 | |
| 590 | #[test] |
| 591 | fn invalid_utf8_line_is_skipped_without_dropping_valid_history() { |
| 592 | let (_tmp, path) = temp_history_path(); |
| 593 | let mut bytes = Vec::new(); |
| 594 | bytes.extend_from_slice(b"\"before corruption\"\n"); |
| 595 | bytes.extend_from_slice(b"bad \xff\xfe bytes\n"); |
| 596 | bytes.extend_from_slice(b"\"after corruption\"\n"); |
| 597 | std::fs::write(&path, bytes).expect("write history with corrupt line"); |
| 598 | |
| 599 | assert_eq!( |
| 600 | load_history_from(&path), |
| 601 | vec![ |
| 602 | "before corruption".to_string(), |
| 603 | "after corruption".to_string(), |
| 604 | ] |
| 605 | ); |
| 606 | |
| 607 | append_history_to(&path, "new entry"); |
| 608 | assert_eq!( |
| 609 | load_history_from(&path), |
| 610 | vec![ |
| 611 | "before corruption".to_string(), |
| 612 | "after corruption".to_string(), |
| 613 | "new entry".to_string(), |
| 614 | ] |
| 615 | ); |
| 616 | } |
| 617 | |
| 618 | /// Regression for #1927 — the dispatched append path must return |
| 619 | /// promptly even when a synchronous write of the seeded file would |
| 620 | /// be slow. We pre-populate the file with ~1000 entries (the cap) |
| 621 | /// so a sync read-modify-write would take real disk time on any |
| 622 | /// platform, then call `append_history_dispatched` many times and |
| 623 | /// assert that the cumulative wall-clock cost stays well below the |
| 624 | /// stall the user reports. |
| 625 | #[test] |
| 626 | fn append_history_dispatched_does_not_block_the_caller() { |
| 627 | let (_tmp, path) = temp_history_path(); |
| 628 | // Seed close to the cap so a synchronous rewrite is non-trivial. |
| 629 | let seed = (0..(MAX_HISTORY_ENTRIES - 50)) |
| 630 | .map(|i| format!("seed entry {i}")) |
| 631 | .collect::<Vec<_>>() |
| 632 | .join("\n") |
| 633 | + "\n"; |
| 634 | std::fs::write(&path, seed).expect("seed history"); |
| 635 | |
| 636 | let start = Instant::now(); |
| 637 | for i in 0..50 { |
| 638 | append_history_dispatched(&path, &format!("new entry {i}")); |
| 639 | } |
| 640 | let dispatch_elapsed = start.elapsed(); |
| 641 | |
| 642 | // 50 sync read-modify-write cycles on a ~200KB file would be |
| 643 | // measurable (tens of ms even on a fast SSD). The dispatch path |
| 644 | // hands work to the writer thread and returns; the whole loop |
| 645 | // should finish in single-digit ms. Pick a generous CI-safe |
| 646 | // bound that still catches a regression to the old sync path. |
| 647 | assert!( |
| 648 | dispatch_elapsed < Duration::from_millis(150), |
| 649 | "append_history dispatch was too slow: {dispatch_elapsed:?} \ |
| 650 | (likely re-introduced #1927: caller blocked on disk write)" |
| 651 | ); |
| 652 | |
| 653 | flush_history_writer_for_tests(Duration::from_secs(if cfg!(windows) { 10 } else { 5 })); |
| 654 | |
| 655 | let loaded = load_history_from(&path); |
| 656 | assert!( |
| 657 | loaded.iter().any(|line| line == "new entry 49"), |
| 658 | "writer thread did not persist the dispatched entries; \ |
| 659 | loaded {} entries, last = {:?}", |
| 660 | loaded.len(), |
| 661 | loaded.last() |
| 662 | ); |
| 663 | assert!(loaded.iter().any(|line| line == "new entry 0")); |
| 664 | } |
| 665 | } |
| 666 |