Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

fix(logs): quiet the polls and drop the duplicated access lines (#8763)

Leo Borcherding7a48774a1d62
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 644f875632e..0f61aa53bcd 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -336,6 +336,7 @@ from core.inference.tool_call_parser import (
from utils.native_path_leases import child_env_without_native_path_secret
from utils.child_stdio import utf8_child_env
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
+from utils.log_retention import prune_log_dir
from utils.subprocess_compat import (
windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,
)
@@ -11253,6 +11254,8 @@ class LlamaCppBackend:
log_dir.mkdir(parents = True, exist_ok = True)
self._llama_log_path = log_dir / f"diffusion-{int(time.time())}-port-{self._port}.log"
self._llama_log_fh = open(self._llama_log_path, "w", encoding = "utf-8", buffering = 1)
+ # After the open, so the cap counts this file and can never delete it.
+ prune_log_dir(log_dir, "diffusion-*.log", protect = self._llama_log_path)
logger.info(f"diffusion runner stdout/stderr -> {self._llama_log_path}")
except (OSError, UnicodeDecodeError) as e:
logger.debug(f"Could not open diffusion runner log file: {e}")
@@ -15123,6 +15126,8 @@ class LlamaCppBackend:
encoding = "utf-8",
buffering = 1,
)
+ # After the open, so the cap counts this file and can never delete it.
+ prune_log_dir(log_dir, "llama-*.log", protect = self._llama_log_path)
logger.info(f"llama-server stdout/stderr -> {self._llama_log_path}")
except (OSError, UnicodeDecodeError) as e:
# Best-effort; never block the load on logging.
@@ -19702,6 +19707,10 @@ class LlamaCppBackend:
encoding = "utf-8",
buffering = 1,
)
+ # After the open, so the cap counts this file and never deletes
+ # it. On the retry path the earlier attempts' logs are what a
+ # reader wants, and keep-newest holds on to them.
+ prune_log_dir(log_dir, "llama-*.log", protect = self._llama_log_path)
logger.info(f"llama-server stdout/stderr -> {self._llama_log_path}")
except (OSError, UnicodeDecodeError) as e:
# Best-effort; never block the load on logging.
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index ac02b12d10c..d3e6028128c 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -380,12 +380,16 @@ class InferenceOrchestrator:
hub_ids = [
m["id"] for m in models if not m.get("id", "").upper().endswith("-GGUF")
][:40]
+ # Counts at info, ids at debug: two lists of 40 repo names, one line each,
+ # cost ~1.5 KB of every boot to say the catalog fetch worked.
if gguf_ids:
self._top_gguf_cache = gguf_ids
- logger.info("Top GGUF models: %s", gguf_ids)
+ logger.info("Fetched %d top GGUF models", len(gguf_ids))
+ logger.debug("Top GGUF models: %s", gguf_ids)
if hub_ids:
self._top_hub_cache = hub_ids
- logger.info("Top hub models: %s", hub_ids)
+ logger.info("Fetched %d top hub models", len(hub_ids))
+ logger.debug("Top hub models: %s", hub_ids)
except Exception as e:
logger.warning("Failed to fetch top models: %s", e)
finally:
diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.py
index 7e203535863..89da165a359 100644
--- a/studio/backend/loggers/handlers.py
+++ b/studio/backend/loggers/handlers.py
@@ -42,6 +42,12 @@ _ACCESS_LOG_DEDUP_MS = _env_int("UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS", 300)
# Liveness/UI polls whose line means only "still polling"; collapse to a longer
# heartbeat. First hit and errors still log. 0 = off.
_QUIET_POLL_DEDUP_MS = _env_int("UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS", 10000)
+# The desktop watchdog probe is slower than every other poll here: 15s between rounds
+# (HEALTH_WATCHDOG_INTERVAL, src-tauri/src/commands.rs) plus up to a 10s probe budget,
+# ~19s in the sample below. A 10s window that stamps only on emit can never close over two
+# of those, so it would collapse nothing. Its own window, wide enough to span a round.
+# 0 = off.
+_WATCHDOG_POLL_DEDUP_MS = _env_int("UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS", 60000)
# Both windows off is what --verbose sets; the drop-the-2xx suppressor below has no
# window of its own, so it must read the same signal to honour --verbose.
_VERBOSE_ACCESS_LOG = _ACCESS_LOG_DEDUP_MS <= 0 and _QUIET_POLL_DEDUP_MS <= 0
@@ -56,6 +62,9 @@ _QUIET_POLL_PATHS = {
"/api/inference/images/status",
"/api/inference/video/status",
"/api/inference/audio/stt/status",
+ # Re-read whenever the settings dialog or the remote-access section is open, and it is
+ # a plain read of a toggle: 116 lines in the 4h sample.
+ "/api/settings/remote-access",
# List polls the tabs refetch on a timer and on every tab switch.
"/api/train/runs",
"/api/models/checkpoints",
@@ -100,6 +109,12 @@ _LIVENESS_POLL_PATHS = frozenset(
"/api/inference/audio/stt/status",
}
)
+# The desktop shell's own watchdog probe. /api/health was already quiet but its sibling was
+# in no suppressor at all: 760 lines on an idle 4h session, 14% of tauri.log, to say the
+# process is still up. Out of _QUIET_POLL_PATHS because that window is narrower than the
+# poll interval; see _WATCHDOG_POLL_DEDUP_MS. Start/stop transitions reach the phase log
+# either way.
+_WATCHDOG_POLL_PATHS = {"/api/liveness"}
# Bucket key for the group above. Not a real (method, path, query, status), so it can
# never collide with one.
_LIVENESS_DEDUP_KEY = ("GET", "\x00liveness", b"", 200)
@@ -269,11 +284,13 @@ class LoggingMiddleware:
# /api/inference/audio/stt/status?model=... extends the downloaded check to a
# custom repo, so it keeps its own identity rather than joining the bucket.
is_liveness = path in _LIVENESS_POLL_PATHS and not query
- window_ms = (
- _QUIET_POLL_DEDUP_MS
- if is_liveness or path in _QUIET_POLL_PATHS
- else _ACCESS_LOG_DEDUP_MS
- )
+ if path in _WATCHDOG_POLL_PATHS:
+ # Zeroed along with the quiet window, so --verbose still logs every probe.
+ window_ms = _WATCHDOG_POLL_DEDUP_MS if _QUIET_POLL_DEDUP_MS > 0 else 0
+ elif is_liveness or path in _QUIET_POLL_PATHS:
+ window_ms = _QUIET_POLL_DEDUP_MS
+ else:
+ window_ms = _ACCESS_LOG_DEDUP_MS
if window_ms <= 0:
return False
# The liveness group shares one bucket, so a burst of them logs once, not once
@@ -285,7 +302,8 @@ class LoggingMiddleware:
return True
self._last_log[key] = now
if len(self._last_log) > _DEDUP_MAP_MAX:
- cutoff = now - (max(_ACCESS_LOG_DEDUP_MS, _QUIET_POLL_DEDUP_MS) / 1000.0)
+ widest = max(_ACCESS_LOG_DEDUP_MS, _QUIET_POLL_DEDUP_MS, _WATCHDOG_POLL_DEDUP_MS)
+ cutoff = now - (widest / 1000.0)
self._last_log = {k: v for k, v in self._last_log.items() if v >= cutoff}
return False
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 3853a1c9b48..6f938009109 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -1716,15 +1716,75 @@ class _TeeStream:
Console behavior is unchanged (writes/returns delegate to the original
stream; Tauri's structured-stdout protocol and isatty probes see exactly
what they saw before). The file copy is best-effort: a full disk or a
- closed handle must never break the console."""
+ closed handle must never break the console.
+
+ The file copy also collapses carriage-return progress frames: a tqdm bar redraws
+ "\\r<frame>" hundreds of times and a file keeps every one (5 KB for one "Loading
+ weights" bar). Only frames are ever withheld -- a partial line with no "\\r" (a
+ prompt, a traceback torn by a hang) is written on arrival, and a held frame is
+ closed off on its own line before the next record, never prefixed onto it.
+
+ Frames are picked exactly as the desktop reader picks them, so the session log and
+ tauri.log stay interchangeable: strip the terminator (trim_line_endings), then take
+ the last non-blank "\\r"-separated frame (collapse_progress_frames), both in
+ src-tauri/src/process.rs. Reading the "\\r" of a CRLF as a redraw instead keeps the
+ empty text after it and drops the line, which on Windows is every relayed child
+ line there is."""
def __init__(self, stream, log_fh):
self._stream = stream
self._log_fh = log_fh
+ # Last frame seen with no newline yet; superseded by the next frame, flushed
+ # ahead of the next real line.
+ self._pending_frame = ""
+
+ @staticmethod
+ def _last_frame(line):
+ # A trailing "\r" terminates the line (CRLF, or tqdm's own sign-off); it does not
+ # open an empty redraw. Strip it first, as trim_line_endings does on the desktop side.
+ line = line.rstrip("\r")
+ if "\r" not in line:
+ return line
+ for frame in reversed(line.split("\r")):
+ if frame.strip():
+ return frame
+ # All frames blank, so the line is blank. Return a frame, not the whole text: a
+ # "\r" reaching the file lands as "\r\r\n" once the handle adds its own terminator.
+ return line.rsplit("\r", 1)[-1]
+
+ def _write_file(self, data):
+ # Not a continuation of a held frame: that would flush it unterminated and glue
+ # the next record on. print("", end = "") is enough to get here.
+ if not data:
+ return
+ # Overwhelmingly the common case, and the one that must stay cheap.
+ if "\r" not in data and not self._pending_frame:
+ self._log_fh.write(data)
+ return
+
+ if self._pending_frame and data[:1] not in ("\r", "\n"):
+ # Not a redraw of the held frame nor its terminator, so it is the next record.
+ # Close the frame off on its own line; concatenating costs a reader the JSON.
+ self._log_fh.write(self._pending_frame + "\n")
+ self._pending_frame = ""
+
+ buf = self._pending_frame + data
+ self._pending_frame = ""
+ head, newline, tail = buf.rpartition("\n")
+ if newline:
+ complete = head + newline
+ self._log_fh.write("\n".join(self._last_frame(line) for line in complete.split("\n")))
+ if tail:
+ # Unterminated remainder: hold it only if it is a redraw, else write it now
+ # so a hang cannot swallow real output.
+ if "\r" in tail:
+ self._pending_frame = self._last_frame(tail)
+ else:
+ self._log_fh.write(tail)
def write(self, data):
try:
- self._log_fh.write(data)
+ self._write_file(data)
except Exception:
pass
if self._stream is None:
@@ -1749,7 +1809,11 @@ class _TeeStream:
# Flush the log copy, then forward close() to the wrapped stream
# best-effort: on Colab that stream is an ipykernel OutStream whose
# close() can raise (see _harden_console_close / ipython/ipykernel#867).
+ # A frame still held here has nothing left to supersede it, so land it.
try:
+ if self._pending_frame:
+ self._log_fh.write(self._pending_frame + "\n")
+ self._pending_frame = ""
self._log_fh.flush()
except Exception:
pass
@@ -1883,11 +1947,12 @@ def _setup_server_disk_logging():
sys.stdout = _TeeStream(sys.stdout, log_fh)
sys.stderr = _TeeStream(sys.stderr, log_fh)
- # Best-effort retention: keep the newest 20 session logs.
+ # Best-effort retention: keep the newest 20 session logs. `protect` says so explicitly
+ # rather than trusting the new file to sort newest, which two starts in the same
+ # second do not guarantee.
try:
- logs = sorted(log_dir.glob("server-*.log"), key = lambda p: p.stat().st_mtime)
- for old in logs[:-20]:
- old.unlink(missing_ok = True)
+ from utils.log_retention import prune_log_dir
+ prune_log_dir(log_dir, "server-*.log", protect = log_path)
except Exception:
pass
return log_path
@@ -2243,6 +2308,53 @@ def run_server(
global _server, _server_thread, _shutdown_event
boot_started = time.perf_counter()
+
+ # --secure exposes ONLY the Cloudflare link, so --secure --no-cloudflare contradicts
+ # itself. Reject it before anything below touches a process global: the tee further
+ # down replaces sys.stdout/sys.stderr, and an embedder that catches this SystemExit
+ # would keep it, the log handle open, and nest another tee on its next call.
+ if secure and cloudflare is False:
+ raise SystemExit(
+ "--secure requires the Cloudflare tunnel; do not combine it with --no-cloudflare."
+ )
+
+ # Windows cp1252 can't encode emoji; reconfigure stdout to UTF-8. Before the tee, so
+ # it reaches the console stream rather than the wrapper.
+ if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
+ try:
+ sys.stdout.reconfigure(encoding = "utf-8", errors = "replace")
+ except Exception:
+ pass
+
+ # Persist a session log + native-crash stacks BEFORE anything else, so even
+ # import-time failures leave evidence on disk. Field report: Unsloth "terminates
+ # without a warning" -- a native crash in the GPU runtime kills the process with no
+ # traceback, and a desktop-shortcut console closes before anything can be read.
+ _session_log = _setup_server_disk_logging()
+ if _session_log is not None and not silent:
+ print(f"Session log: {_session_log}")
+
+ # Configure structlog only now, after the tee: PrintLoggerFactory captures sys.stdout
+ # at configure() time and cache_logger_on_first_use freezes it into any logger that
+ # has already emitted, so configuring first pins this module's logger to the console
+ # and keeps its lines out of the file just opened above.
+ #
+ # main.py configures too, but on import, which lands seconds later -- after the
+ # "startup begin" line below. That line used to render through structlog's defaults
+ # (ConsoleRenderer, local time) and everything after it as JSON in UTC, so the clock
+ # appeared to jump hours between line one and line two. Repeating configure() is safe;
+ # main.py's call still wins for its own service name.
+ #
+ # Imported here, not at module scope: `loggers` must be a real package to resolve
+ # `loggers.config`, and run.py is loaded by tests that stand a bare ModuleType in for
+ # it (tests/studio/install/test_selection_logic.py:84), which never reach this call.
+ from loggers.config import LogConfig
+
+ LogConfig.setup_logging(
+ service_name = "unsloth-studio-backend",
+ env = os.getenv("ENVIRONMENT_TYPE", "production"),
+ )
+
logger.info("run_server startup begin api_only=%s host=%s port=%s", api_only, host, port)
cloudflare_intent = _consume_cloudflare_intent(cloudflare, secure)
@@ -2261,38 +2373,18 @@ def run_server(
except Exception as e:
logger.warning("Could not sweep orphans from a previous run: %s", e)
- # --secure exposes ONLY the Cloudflare link: reject --secure --no-cloudflare,
- # then force a loopback bind so the raw port is never public (even -H 0.0.0.0).
- # Otherwise keep the tri-state so the banner distinguishes "off by default"
- # from an explicit --no-cloudflare.
+ # --secure exposes ONLY the Cloudflare link, so force a loopback bind and the raw
+ # port is never public (even -H 0.0.0.0). The --no-cloudflare contradiction was
+ # already rejected at the top of this function, before the tee went in. Otherwise
+ # keep the tri-state so the banner distinguishes "off by default" from an explicit
+ # --no-cloudflare.
if secure:
- if cloudflare is False:
- raise SystemExit(
- "--secure requires the Cloudflare tunnel; do not combine it with --no-cloudflare."
- )
cloudflare = True
host = "127.0.0.1"
# `unsloth studio run` installs its own resolved policy and passes None here.
_apply_cli_tool_policy(enable_tools)
- # Windows cp1252 can't encode emoji; reconfigure stdout to UTF-8.
- if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
- try:
- sys.stdout.reconfigure(encoding = "utf-8", errors = "replace")
- except Exception:
- pass
-
- # Persist a session log + native-crash stacks BEFORE importing main, so
- # even import-time failures leave evidence on disk. Field report: Unsloth
- # "terminates without a warning" -- a native crash in the GPU runtime
- # kills the process with no Python traceback, and a desktop-shortcut
- # console closes before anything can be read. Console-only logging made
- # that undiagnosable.
- _session_log = _setup_server_disk_logging()
- if _session_log is not None and not silent:
- print(f"Session log: {_session_log}")
-
# Set env vars BEFORE importing main so CORS middleware picks them up.
# secure api-only is a remote server behind Cloudflare, so it keeps the
# any-origin CORS profile; plain api-only stays locked to the Tauri app.
diff --git a/studio/backend/tests/test_log_retention.py b/studio/backend/tests/test_log_retention.py
new file mode 100644
index 00000000000..4b3f91aa5e9
--- /dev/null
+++ b/studio/backend/tests/test_log_retention.py
@@ -0,0 +1,136 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keep-newest-N retention for the per-session log directories.
+
+Three things decide whether this helper is safe to point at a directory the app is
+actively writing into: the cap has to mean what it says, the file the caller just opened
+has to survive, and one odd directory entry must not disable retention for everything
+else.
+"""
+
+import os
+
+import pytest
+
+from utils.log_retention import DEFAULT_KEEP, prune_log_dir
+
+PATTERN = "llama-*.log"
+
+
+def _seed(root, count):
+ for i in range(count):
+ path = root / f"llama-{i:04d}.log"
+ path.write_text(f"log {i}\n", encoding = "utf-8")
+ os.utime(path, (1_000_000 + i, 1_000_000 + i))
+
+
+def _logs(root):
+ return sorted(p.name for p in root.glob(PATTERN) if p.is_file())
+
+
[email protected]("keep", [0, 1, 5, DEFAULT_KEEP])
+def test_keep_leaves_exactly_that_many(tmp_path, keep):
+ _seed(tmp_path, 30)
+ prune_log_dir(tmp_path, PATTERN, keep = keep)
+ assert len(_logs(tmp_path)) == keep
+
+
+def test_the_newest_are_the_ones_kept(tmp_path):
+ _seed(tmp_path, 30)
+ prune_log_dir(tmp_path, PATTERN, keep = 3)
+ assert _logs(tmp_path) == ["llama-0027.log", "llama-0028.log", "llama-0029.log"]
+
+
+def test_a_negative_keep_is_a_no_op(tmp_path):
+ _seed(tmp_path, 5)
+ prune_log_dir(tmp_path, PATTERN, keep = -1)
+ assert len(_logs(tmp_path)) == 5
+
+
+def test_a_missing_directory_is_survivable(tmp_path):
+ prune_log_dir(tmp_path / "not-there", PATTERN)
+
+
[email protected]("population", [0, 19, 20, 21, 319])
+def test_the_protected_file_counts_toward_the_cap(tmp_path, population):
+ """Called after the open, the directory settles at `keep`, not `keep + 1`.
+
+ Pruning first leaves one extra behind on every load, so the cap is never reached.
+ """
+ _seed(tmp_path, population)
+ for load in range(5):
+ active = tmp_path / f"llama-active{load}.log"
+ active.write_text("live", encoding = "utf-8")
+ os.utime(active, (2_000_000 + load, 2_000_000 + load))
+ prune_log_dir(tmp_path, PATTERN, keep = DEFAULT_KEEP, protect = active)
+ assert active.exists(), "the log this load just opened was pruned"
+ assert len(_logs(tmp_path)) == min(population + 5, DEFAULT_KEEP)
+
+
+def test_the_protected_file_survives_even_when_it_sorts_oldest(tmp_path):
+ """Two loads in the same second, or a clock that stepped back, and the file the caller
+ is writing to is no longer the newest. It still may not be deleted."""
+ _seed(tmp_path, 30)
+ active = tmp_path / "llama-active.log"
+ active.write_text("live", encoding = "utf-8")
+ os.utime(active, (1, 1))
+ prune_log_dir(tmp_path, PATTERN, keep = 3, protect = active)
+ assert active.exists()
+ assert len(_logs(tmp_path)) == 3
+
+
+def test_a_dangling_symlink_does_not_disable_retention(tmp_path):
+ """stat() on a broken link raises. One try/except around the whole scan turned that
+ into "never prune this directory again", the growth this helper exists to stop."""
+ _seed(tmp_path, 30)
+ (tmp_path / "llama-dangling.log").symlink_to(tmp_path / "gone.log")
+ prune_log_dir(tmp_path, PATTERN, keep = 5)
+ assert len(_logs(tmp_path)) == 5
+
+
+def test_a_symlink_never_destroys_a_target_outside_the_log_directory(tmp_path):
+ outside = tmp_path / "keep-me.txt"
+ outside.write_text("not a log", encoding = "utf-8")
+ logs = tmp_path / "logs"
+ logs.mkdir()
+ _seed(logs, 30)
+ (logs / "llama-link.log").symlink_to(outside)
+ prune_log_dir(logs, PATTERN, keep = 1)
+ assert outside.read_text(encoding = "utf-8") == "not a log"
+
+
+def test_a_directory_matching_the_glob_is_neither_counted_nor_removed(tmp_path):
+ _seed(tmp_path, 25)
+ (tmp_path / "llama-not-a-log.log").mkdir()
+ prune_log_dir(tmp_path, PATTERN, keep = 5)
+ assert (tmp_path / "llama-not-a-log.log").is_dir()
+ assert len(_logs(tmp_path)) == 5, "a directory took one of the kept slots"
+
+
+def test_identical_mtimes_still_leave_exactly_keep(tmp_path):
+ for i in range(30):
+ path = tmp_path / f"llama-{i:04d}.log"
+ path.write_text("x", encoding = "utf-8")
+ os.utime(path, (1_500_000, 1_500_000))
+ prune_log_dir(tmp_path, PATTERN, keep = 7)
+ assert len(_logs(tmp_path)) == 7
+
+
+def test_families_do_not_prune_each_other(tmp_path):
+ for i in range(30):
+ (tmp_path / f"llama-{i:04d}.log").write_text("l", encoding = "utf-8")
+ (tmp_path / f"diffusion-{i:04d}.log").write_text("d", encoding = "utf-8")
+ prune_log_dir(tmp_path, PATTERN, keep = 5)
+ assert len(list(tmp_path.glob("llama-*.log"))) == 5
+ assert len(list(tmp_path.glob("diffusion-*.log"))) == 30
+
+
+def test_a_writer_can_keep_appending_across_a_prune(tmp_path):
+ _seed(tmp_path, 30)
+ active = tmp_path / "llama-writing.log"
+ with open(active, "w", encoding = "utf-8", buffering = 1) as handle:
+ handle.write("first\n")
+ prune_log_dir(tmp_path, PATTERN, keep = 3, protect = active)
+ handle.write("second\n")
+ assert active.read_text(encoding = "utf-8") == "first\nsecond\n"
diff --git a/studio/backend/tests/test_logging_middleware.py b/studio/backend/tests/test_logging_middleware.py
index dc76862e68c..6c1ff25935f 100644
--- a/studio/backend/tests/test_logging_middleware.py
+++ b/studio/backend/tests/test_logging_middleware.py
@@ -2,6 +2,9 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import asyncio
+import os
+import re
+from pathlib import Path
import pytest
from fastapi import FastAPI
@@ -190,6 +193,105 @@ def test_quiet_poll_paths_use_longer_heartbeat_window(logs, monkeypatch):
assert paths.count("/api/models/browse-folders") == 3 # base dedup off -> all logged
+def test_liveness_probe_heartbeats(logs, monkeypatch):
+ # The desktop watchdog's own probe. Its sibling /api/health was already quiet, so a
+ # steady poll of this one was a line per request.
+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)
+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 1000)
+ monkeypatch.setattr(hmod, "_WATCHDOG_POLL_DEDUP_MS", 1000)
+
+ async def app(scope, receive, send):
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ await send({"type": "http.response.body", "body": b"ok"})
+
+ async def send(message):
+ pass
+
+ mw = LoggingMiddleware(app)
+ for _ in range(4):
+ _run(mw(_http_scope("/api/liveness"), _noop_receive, send))
+
+ paths = [e[2]["path"] for e in logs.events]
+ assert paths.count("/api/liveness") == 1
+
+
+def test_watchdog_window_outlasts_the_probe_interval():
+ """The window has to be wider than the poll, or the heartbeat is a no-op.
+
+ ``_QUIET_POLL_DEDUP_MS`` stamps only on emit, so a 10s window against a probe that
+ arrives every ~19s never sees two inside one window and every probe logs anyway --
+ which is what putting this path in ``_QUIET_POLL_PATHS`` would have done. The desktop
+ watchdog runs ``HEALTH_WATCHDOG_INTERVAL`` (15s) between rounds plus up to
+ ``HEALTH_PROBE_TIMEOUT`` (10s) inside one, so pin the floor at a full round.
+ """
+ commands_rs = (
+ Path(__file__).resolve().parents[2] / "src-tauri" / "src" / "commands.rs"
+ ).read_text(encoding = "utf-8")
+
+ def _secs(name):
+ match = re.search(rf"{name}: Duration = Duration::from_secs\((\d+)\)", commands_rs)
+ assert match is not None, (
+ f"{name} is no longer a Duration::from_secs literal in commands.rs; this test "
+ f"reads it to pin the heartbeat window and needs updating alongside it"
+ )
+ return int(match.group(1))
+
+ interval_s = _secs("HEALTH_WATCHDOG_INTERVAL")
+ probe_s = _secs("HEALTH_PROBE_TIMEOUT")
+
+ # The default, not whatever this shell exports: reading the module global would fail
+ # the test for anyone with the override set.
+ window_ms = hmod._env_int("UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS", 60000)
+ if os.environ.get("UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS"):
+ window_ms = 60000
+ assert window_ms > (interval_s + probe_s) * 1000, (
+ f"the watchdog heartbeat window ({window_ms}ms) is not wider "
+ f"than one probe round ({interval_s}s + {probe_s}s), so it would collapse nothing"
+ )
+
+
+def test_liveness_probe_errors_still_log(logs, monkeypatch):
+ # A watchdog probe that starts failing is the whole signal; heartbeating is 2xx-only.
+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)
+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 1000)
+ monkeypatch.setattr(hmod, "_WATCHDOG_POLL_DEDUP_MS", 1000)
+
+ async def app(scope, receive, send):
+ await send({"type": "http.response.start", "status": 503, "headers": []})
+ await send({"type": "http.response.body", "body": b"down"})
+
+ async def send(message):
+ pass
+
+ mw = LoggingMiddleware(app)
+ for _ in range(3):
+ _run(mw(_http_scope("/api/liveness"), _noop_receive, send))
+
+ paths = [e[2]["path"] for e in logs.events]
+ assert paths.count("/api/liveness") == 3
+
+
+def test_verbose_keeps_every_watchdog_probe(logs, monkeypatch):
+ # --verbose zeroes the poll window; the watchdog's own window must go with it.
+ monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 0)
+ monkeypatch.setattr(hmod, "_QUIET_POLL_DEDUP_MS", 0)
+ monkeypatch.setattr(hmod, "_WATCHDOG_POLL_DEDUP_MS", 60000)
+
+ async def app(scope, receive, send):
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ await send({"type": "http.response.body", "body": b"ok"})
+
+ async def send(message):
+ pass
+
+ mw = LoggingMiddleware(app)
+ for _ in range(3):
+ _run(mw(_http_scope("/api/liveness"), _noop_receive, send))
+
+ paths = [e[2]["path"] for e in logs.events]
+ assert paths.count("/api/liveness") == 3
+
+
def test_distinct_query_strings_are_not_deduped(logs, monkeypatch):
monkeypatch.setattr(hmod, "_ACCESS_LOG_DEDUP_MS", 1000)
diff --git a/studio/backend/tests/test_server_disk_logging.py b/studio/backend/tests/test_server_disk_logging.py
index 0d149ce0090..3caddf649f8 100644
--- a/studio/backend/tests/test_server_disk_logging.py
+++ b/studio/backend/tests/test_server_disk_logging.py
@@ -153,3 +153,79 @@ class TestSetupServerDiskLogging:
"disk logging must be armed before importing main so import-time "
"failures leave evidence on disk"
)
+
+ def test_structlog_is_configured_after_the_tee_and_before_the_first_line(self):
+ """Order, not presence, is the invariant.
+
+ ``LogConfig.setup_logging`` hands structlog a
+ ``PrintLoggerFactory(file = sys.stdout)``, which snapshots the stream it is given,
+ and ``cache_logger_on_first_use`` then freezes that snapshot into any logger that
+ has already emitted a line. Configure before the tee and this module's ``logger``
+ is pinned to the console for the rest of the process -- every later run.py line
+ goes missing from the session log. Configure after it and the whole session,
+ starting with the first line, renders one way into both.
+ """
+ src = (Path(_BACKEND_DIR) / "run.py").read_text(encoding = "utf-8")
+ body = src.index("def run_server")
+ tee_idx = src.index("_setup_server_disk_logging()", body)
+ setup_idx = src.index("LogConfig.setup_logging(", body)
+ first_log_idx = src.index("logger.info(", body)
+ assert tee_idx < setup_idx < first_log_idx, (
+ "run_server must install the tee, then configure structlog, then log; "
+ f"got tee@{tee_idx} setup@{setup_idx} first-log@{first_log_idx}"
+ )
+ assert (
+ "LogConfig.setup_logging(" not in src[:body]
+ ), "configuring structlog at import time pins it to the pre-tee sys.stdout"
+
+ def test_run_py_does_not_import_a_loggers_submodule_at_module_scope(self):
+ """`loggers` must be a real package for `loggers.config` to resolve.
+
+ run.py is loaded by tests that stand a bare ``types.ModuleType`` in for it
+ (tests/studio/install/test_selection_logic.py). A bare module has no ``__path__``,
+ so a module-scope submodule import fails during collection and takes every test in
+ that file with it. Import it where it is used instead.
+ """
+ import ast
+
+ tree = ast.parse((Path(_BACKEND_DIR) / "run.py").read_text(encoding = "utf-8"))
+ offenders = []
+ for node in tree.body: # module scope only
+ if isinstance(node, ast.ImportFrom) and (node.module or "").startswith("loggers."):
+ offenders.append(f"line {node.lineno}: from {node.module} import ...")
+ elif isinstance(node, ast.Import):
+ offenders += [
+ f"line {node.lineno}: import {a.name}"
+ for a in node.names
+ if a.name.startswith("loggers.")
+ ]
+ assert not offenders, "; ".join(offenders)
+
+ def test_conflicting_flags_are_rejected_before_the_tee_is_installed(self):
+ """A deterministic preflight failure must not leave the process streams swapped.
+
+ ``_setup_server_disk_logging()`` replaces ``sys.stdout``/``sys.stderr`` and opens a
+ log handle. An embedder that catches this ``SystemExit`` keeps all of it, and its
+ next ``run_server()`` call nests a second tee, writing every line twice.
+ """
+ src = (Path(_BACKEND_DIR) / "run.py").read_text(encoding = "utf-8")
+ body = src.index("def run_server")
+ reject_idx = src.index("--secure requires the Cloudflare tunnel", body)
+ # Anchor on the assignment, not the bare name: a comment mentioning the call
+ # would otherwise satisfy this.
+ tee_idx = src.index("_session_log = _setup_server_disk_logging()", body)
+ assert reject_idx < tee_idx, (
+ "the --secure/--no-cloudflare rejection must run before the tee is installed; "
+ f"got reject@{reject_idx} tee@{tee_idx}"
+ )
+
+ def test_a_rejected_flag_combination_leaves_the_streams_alone(self):
+ import run as run_mod
+ orig_out, orig_err = sys.stdout, sys.stderr
+ try:
+ with pytest.raises(SystemExit):
+ run_mod.run_server(secure = True, cloudflare = False, silent = True)
+ assert sys.stdout is orig_out
+ assert sys.stderr is orig_err
+ finally:
+ sys.stdout, sys.stderr = orig_out, orig_err
diff --git a/studio/backend/tests/test_tee_progress_frames.py b/studio/backend/tests/test_tee_progress_frames.py
new file mode 100644
index 00000000000..9cde95ff505
--- /dev/null
+++ b/studio/backend/tests/test_tee_progress_frames.py
@@ -0,0 +1,178 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The session log's copy of carriage-return progress bars.
+
+A terminal overwrites a redraw in place; a file keeps every frame, so one tqdm bar landed as
+kilobytes of near-identical text. The tee keeps the last frame only, and withholds nothing
+except frames -- anything without a "\\r" is written the moment it arrives, so a hang cannot
+swallow a partial traceback or a prompt.
+"""
+
+import io
+import json
+
+from run import _TeeStream
+
+
+class _Sink:
+ def __init__(self):
+ self.buf = io.StringIO()
+
+ def write(self, data):
+ self.buf.write(data)
+ return len(data)
+
+ def flush(self):
+ pass
+
+ @property
+ def text(self):
+ return self.buf.getvalue()
+
+
+def _tee(chunks):
+ log, console = _Sink(), _Sink()
+ stream = _TeeStream(console, log)
+ for chunk in chunks:
+ stream.write(chunk)
+ return log.text, console.text
+
+
+def test_plain_output_is_unchanged_on_both_sides():
+ log, console = _tee(["plain line\n", "another\n"])
+ assert log == "plain line\nanother\n"
+ assert console == "plain line\nanother\n"
+
+
+def test_console_always_sees_every_frame():
+ _log, console = _tee(["\rbar 1%", "\rbar 50%", "\rbar 100%", "\n"])
+ # The animation is the console's whole point; only the file copy collapses.
+ assert console == "\rbar 1%\rbar 50%\rbar 100%\n"
+
+
+def test_progress_bar_collapses_to_its_final_frame():
+ log, _console = _tee(["\rbar 1%", "\rbar 50%", "\rbar 100%", "\n"])
+ assert log == "bar 100%\n"
+
+
+def test_bar_between_real_lines_keeps_both():
+ log, _console = _tee(["Loading\n", "\ra 10%", "\ra 99%", "\n", "done\n"])
+ assert log == "Loading\na 99%\ndone\n"
+
+
+def test_several_bars_in_one_chunk_collapse_per_line():
+ log, _console = _tee(["a\rb\rc\nd\re\n"])
+ assert log == "c\ne\n"
+
+
+def test_unterminated_prompt_after_a_bar_is_not_withheld():
+ # "Start Unsloth Studio now? [Y/n]: " never gets a newline; it must still reach the file,
+ # and on its own line rather than glued to the frame that was being held.
+ log, _console = _tee(["\rbar 40%", "Start Unsloth Studio now? [Y/n]: "])
+ assert log == "bar 40%\nStart Unsloth Studio now? [Y/n]: "
+
+
+def test_record_after_a_held_frame_stays_parseable():
+ # The reason the frame is closed off rather than prefixed: a structlog record arriving
+ # while a bar is mid-redraw must still be one JSON object on one line.
+ log, _console = _tee(["\rLoading weights: 47%", '{"event": "model_loaded"}\n'])
+ lines = log.splitlines()
+ assert lines == ["Loading weights: 47%", '{"event": "model_loaded"}']
+ json.loads(lines[-1])
+
+
+def test_close_lands_a_frame_nothing_came_back_to_supersede():
+ log, console = _Sink(), _Sink()
+ stream = _TeeStream(console, log)
+ stream.write("\rbar 90%")
+ stream.close()
+ assert log.text == "bar 90%\n"
+
+
+def test_hang_mid_bar_keeps_the_real_partial_line():
+ # The case that decides whether this is safe: a torn line is written, a frame is not.
+ log, _console = _tee(["Traceback (most recent call last):", "\rbar 5%"])
+ assert log == "Traceback (most recent call last):"
+
+
+def test_file_failure_never_reaches_the_console():
+ class Exploding(_Sink):
+ def write(self, data):
+ raise OSError("disk full")
+
+ console = _Sink()
+ stream = _TeeStream(console, Exploding())
+ stream.write("still printed\n")
+ assert console.text == "still printed\n"
+
+
+# ---------------------------------------------------------------------------------------
+# A "\r" is only a redraw when something follows it on the same line.
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_crlf_line_keeps_its_payload():
+ # "\r\n" is one terminator. Reading its "\r" as a redraw keeps the empty text after it
+ # and drops the line -- and on Windows every relayed child line arrives in this shape,
+ # so the session log goes blank exactly where the evidence should be.
+ log, _console = _tee(["Hardware detected: NVIDIA GeForce RTX 4090\r\n"])
+ assert log == "Hardware detected: NVIDIA GeForce RTX 4090\n"
+
+
+def test_a_crlf_traceback_is_not_reduced_to_blank_lines():
+ log, _console = _tee(
+ ['Traceback (most recent call last):\r\n File "run.py", line 3\r\nRuntimeError: boom\r\n']
+ )
+ assert log.splitlines() == [
+ "Traceback (most recent call last):",
+ ' File "run.py", line 3',
+ "RuntimeError: boom",
+ ]
+
+
+def test_a_crlf_record_stays_one_json_object():
+ log, _console = _tee(['{"event": "model_loaded"}\r\n'])
+ assert log == '{"event": "model_loaded"}\n'
+ json.loads(log.strip())
+
+
+def test_a_bar_signing_off_with_a_bare_cr_keeps_its_last_frame():
+ # tqdm's close() can leave the terminator on the same write as the final frame.
+ log, _console = _tee(["Map: 50%\rMap: 100%\r\n"])
+ assert log == "Map: 100%\n"
+
+
+def test_an_all_blank_line_never_writes_a_carriage_return():
+ # The handle appends the platform terminator itself, so a surviving "\r" lands as
+ # "\r\r\n" on Windows.
+ for chunk in ("\r\n", "\r\r\r\n", " \r \n"):
+ log, _console = _tee([chunk])
+ assert "\r" not in log, repr(chunk)
+
+
+def test_a_zero_length_write_does_not_glue_a_frame_onto_the_next_record():
+ # print("", end = "") is enough: an empty write used to read as a continuation of the
+ # held frame, which then fell through and was written with no newline.
+ log, _console = _tee(["\rLoading weights: 47%", "", '{"event": "model_loaded"}\n'])
+ lines = log.splitlines()
+ assert lines == ["Loading weights: 47%", '{"event": "model_loaded"}']
+ json.loads(lines[-1])
+
+
+def test_the_collapse_matches_the_desktop_reader():
+ """Same rule as collapse_progress_frames in src-tauri/src/process.rs.
+
+ Settings > Logs offers both sinks side by side, so a line must look the same in either.
+ """
+ cases = {
+ "plain line": "plain line",
+ "a\rb\rc": "c",
+ "bar 100%\r": "bar 100%",
+ "Map: 50%\rMap: 100%\r ": "Map: 100%",
+ "Hardware detected: ROCm": "Hardware detected: ROCm",
+ "TAURI_PORT=8888\r": "TAURI_PORT=8888",
+ }
+ for line, expected in cases.items():
+ log, _console = _tee([line + "\n"])
+ assert log == expected + "\n", f"{line!r} -> {log!r}, expected {expected!r}"
diff --git a/studio/backend/utils/log_retention.py b/studio/backend/utils/log_retention.py
new file mode 100644
index 00000000000..3a2909ac76e
--- /dev/null
+++ b/studio/backend/utils/log_retention.py
@@ -0,0 +1,81 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keep-newest-N retention for the per-session log directories.
+
+The server session log has capped itself since it was added; the llama-server and
+diffusion-server subprocess logs beside it never did, so they accumulated one file per
+model load for the life of the install (319 files going back two months on the machine
+this was found on). One helper so a fourth log directory cannot quietly opt out again.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Optional
+
+DEFAULT_KEEP = 20
+
+
+def prune_log_dir(
+ log_dir: Path,
+ pattern: str,
+ keep: int = DEFAULT_KEEP,
+ protect: Optional[Path] = None,
+) -> None:
+ """Delete all but the ``keep`` most recently modified ``pattern`` files in ``log_dir``.
+
+ ``protect`` is the log the caller is writing to. It is never deleted and counts as one
+ of the ``keep``, so the directory settles at ``keep``, not ``keep + 1``. Call this
+ *after* opening it: pruning first leaves an extra file every time, and the new file
+ only sorts newest until two loads share a second or a clock steps back.
+
+ Only regular files count. A directory matching the glob is not a log, and a symlink is
+ stat'd through but unlinked by name, so counting either shrinks how many real logs are
+ kept.
+
+ Best effort throughout: retention must never take down the thing it logs for, and
+ losing a race to a concurrent writer just leaves the file for the next call. One
+ unreadable entry skips that entry, not the directory -- a single dangling symlink used
+ to abort the sort and disable retention entirely.
+ """
+ if keep < 0:
+ return
+
+ protected = None
+ if protect is not None:
+ try:
+ protected = Path(protect).resolve()
+ except OSError:
+ protected = Path(protect)
+
+ entries = []
+ saw_protected = False
+ try:
+ candidates = list(log_dir.glob(pattern))
+ except OSError:
+ return
+ for path in candidates:
+ try:
+ stat = path.stat()
+ if not path.is_file():
+ continue
+ if protected is not None and path.resolve() == protected:
+ saw_protected = True
+ continue
+ except OSError:
+ # Dangling symlink, vanished file, or an unreadable directory. Skip the entry
+ # only: one bad name must not disable retention for the whole directory.
+ continue
+ entries.append((stat.st_mtime, path))
+
+ # The protected file occupies one of the slots, so the total stays at `keep`.
+ room = keep - 1 if saw_protected else keep
+ entries.sort(key = lambda item: item[0])
+ if room > 0:
+ entries = entries[:-room]
+ for _mtime, old in entries:
+ try:
+ old.unlink(missing_ok = True)
+ except OSError:
+ pass
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index ed3c1d72e6c..96ccf8c93c8 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -1,5 +1,5 @@
use crate::diagnostics::{self, BackendLog, DiagnosticsState};
-use log::{error, info, warn};
+use log::{debug, error, info, warn};
use process_wrap::std::*;
use regex::Regex;
use std::collections::VecDeque;
@@ -1215,6 +1215,64 @@ pub(crate) fn trim_line_endings(bytes: &[u8]) -> &[u8] {
&bytes[..end]
}
+/// Longest single line we will hand to `tauri.log`. Matches the phase log's own cap, which
+/// already trimmed these; without it the same line was capped on one sink and not the other.
+pub(crate) const MAX_BACKEND_LOG_LINE_BYTES: usize = 16 * 1024;
+
+/// Keep only the last frame of a carriage-return progress redraw.
+///
+/// We read to `\n`, so a tqdm or pip bar arrives as every frame it ever drew concatenated
+/// into one line, across three sinks: one "Loading weights" bar measured 5086 bytes. Only
+/// the final frame carries information. Text with no interior `\r` is returned untouched,
+/// and a bar whose last frame is empty keeps the last non-empty one rather than a blank line.
+///
+/// `_TeeStream._last_frame` in studio/backend/run.py applies this same rule to this same
+/// input for the session log, so the two sinks stay interchangeable for a reader.
+pub(crate) fn collapse_progress_frames(text: &str) -> &str {
+ if !text.contains('\r') {
+ return text;
+ }
+ text.rsplit('\r')
+ .find(|frame| !frame.trim().is_empty())
+ // All frames blank, so the line is blank. Return a frame, not the whole text, which
+ // still holds the `\r` we were asked to collapse away.
+ .unwrap_or_else(|| text.rsplit('\r').next().unwrap_or(""))
+}
+
+/// True when the line is one of the backend's own structured access-log records **and it
+/// reports success**.
+///
+/// These already reach the phase log (stream-tagged and stamped) and the backend's own
+/// session log, so a third copy in `tauri.log` was pure duplication: 4056 of 5308 lines on
+/// an idle 4h session, pushing real failures out of the 5 MiB window inside a day.
+///
+/// The 2xx check is the point. The backend's heartbeat suppressor exempts non-2xx so a
+/// failing poll logs every time, and `tauri.log` is where a watchdog going red gets read.
+/// A record with no `status_code` we cannot vouch for, so it keeps INFO too.
+///
+/// For the records this *does* match, "debug" means dropped, not demoted: `setup_logging`
+/// in main.rs builds every logger at `LevelFilter::Info` with no `RUST_LOG` to raise it,
+/// so `log::max_level()` is `Info` -- including under backend `--verbose`, which emits
+/// *more* of them. Deliberate: `append_phase_line` below runs before this decision, and
+/// both that log and the session log are already offered by the support report and by
+/// Settings > Logs. Nothing is lost; it moves one source over in the picker.
+fn is_backend_access_log_line(text: &str) -> bool {
+ let trimmed = text.trim_start();
+ if !trimmed.starts_with('{') {
+ return false;
+ }
+ let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) else {
+ return false;
+ };
+ if value.get("event").and_then(|event| event.as_str()) != Some("request_completed") {
+ return false;
+ }
+ matches!(
+ value.get("status_code").and_then(|code| code.as_u64()),
+ Some(200..=299)
+ )
+}
+
/// Windows `CREATE_NO_WINDOW` flag — suppresses console windows for child processes.
#[cfg(windows)]
pub(crate) const CREATE_NO_WINDOW: u32 = 0x08000000;
@@ -3724,7 +3782,8 @@ fn read_output_stream<R: std::io::Read>(
break;
}
Ok(_) => {
- let text = String::from_utf8_lossy(trim_line_endings(&buf)).into_owned();
+ let raw = String::from_utf8_lossy(trim_line_endings(&buf));
+ let text = collapse_progress_frames(&raw).to_owned();
let log_line = if is_stderr {
format!("[stderr] {}", text)
} else {
@@ -3788,7 +3847,19 @@ fn read_output_stream<R: std::io::Read>(
});
}
- info!("[backend] {}", log_line);
+ // Keeping the successful access records out leaves tauri.log for the startup
+ // banner, hardware lines, stderr, tracebacks and failed requests.
+ if is_backend_access_log_line(&text) {
+ debug!("[backend] {}", log_line);
+ } else if log_line.len() > MAX_BACKEND_LOG_LINE_BYTES {
+ let mut end = MAX_BACKEND_LOG_LINE_BYTES;
+ while end > 0 && !log_line.is_char_boundary(end) {
+ end -= 1;
+ }
+ info!("[backend] {} [line truncated]", &log_line[..end]);
+ } else {
+ info!("[backend] {}", log_line);
+ }
let _ = app.emit("server-log", &log_line);
}
@@ -4238,6 +4309,135 @@ fn stop_backend_inner(
result
}
+#[cfg(test)]
+mod backend_log_line_tests {
+ use super::*;
+
+ #[test]
+ fn plain_line_is_untouched() {
+ assert_eq!(collapse_progress_frames("Hardware detected: ROCm"), "Hardware detected: ROCm");
+ assert_eq!(collapse_progress_frames(""), "");
+ }
+
+ #[test]
+ fn progress_bar_keeps_only_the_final_frame() {
+ let bar = "Loading weights: 0%| | 0/617\rLoading weights: 47%| | 288/617\rLoading weights: 100%|#| 617/617";
+ assert_eq!(collapse_progress_frames(bar), "Loading weights: 100%|#| 617/617");
+ }
+
+ #[test]
+ fn trailing_blank_frame_falls_back_to_the_last_real_one() {
+ assert_eq!(collapse_progress_frames("Map: 50%\rMap: 100%\r "), "Map: 100%");
+ }
+
+ #[test]
+ fn an_all_blank_line_never_keeps_its_carriage_returns() {
+ // The log handle appends the platform terminator itself, so a `\r` that survives
+ // here lands as "\r\r\n" in the file on Windows.
+ for line in ["\r", "\r\r\r", " \r "] {
+ assert!(
+ !collapse_progress_frames(line).contains('\r'),
+ "collapse left a carriage return in {line:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn a_crlf_line_keeps_its_payload() {
+ // read_output_stream trims the terminator before collapsing, so a CRLF's `\r` is
+ // never read as a redraw ending in an empty frame. Every line a Windows child
+ // relays arrives in this shape.
+ let raw = b"Hardware detected: NVIDIA GeForce RTX 4090\r\n";
+ let trimmed = String::from_utf8_lossy(trim_line_endings(raw)).into_owned();
+ assert_eq!(
+ collapse_progress_frames(&trimmed),
+ "Hardware detected: NVIDIA GeForce RTX 4090"
+ );
+ }
+
+ #[test]
+ fn a_crlf_terminated_bar_still_collapses() {
+ let raw = b"Map: 50%\rMap: 100%\r\n";
+ let trimmed = String::from_utf8_lossy(trim_line_endings(raw)).into_owned();
+ assert_eq!(collapse_progress_frames(&trimmed), "Map: 100%");
+ }
+
+ #[test]
+ fn a_crlf_json_record_stays_parseable() {
+ let raw = b"{\"event\": \"request_completed\", \"status_code\": 200}\r\n";
+ let trimmed = String::from_utf8_lossy(trim_line_endings(raw)).into_owned();
+ let line = collapse_progress_frames(&trimmed);
+ assert!(serde_json::from_str::<serde_json::Value>(line).is_ok(), "{line:?}");
+ assert!(is_backend_access_log_line(line));
+ }
+
+ #[test]
+ fn a_marker_line_survives_the_collapse() {
+ // read_output_stream runs the TAURI_PORT regex against the collapsed text, so a
+ // marker that shares its line with a redraw must still be the frame we keep.
+ for raw in [
+ &b"TAURI_PORT=8888\n"[..],
+ &b"TAURI_PORT=8888\r\n"[..],
+ &b"Loading weights: 47%\rTAURI_PORT=8888\r\n"[..],
+ ] {
+ let trimmed = String::from_utf8_lossy(trim_line_endings(raw)).into_owned();
+ assert_eq!(collapse_progress_frames(&trimmed), "TAURI_PORT=8888", "{raw:?}");
+ }
+ }
+
+ #[test]
+ fn truncation_lands_on_a_character_boundary() {
+ let line = "\u{1f680}".repeat(MAX_BACKEND_LOG_LINE_BYTES);
+ let mut end = MAX_BACKEND_LOG_LINE_BYTES;
+ while end > 0 && !line.is_char_boundary(end) {
+ end -= 1;
+ }
+ // Slicing at `end` must not panic and must stay under the cap.
+ assert!(end <= MAX_BACKEND_LOG_LINE_BYTES);
+ assert_eq!(line[..end].len(), end);
+ }
+
+ #[test]
+ fn access_log_records_are_recognised() {
+ assert!(is_backend_access_log_line(
+ r#"{"timestamp": "2026-08-13T14:22:11Z", "level": "info", "event": "request_completed", "path": "/api/liveness", "status_code": 200}"#
+ ));
+ assert!(is_backend_access_log_line(
+ r#"{"event": "request_completed", "path": "/api/models/local", "status_code": 204}"#
+ ));
+ }
+
+ #[test]
+ fn failed_access_records_keep_their_info_line() {
+ // A watchdog probe going red is the case tauri.log exists for; the backend logs
+ // every one of these (the heartbeat suppressor is 2xx-only) and so must we.
+ assert!(!is_backend_access_log_line(
+ r#"{"event": "request_completed", "path": "/api/liveness", "status_code": 503}"#
+ ));
+ assert!(!is_backend_access_log_line(
+ r#"{"event": "request_completed", "path": "/api/train/start", "status_code": 401}"#
+ ));
+ // No status at all: not a record we can vouch for.
+ assert!(!is_backend_access_log_line(
+ r#"{"event": "request_completed", "path": "/api/liveness"}"#
+ ));
+ }
+
+ #[test]
+ fn other_structured_events_and_plain_text_are_not() {
+ assert!(!is_backend_access_log_line(
+ r#"{"level": "info", "event": "engine_stats", "gen_tok_s": 64.9}"#
+ ));
+ assert!(!is_backend_access_log_line("TAURI_PORT=8888"));
+ // Mentioning the event name in free text must not silence the line.
+ assert!(!is_backend_access_log_line("saw request_completed in the trace"));
+ // Truncated JSON is not a record we can vouch for, so it keeps its INFO line.
+ assert!(!is_backend_access_log_line(
+ r#"{"event": "request_completed", "status_code": 200"#
+ ));
+ }
+}
+
// A login-started desktop on Windows inherits C:\Windows\system32 (issue #8510),
// and so did every CLI child, where the Python CLI refuses to run. These pin the
// replacement directory and that each command carries it.