From 5b3810310b18aac2abfceb104202ffa30a5a18bd Mon Sep 17 00:00:00 2001 From: Junho Yeo Date: Fri, 17 Jul 2026 02:47:40 +0900 Subject: [PATCH 1/2] fix(tui): stop background cache-warning writes from corrupting TUI screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The TUI's screen occasionally gets scrolled/corrupted on a background cache save failure (#893). Two stackable root causes: 1. On Windows, MoveFileExW replacing the cache file is a well-known source of transient ERROR_ACCESS_DENIED/ERROR_SHARING_VIOLATION when AV/indexer/cloud-sync briefly holds a scan handle open on the just-written file. fs_atomic::windows_replace_file made a single attempt with no retry. 2. warn_cache_failure_once() falls back to a raw eprintln! the first time each failure context is seen, since most non-TUI commands never install a tracing subscriber. But the TUI only installs one under --debug, so in normal use that eprintln! is the only visible output — and it writes directly to stdio while the TUI owns raw mode and the crossterm alternate screen, corrupting the display. Fixes both: retry the Windows rename a few times with a short backoff on the specific transient errors (benefits all 10 existing fs_atomic::replace_file call sites, not just the cache), and add a process-wide tui_signal flag the TUI sets while it owns the terminal so the eprintln! fallback is suppressed during that window instead of corrupting the screen. Constraint: fs_atomic::replace_file is a single shared primitive used by 10 call sites across both crates — the retry must be transparent with no call-site changes Rejected: Redirect all cache warnings through the TUI's own status/error UI | would require threading a channel through every non-TUI call site too; the flag-gated eprintln! keeps non-TUI behavior byte-for-byte unchanged Confidence: high Scope-risk: narrow Not-tested: actual Windows MoveFileEx retry behavior, no Windows machine available in this environment — relying on build-native.yml CI's Windows job plus manual FFI review --- crates/tokscale-cli/src/tui/mod.rs | 9 +++++ crates/tokscale-core/src/fs_atomic.rs | 45 +++++++++++++++++------ crates/tokscale-core/src/lib.rs | 1 + crates/tokscale-core/src/message_cache.rs | 10 ++++- crates/tokscale-core/src/tui_signal.rs | 35 ++++++++++++++++++ 5 files changed, 87 insertions(+), 13 deletions(-) create mode 100644 crates/tokscale-core/src/tui_signal.rs diff --git a/crates/tokscale-cli/src/tui/mod.rs b/crates/tokscale-cli/src/tui/mod.rs index 9ef43ba4f..5d11ac25e 100644 --- a/crates/tokscale-cli/src/tui/mod.rs +++ b/crates/tokscale-cli/src/tui/mod.rs @@ -146,6 +146,13 @@ pub fn run( return Err(e.into()); } + // From here on the TUI owns raw mode and the alternate screen for its + // whole run. Background diagnostics (e.g. cache save warnings) must not + // write raw stdio while this is set, or they corrupt the rendered + // display instead of being visible as a log line. Cleared in both + // `restore_terminal` and `restore_terminal_best_effort` below. + tokscale_core::tui_signal::set_tui_active(true); + let backend = CrosstermBackend::new(stdout); let terminal_result = Terminal::new(backend); let mut terminal = match terminal_result { @@ -233,6 +240,7 @@ pub fn run( } fn restore_terminal_best_effort() { + tokscale_core::tui_signal::set_tui_active(false); let _ = execute!( io::stdout(), LeaveAlternateScreen, @@ -243,6 +251,7 @@ fn restore_terminal_best_effort() { } fn restore_terminal(terminal: &mut Terminal>) { + tokscale_core::tui_signal::set_tui_active(false); let _ = disable_raw_mode(); let _ = execute!( terminal.backend_mut(), diff --git a/crates/tokscale-core/src/fs_atomic.rs b/crates/tokscale-core/src/fs_atomic.rs index 876c2a0b5..cfe7ae262 100644 --- a/crates/tokscale-core/src/fs_atomic.rs +++ b/crates/tokscale-core/src/fs_atomic.rs @@ -36,18 +36,41 @@ fn windows_replace_file(tmp_path: &Path, final_path: &Path) -> io::Result<()> { .collect() } + // MoveFileExW replacing an existing file is a well-known source of + // transient ERROR_ACCESS_DENIED (5) / ERROR_SHARING_VIOLATION (32) on + // Windows: antivirus, indexing, and cloud-sync agents routinely hold a + // brief scan handle open on a just-written file. Retry a handful of + // times with a short backoff before giving up, rather than surfacing a + // one-shot failure for what is usually a few-millisecond lock. + const ERROR_ACCESS_DENIED: i32 = 5; + const ERROR_SHARING_VIOLATION: i32 = 32; + const MAX_ATTEMPTS: u32 = 5; + let existing = encode(tmp_path); let new = encode(final_path); - let result = unsafe { - MoveFileExW( - existing.as_ptr(), - new.as_ptr(), - MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, - ) - }; - if result == 0 { - Err(io::Error::last_os_error()) - } else { - Ok(()) + + for attempt in 1..=MAX_ATTEMPTS { + let result = unsafe { + MoveFileExW( + existing.as_ptr(), + new.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + }; + if result != 0 { + return Ok(()); + } + + let error = io::Error::last_os_error(); + let is_retryable = matches!( + error.raw_os_error(), + Some(ERROR_ACCESS_DENIED) | Some(ERROR_SHARING_VIOLATION) + ); + if !is_retryable || attempt == MAX_ATTEMPTS { + return Err(error); + } + std::thread::sleep(std::time::Duration::from_millis(10 * attempt as u64)); } + + unreachable!("loop always returns on its final attempt") } diff --git a/crates/tokscale-core/src/lib.rs b/crates/tokscale-core/src/lib.rs index f55e58258..dcf5581bd 100644 --- a/crates/tokscale-core/src/lib.rs +++ b/crates/tokscale-core/src/lib.rs @@ -15,6 +15,7 @@ mod provider_identity; pub mod scanner; pub mod sessionize; pub mod sessions; +pub mod tui_signal; pub mod wiki; pub use aggregator::*; diff --git a/crates/tokscale-core/src/message_cache.rs b/crates/tokscale-core/src/message_cache.rs index 41ebe539f..c67f61d92 100644 --- a/crates/tokscale-core/src/message_cache.rs +++ b/crates/tokscale-core/src/message_cache.rs @@ -102,10 +102,16 @@ fn warn_cache_failure_once(context: &'static str, path: &Path, error: &impl std: // Most non-TUI commands (including `submit`) do not install a tracing // subscriber. Surface persistence failures directly once per process so a - // permanently cold cache can never fail silently again. + // permanently cold cache can never fail silently again. The TUI owns raw + // mode and the alternate screen for its whole run, so a raw stdio write + // there corrupts the rendered display instead of being visible as a log + // line — suppress it in that case and rely on tracing::warn! (or the + // TUI's own status/error UI) instead. static WARNED_CONTEXTS: OnceLock>> = OnceLock::new(); let warned = WARNED_CONTEXTS.get_or_init(|| Mutex::new(HashSet::new())); - if warned.lock().is_ok_and(|mut warned| warned.insert(context)) { + if warned.lock().is_ok_and(|mut warned| warned.insert(context)) + && !crate::tui_signal::is_tui_active() + { eprintln!("tokscale: warning: {context} ({}): {error}", path.display()); } } diff --git a/crates/tokscale-core/src/tui_signal.rs b/crates/tokscale-core/src/tui_signal.rs new file mode 100644 index 000000000..f91717a6f --- /dev/null +++ b/crates/tokscale-core/src/tui_signal.rs @@ -0,0 +1,35 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + +// Some diagnostics (e.g. cache save failures) fall back to a direct +// eprintln! when no tracing subscriber is guaranteed to be installed, so +// non-TUI commands still surface them. The TUI owns raw mode and the +// crossterm alternate screen for its whole lifetime, and a stray stdio +// write there corrupts the rendered display instead of being visible as a +// normal log line. This flag lets that diagnostic code suppress the raw +// stdio fallback while the TUI holds the terminal. +static TUI_ACTIVE: AtomicBool = AtomicBool::new(false); + +pub fn set_tui_active(active: bool) { + TUI_ACTIVE.store(active, Ordering::Relaxed); +} + +pub fn is_tui_active() -> bool { + TUI_ACTIVE.load(Ordering::Relaxed) +} + +#[cfg(test)] +mod tests { + use super::*; + use serial_test::serial; + + #[test] + #[serial] + fn round_trips() { + let previous = is_tui_active(); + set_tui_active(true); + assert!(is_tui_active()); + set_tui_active(false); + assert!(!is_tui_active()); + set_tui_active(previous); + } +} From eb31d945992416ca0db0172c8acee2c2262bbcc7 Mon Sep 17 00:00:00 2001 From: Junho Yeo Date: Fri, 17 Jul 2026 03:48:13 +0900 Subject: [PATCH 2/2] chore: apply cargo fmt to pre-existing main drift CI's Lint job runs cargo fmt --all -- --check across the whole workspace, not just this PR's diff. Two unrelated files on main had already drifted out of rustfmt's canonical form before this branch forked, which was failing this PR's Lint check despite neither file being touched by the TUI fix itself. Constraint: cargo fmt --all -- --check must pass workspace-wide, not just on changed files Confidence: high Scope-risk: narrow --- crates/tokscale-core/src/pricing/lookup.rs | 6 +----- crates/tokscale-core/src/sessions/claudecode.rs | 3 +-- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/crates/tokscale-core/src/pricing/lookup.rs b/crates/tokscale-core/src/pricing/lookup.rs index 2c147ec3f..203e74e97 100644 --- a/crates/tokscale-core/src/pricing/lookup.rs +++ b/crates/tokscale-core/src/pricing/lookup.rs @@ -2806,11 +2806,7 @@ mod tests { "google/gemini-3.5-flash", "Models.dev", ), - ( - "gemini-3-flash-b", - "google/gemini-3.5-flash", - "Models.dev", - ), + ("gemini-3-flash-b", "google/gemini-3.5-flash", "Models.dev"), ( // Legacy CLI responseModel for M132, the retired predecessor // of M133 — prices as the High tier, same catalog entry as diff --git a/crates/tokscale-core/src/sessions/claudecode.rs b/crates/tokscale-core/src/sessions/claudecode.rs index f52f7597f..faa441f7d 100644 --- a/crates/tokscale-core/src/sessions/claudecode.rs +++ b/crates/tokscale-core/src/sessions/claudecode.rs @@ -901,8 +901,7 @@ fn merge_claude_duplicate( // streaming chunks), so never let a later-processed duplicate // with an earlier completion timestamp shrink a duration // already established by another duplicate. - existing.duration_ms = - Some(existing.duration_ms.unwrap_or(0).max(new_duration)); + existing.duration_ms = Some(existing.duration_ms.unwrap_or(0).max(new_duration)); } } }