Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/tokscale-cli/src/tui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -243,6 +251,7 @@ fn restore_terminal_best_effort() {
}

fn restore_terminal(terminal: &mut Terminal<CrosstermBackend<io::Stdout>>) {
tokscale_core::tui_signal::set_tui_active(false);
let _ = disable_raw_mode();
let _ = execute!(
terminal.backend_mut(),
Expand Down
45 changes: 34 additions & 11 deletions crates/tokscale-core/src/fs_atomic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
1 change: 1 addition & 0 deletions crates/tokscale-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down
10 changes: 8 additions & 2 deletions crates/tokscale-core/src/message_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Mutex<HashSet<&'static str>>> = 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());
}
}
Expand Down
35 changes: 35 additions & 0 deletions crates/tokscale-core/src/tui_signal.rs
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading