返回 CodeWhale
runtime_log.rs
根目录 / crates / runtime / src / runtime_log.rs
1 //! TUI runtime logging. Initializes a `tracing-subscriber` that writes to a
2 //! per-process file under `~/.codewhale/logs/tui-YYYY-MM-DD-PID.log`, and (on
3 //! Unix and Windows) redirects the process's `stderr` handle/fd to that same
4 //! file for the lifetime of the alt-screen TUI.
5 //!
6 //! Why this exists:
7 //!
8 //! The TUI runs inside an alt-screen buffer drawn by `ratatui` using an
9 //! incremental diff renderer. The renderer assumes nothing else is writing
10 //! to the terminal — its internal "current cells" model is the only source
11 //! of truth for what's on screen. If anything emits raw bytes to stdout or
12 //! stderr while the alt-screen is active (an `eprintln!` from a sub-agent,
13 //! a `tracing` warning that defaulted to `stderr`, a panic message, a
14 //! third-party crate's verbose output, …) those bytes land in the alt-screen
15 //! buffer at the current cursor position, scroll the buffer up, and leave
16 //! the renderer's model out of sync with reality. The visible symptom is
17 //! "scroll demon": the TUI content drifts down, leaving a band of blank
18 //! rows above the header. This was the regression in issue #1085 (fixed in
19 //! v0.8.18 by adding a viewport-reset path) and re-surfaced in v0.8.27
20 //! when the flicker fix dropped the `\x1b[2J\x1b[3J` deep-clear that had
21 //! been masking the underlying leak.
22 //!
23 //! Defence-in-depth:
24 //! 1. A `tracing-subscriber` writes formatted logs to
25 //! `~/.codewhale/logs/tui-YYYY-MM-DD-PID.log` so `tracing::warn!` /
26 //! `tracing::error!` calls go somewhere observable instead of
27 //! disappearing into the void (the TUI previously had no global
28 //! subscriber, so contributors reached for `eprintln!`).
29 //! 2. On Unix and Windows the process's stderr handle/fd is redirected to
30 //! the same log file for the lifetime of `TuiLogGuard`. Any raw stderr
31 //! write — ours, a dependency's, a panic message — lands in the log
32 //! file instead of the alt-screen. The guard restores the original
33 //! stderr handle/fd on drop so post-TUI shutdown messages still reach
34 //! the user's terminal.
35 //! 3. Crate-level `#![deny(clippy::print_stderr, clippy::print_stdout)]`
36 //! on the TUI runtime modules forbids new `eprintln!` / `println!`
37 //! calls at compile time. CLI-output paths (`main.rs` eval, init,
38 //! `runtime_api::print_*`, `logging::info`/`warn`) keep their existing
39 //! prints via `#[allow(clippy::print_stderr)]` because they run before
40 //! the alt-screen is entered.
41
42 use std::fs::{self, File, OpenOptions};
43 use std::path::{Path, PathBuf};
44 use std::time::{Duration, SystemTime};
45
46 use anyhow::{Context, Result};
47 use tracing_subscriber::{EnvFilter, fmt, prelude::*};
48
49 const DEFAULT_LOG_RETENTION_DAYS: u64 = 7;
50 const LOG_RETENTION_ENV: &str = "DEEPSEEK_LOG_RETENTION_DAYS";
51 const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
52
53 /// Owns the active tracing subscriber and (on Unix/Windows) a saved copy of
54 /// the original `stderr` handle/fd so it can be restored on drop. Dropped when
55 /// the TUI exits the alt-screen.
56 pub struct TuiLogGuard {
57 #[cfg(unix)]
58 saved_stderr_fd: Option<libc::c_int>,
59 #[cfg(windows)]
60 saved_stderr_handle: Option<windows::Win32::Foundation::HANDLE>,
61 #[cfg(windows)]
62 redirected_stderr_handle: Option<windows::Win32::Foundation::HANDLE>,
63 _file: File,
64 }
65
66 #[cfg(unix)]
67 impl Drop for TuiLogGuard {
68 fn drop(&mut self) {
69 if let Some(saved) = self.saved_stderr_fd.take() {
70 // SAFETY: `saved` came from `libc::dup` of the original stderr
71 // fd in `init`; calling `dup2` to restore it is the standard
72 // pairing. If `dup2` fails we just leak the saved fd — the
73 // process is exiting anyway.
74 unsafe {
75 let _ = libc::dup2(saved, libc::STDERR_FILENO);
76 let _ = libc::close(saved);
77 }
78 }
79 }
80 }
81
82 #[cfg(windows)]
83 impl Drop for TuiLogGuard {
84 fn drop(&mut self) {
85 if let Some(handle) = self.saved_stderr_handle.take() {
86 // SAFETY: `handle` is owned here via take; Drop runs once.
87 unsafe {
88 let _ = windows::Win32::System::Console::SetStdHandle(
89 windows::Win32::System::Console::STD_ERROR_HANDLE,
90 handle,
91 );
92 }
93 }
94 // Close the duplicated handle that was serving as the redirected
95 // stderr target. This is safe because `SetStdHandle` above already
96 // restored the original handle, so nothing references this one.
97 if let Some(dup) = self.redirected_stderr_handle.take() {
98 // SAFETY: `dup` is owned here via take; nothing references it.
99 unsafe {
100 let _ = windows::Win32::Foundation::CloseHandle(dup);
101 }
102 }
103 }
104 }
105
106 #[cfg(not(any(unix, windows)))]
107 impl Drop for TuiLogGuard {
108 fn drop(&mut self) {}
109 }
110
111 /// Initialize the TUI logging subsystem. Idempotent across re-entry by way
112 /// of `set_default` — if a global subscriber is already set we still install
113 /// the stderr redirect.
114 ///
115 /// Returns a guard that must outlive the alt-screen session. Drop it after
116 /// `LeaveAlternateScreen` so any shutdown messages reach the user.
117 pub fn init() -> Result<TuiLogGuard> {
118 let log_dir = log_directory().context("could not resolve TUI log directory")?;
119 fs::create_dir_all(&log_dir)
120 .with_context(|| format!("failed to create {}", log_dir.display()))?;
121 let _ = prune_old_logs(&log_dir, log_retention_days());
122
123 let date = chrono::Local::now().format("%Y-%m-%d").to_string();
124 let log_path = log_dir.join(log_file_name(&date, std::process::id()));
125
126 let file = open_log_file(&log_path)
127 .with_context(|| format!("failed to open {}", log_path.display()))?;
128
129 // The tracing-subscriber consumes a clone of the file handle for its
130 // writer. We keep our own handle for the dup2 redirect below — we need
131 // the same on-disk file but a separate fd so the subscriber's writes
132 // and the raw-stderr writes don't fight over the same kernel offset.
133 let subscriber_file = file
134 .try_clone()
135 .context("failed to clone log file handle for subscriber")?;
136
137 let env_filter = EnvFilter::try_from_default_env()
138 .or_else(|_| EnvFilter::try_new("info"))
139 .unwrap_or_else(|_| EnvFilter::new("info"));
140
141 let log_path_clone = log_path.clone();
142 let subscriber = tracing_subscriber::registry().with(env_filter).with(
143 fmt::layer()
144 .with_writer(move || -> Box<dyn std::io::Write + Send> {
145 // Clone the file handle for each write. If clone fails (fd exhaustion),
146 // fall back to reopening the same path, or ultimately stderr.
147 match subscriber_file.try_clone() {
148 Ok(f) => Box::new(f),
149 Err(e) => {
150 tracing::warn!("Failed to clone log file handle: {e}, reopening");
151 match open_log_file(&log_path_clone) {
152 Ok(f) => Box::new(f),
153 Err(_) => Box::new(std::io::stderr()),
154 }
155 }
156 }
157 })
158 .with_ansi(false)
159 .with_target(true)
160 .with_thread_ids(false),
161 );
162
163 // Best-effort: if a subscriber is already set (e.g., re-entry, or a
164 // host process installed one), we skip ours rather than panic. The
165 // stderr redirect below still happens.
166 let _ = tracing::subscriber::set_global_default(subscriber);
167
168 #[cfg(unix)]
169 let saved_stderr_fd = redirect_stderr_to(&file).ok();
170 #[cfg(windows)]
171 let (saved_stderr_handle, redirected_stderr_handle) = match redirect_stderr_to(&file) {
172 Ok((saved, dup)) => (Some(saved), Some(dup)),
173 Err(e) => {
174 tracing::warn!("Failed to redirect stderr to log file: {e}");
175 (None, None)
176 }
177 };
178
179 Ok(TuiLogGuard {
180 #[cfg(unix)]
181 saved_stderr_fd,
182 #[cfg(windows)]
183 saved_stderr_handle,
184 #[cfg(windows)]
185 redirected_stderr_handle,
186 _file: file,
187 })
188 }
189
190 /// Open (creating if needed) the per-process log for append. Logs can hold
191 /// prompts and paths, so on Unix the file is owner-only: created 0600, an
192 /// existing file is tightened to 0600, and a symlink at the log path is
193 /// refused (`O_NOFOLLOW`) instead of followed to wherever it points.
194 fn open_log_file(path: &Path) -> std::io::Result<std::fs::File> {
195 let mut options = OpenOptions::new();
196 options.create(true).append(true);
197 #[cfg(unix)]
198 {
199 use std::os::unix::fs::OpenOptionsExt as _;
200 options
201 .mode(0o600)
202 .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);
203 let file = options.open(path)?;
204 // Through the handle that was opened `O_NOFOLLOW`: re-resolving `path`
205 // here could narrow a substitute, and this log is the object the caller
206 // is about to write prompts and paths into. `tighten_mode_of` keeps the
207 // refusal for a filesystem that stores modes and excuses only one that
208 // cannot apply them, so a log still readable by group or other is
209 // reported rather than ignored.
210 codewhale_config::private_directory::tighten_mode_of(&file, path, 0o600)
211 .map_err(|error| std::io::Error::other(error.to_string()))?;
212 Ok(file)
213 }
214 #[cfg(not(unix))]
215 {
216 options.open(path)
217 }
218 }
219
220 pub fn log_directory() -> Option<PathBuf> {
221 // $CODEWHALE_HOME is a hard override of the base data directory
222 // (docs/CONFIGURATION.md): when SET, logs live under it and we do NOT fall
223 // back to the legacy ~/.deepseek path — silent fallback would defeat the
224 // isolation the override promises (CI, containers, test harnesses). We
225 // check the env var directly rather than codewhale_home()'s Ok/Err because
226 // that helper succeeds (returns $HOME/.codewhale) even when the override is
227 // unset, which would short-circuit the legacy fallback below.
228 if let Some(home) = codewhale_paths::codewhale_home_override().ok().flatten() {
229 return Some(home.join("logs"));
230 }
231 let resolve = |base: PathBuf| -> Option<PathBuf> {
232 let primary = base.join(".codewhale").join("logs");
233 if primary.exists() {
234 return Some(primary);
235 }
236 let legacy = base.join(".deepseek").join("logs");
237 if legacy.exists() {
238 return Some(legacy);
239 }
240 Some(primary)
241 };
242 codewhale_paths::user_home().and_then(resolve)
243 }
244
245 fn log_file_name(date: &str, pid: u32) -> String {
246 format!("tui-{date}-{pid}.log")
247 }
248
249 fn log_retention_days() -> u64 {
250 std::env::var(LOG_RETENTION_ENV)
251 .ok()
252 .and_then(|raw| raw.trim().parse::<u64>().ok())
253 .filter(|days| *days > 0)
254 .unwrap_or(DEFAULT_LOG_RETENTION_DAYS)
255 }
256
257 fn prune_old_logs(log_dir: &Path, retention_days: u64) -> std::io::Result<usize> {
258 let retention = Duration::from_secs(retention_days.saturating_mul(SECONDS_PER_DAY));
259 let cutoff = SystemTime::now()
260 .checked_sub(retention)
261 .unwrap_or(SystemTime::UNIX_EPOCH);
262 let mut removed = 0usize;
263
264 for entry in fs::read_dir(log_dir)? {
265 let entry = entry?;
266 if !is_tui_log_file_name(&entry.file_name()) {
267 continue;
268 }
269 let metadata = match entry.metadata() {
270 Ok(metadata) if metadata.is_file() => metadata,
271 _ => continue,
272 };
273 let modified = match metadata.modified() {
274 Ok(modified) => modified,
275 Err(_) => continue,
276 };
277 if modified < cutoff && fs::remove_file(entry.path()).is_ok() {
278 removed += 1;
279 }
280 }
281
282 Ok(removed)
283 }
284
285 fn is_tui_log_file_name(file_name: &std::ffi::OsStr) -> bool {
286 file_name
287 .to_str()
288 .is_some_and(|name| name.starts_with("tui-") && name.ends_with(".log"))
289 }
290
291 #[cfg(unix)]
292 fn redirect_stderr_to(file: &File) -> Result<libc::c_int> {
293 use std::os::fd::AsRawFd;
294 let target = file.as_raw_fd();
295 // SAFETY: `libc::dup` and `libc::dup2` are the documented fd-management
296 // primitives. We save the current stderr fd before reassigning so the
297 // guard can restore it on drop.
298 unsafe {
299 let saved = libc::dup(libc::STDERR_FILENO);
300 if saved < 0 {
301 return Err(
302 anyhow::Error::from(std::io::Error::last_os_error()).context("dup(STDERR_FILENO)")
303 );
304 }
305 if libc::dup2(target, libc::STDERR_FILENO) < 0 {
306 let err = std::io::Error::last_os_error();
307 let _ = libc::close(saved);
308 return Err(anyhow::Error::from(err).context("dup2(log_file, STDERR_FILENO)"));
309 }
310 Ok(saved)
311 }
312 }
313
314 #[cfg(windows)]
315 fn redirect_stderr_to(
316 file: &File,
317 ) -> Result<(
318 windows::Win32::Foundation::HANDLE,
319 windows::Win32::Foundation::HANDLE,
320 )> {
321 use std::os::windows::io::AsRawHandle;
322 use windows::Win32::Foundation::{CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE};
323 use windows::Win32::System::Console::{GetStdHandle, STD_ERROR_HANDLE, SetStdHandle};
324 use windows::Win32::System::Threading::GetCurrentProcess;
325
326 // SAFETY: GetStdHandle is always available; returns INVALID_HANDLE_VALUE
327 // on failure or null-like handles for console-less processes.
328 let saved =
329 unsafe { GetStdHandle(STD_ERROR_HANDLE) }.context("GetStdHandle(STD_ERROR_HANDLE)")?;
330 if saved.is_invalid() {
331 return Err(anyhow::anyhow!("GetStdHandle(STD_ERROR_HANDLE) failed"));
332 }
333
334 // Duplicate the file handle so the redirected stderr owns an
335 // independent HANDLE — mirroring the Unix path's `libc::dup`.
336 // Without this, `_file` and stderr would alias the same HANDLE;
337 // a rogue `CloseHandle` on stderr would silently invalidate `_file`.
338 let raw = HANDLE(file.as_raw_handle());
339 // SAFETY: pseudo-handle; no preconditions.
340 let process = unsafe { GetCurrentProcess() };
341 let mut dup = HANDLE::default();
342 // SAFETY: `file` and `dup` are live; pseudo-handle needs no close.
343 unsafe {
344 DuplicateHandle(
345 process,
346 raw,
347 process,
348 &mut dup,
349 0,
350 false,
351 DUPLICATE_SAME_ACCESS,
352 )
353 .context("DuplicateHandle for stderr redirect")?;
354 }
355
356 // SAFETY: SetStdHandle redirects stderr to the duplicated handle.
357 // We save the original handle so the guard can restore it on drop.
358 unsafe {
359 if let Err(e) = SetStdHandle(STD_ERROR_HANDLE, dup) {
360 let _ = CloseHandle(dup);
361 return Err(anyhow::anyhow!(
362 "SetStdHandle(STD_ERROR_HANDLE) failed: {e}"
363 ));
364 }
365 }
366 Ok((saved, dup))
367 }
368
369 #[cfg(test)]
370 mod tests {
371 use super::*;
372 use std::fs::FileTimes;
373
374 #[cfg(unix)]
375 #[test]
376 fn log_file_is_owner_only_and_refuses_symlinks() {
377 use std::io::Write as _;
378 use std::os::unix::fs::{PermissionsExt as _, symlink};
379 let tmp = tempfile::TempDir::new().expect("temporary dir");
380 let mode = |path: &Path| {
381 std::fs::metadata(path)
382 .expect("metadata")
383 .permissions()
384 .mode()
385 & 0o777
386 };
387
388 let fresh = tmp.path().join("fresh.log");
389 open_log_file(&fresh)
390 .expect("create")
391 .write_all(b"one\n")
392 .expect("write");
393 assert_eq!(mode(&fresh), 0o600);
394
395 // An existing world-readable log is tightened, and stays appended to.
396 let old = tmp.path().join("old.log");
397 std::fs::write(&old, "before\n").expect("seed");
398 std::fs::set_permissions(&old, std::fs::Permissions::from_mode(0o644)).expect("chmod");
399 open_log_file(&old)
400 .expect("reopen")
401 .write_all(b"after\n")
402 .expect("write");
403 assert_eq!(mode(&old), 0o600);
404 assert_eq!(
405 std::fs::read_to_string(&old).expect("read"),
406 "before\nafter\n"
407 );
408
409 // A symlink planted at the log path is not followed.
410 let target = tmp.path().join("target.txt");
411 std::fs::write(&target, "keep").expect("target");
412 std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o644)).expect("chmod");
413 let link = tmp.path().join("link.log");
414 symlink(&target, &link).expect("symlink");
415 assert!(open_log_file(&link).is_err());
416 assert_eq!(std::fs::read_to_string(&target).expect("read"), "keep");
417 assert_eq!(mode(&target), 0o644);
418 }
419
420 fn set_modified(path: &Path, modified: SystemTime) {
421 let file = OpenOptions::new().write(true).open(path).unwrap();
422 file.set_times(FileTimes::new().set_modified(modified))
423 .unwrap();
424 }
425
426 #[test]
427 fn log_directory_prefers_home() {
428 let _lock = crate::test_support::lock_test_env();
429 let tmp = tempfile::TempDir::new().unwrap();
430 let prev_home = std::env::var_os("HOME");
431 let prev_userprofile = std::env::var_os("USERPROFILE");
432 // SAFETY: serialised by lock_test_env.
433 unsafe {
434 std::env::set_var("HOME", tmp.path());
435 std::env::set_var("USERPROFILE", "");
436 }
437
438 let resolved = log_directory().expect("log_directory should resolve");
439 assert_eq!(resolved, tmp.path().join(".codewhale").join("logs"));
440
441 // SAFETY: cleanup under the same lock.
442 unsafe {
443 match prev_home {
444 Some(v) => std::env::set_var("HOME", v),
445 None => std::env::remove_var("HOME"),
446 }
447 match prev_userprofile {
448 Some(v) => std::env::set_var("USERPROFILE", v),
449 None => std::env::remove_var("USERPROFILE"),
450 }
451 }
452 }
453
454 #[test]
455 fn log_directory_uses_existing_legacy_deepseek_logs() {
456 let _lock = crate::test_support::lock_test_env();
457 let tmp = tempfile::TempDir::new().unwrap();
458 let legacy = tmp.path().join(".deepseek").join("logs");
459 fs::create_dir_all(&legacy).unwrap();
460 let prev_home = std::env::var_os("HOME");
461 let prev_userprofile = std::env::var_os("USERPROFILE");
462 // SAFETY: serialised by lock_test_env.
463 unsafe {
464 std::env::set_var("HOME", tmp.path());
465 std::env::set_var("USERPROFILE", "");
466 }
467
468 let resolved = log_directory().expect("log_directory should resolve");
469 assert_eq!(resolved, legacy);
470
471 // SAFETY: cleanup under the same lock.
472 unsafe {
473 match prev_home {
474 Some(v) => std::env::set_var("HOME", v),
475 None => std::env::remove_var("HOME"),
476 }
477 match prev_userprofile {
478 Some(v) => std::env::set_var("USERPROFILE", v),
479 None => std::env::remove_var("USERPROFILE"),
480 }
481 }
482 }
483
484 #[test]
485 fn log_file_name_includes_pid() {
486 assert_eq!(
487 log_file_name("2026-05-18", 12345),
488 "tui-2026-05-18-12345.log"
489 );
490 }
491
492 #[test]
493 fn log_retention_days_uses_positive_env_override() {
494 let _lock = crate::test_support::lock_test_env();
495 let previous = std::env::var_os(LOG_RETENTION_ENV);
496
497 // SAFETY: serialised by lock_test_env.
498 unsafe {
499 std::env::set_var(LOG_RETENTION_ENV, "14");
500 }
501 assert_eq!(log_retention_days(), 14);
502
503 // SAFETY: serialised by lock_test_env.
504 unsafe {
505 std::env::set_var(LOG_RETENTION_ENV, "0");
506 }
507 assert_eq!(log_retention_days(), DEFAULT_LOG_RETENTION_DAYS);
508
509 // SAFETY: cleanup under the same lock.
510 unsafe {
511 match previous {
512 Some(value) => std::env::set_var(LOG_RETENTION_ENV, value),
513 None => std::env::remove_var(LOG_RETENTION_ENV),
514 }
515 }
516 }
517
518 #[test]
519 fn prune_old_logs_drops_only_stale_tui_logs() {
520 let tmp = tempfile::TempDir::new().unwrap();
521 let fresh = tmp.path().join("tui-2026-05-18-1.log");
522 let stale = tmp.path().join("tui-2026-05-01-2.log");
523 let legacy_stale = tmp.path().join("tui-2026-05-01.log");
524 let unrelated = tmp.path().join("agent-2026-05-01.log");
525
526 fs::write(&fresh, "fresh").unwrap();
527 fs::write(&stale, "stale").unwrap();
528 fs::write(&legacy_stale, "legacy").unwrap();
529 fs::write(&unrelated, "other").unwrap();
530
531 let now = SystemTime::now();
532 let old = now - Duration::from_secs(10 * SECONDS_PER_DAY);
533 set_modified(&stale, old);
534 set_modified(&legacy_stale, old);
535 set_modified(&unrelated, old);
536
537 let removed = prune_old_logs(tmp.path(), 7).unwrap();
538
539 assert_eq!(removed, 2);
540 assert!(fresh.exists());
541 assert!(!stale.exists());
542 assert!(!legacy_stale.exists());
543 assert!(unrelated.exists());
544 }
545
546 #[test]
547 fn log_directory_honors_codewhale_home_as_hard_override() {
548 let _lock = crate::test_support::lock_test_env();
549 let tmp = tempfile::TempDir::new().unwrap();
550 // SAFETY: serialised by lock_test_env.
551 unsafe {
552 std::env::set_var("CODEWHALE_HOME", tmp.path());
553 }
554 // $CODEWHALE_HOME IS the home dir (no ".codewhale" appended), and the
555 // legacy ~/.deepseek fallback is bypassed entirely.
556 let resolved = log_directory().expect("log_directory should resolve");
557 assert_eq!(resolved, tmp.path().join("logs"));
558 // SAFETY: cleanup under the same lock.
559 unsafe {
560 std::env::remove_var("CODEWHALE_HOME");
561 }
562 }
563 }
564
564 lines RUST