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.

Studio: read the logs from inside the app, in Settings > Debugging (#8690)

Daniel Han046e3ee112a3
diff --git a/studio/backend/loggers/handlers.py b/studio/backend/loggers/handlers.py
index ab28222cf33..7e203535863 100644
--- a/studio/backend/loggers/handlers.py
+++ b/studio/backend/loggers/handlers.py
@@ -131,6 +131,7 @@ _QUIET_SUCCESS_PATHS = {
"/api/llama/update-status",
"/api/export/logs",
"/api/export/status",
+ # The Settings > Logs viewer polls are suppressed in _SELF_READ_PATHS below.
"/api/hub/download-status",
"/api/hub/download-progress",
"/api/hub/gguf-download-progress",
@@ -166,12 +167,30 @@ _CHAT_LIST_PATHS = {
}
+# The log viewer polls these while reading the very file this middleware writes,
+# so unsuppressed each poll appends a record the next poll reads back and the log
+# grows forever. _is_redundant_repeat does not cover it: it keys on the query
+# string, and every poll carries a fresh cursor.
+# Separate from _QUIET_SUCCESS_PATHS because --verbose must NOT lift this one:
+# --verbose is what someone debugging turns on, and here the extra noise (~390
+# bytes/s at the 1 Hz Live poll rate) buries the failure they opened the viewer for.
+_SELF_READ_PATHS = {
+ "/api/settings/debug/logs",
+ "/api/settings/debug/logs/sources",
+}
+
+
def _is_quiet_success(method: str, path: str, status_code: int, pre_auth: bool) -> bool:
"""GET-only. Suppress a 2xx poll line that carries no signal, plus a chat list
poll's transient pre-auth 401 (only in the bootstrap window before the first
successful token refresh). Mutations, real (post-refresh) auth failures, and
- all other errors always log. --verbose disables the whole suppressor."""
- if _VERBOSE_ACCESS_LOG or method != "GET":
+ all other errors always log. --verbose disables the whole suppressor, except
+ for the log viewer's own reads."""
+ if method != "GET":
+ return False
+ if 200 <= status_code < 300 and path in _SELF_READ_PATHS:
+ return True
+ if _VERBOSE_ACCESS_LOG:
return False
if 200 <= status_code < 300:
return path in _QUIET_SUCCESS_PATHS or path in _CHAT_LIST_PATHS
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index ec184207422..e7cf1c65958 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -2075,3 +2075,133 @@ def update_personalization_settings(
# Return the stored record, not the defaults-filled request, so the response
# matches storage (and the next GET) for fields the client omitted.
return PersonalizationPayload.model_validate(merged)
+
+
+# ── Logs: read the log files from inside the app ─────────────────────────────
+# Backs the Settings > Logs tab. The session log always existed, but its
+# path was only printed to a console the desktop user never sees.
+
+
+class DebugLogSourceModel(BaseModel):
+ id: str
+ family: str
+ label: str
+ realpath: str
+ size_bytes: int
+ modified_at: float
+ is_current: bool
+
+
+class DebugLogSourcesResponse(BaseModel):
+ sources: list[DebugLogSourceModel]
+ default_source_id: Optional[str] = None
+ file_logging_disabled: bool = False
+
+
+class DebugLogResponse(BaseModel):
+ status: Literal["ok", "empty", "missing", "unreadable", "disabled"]
+ reason: Optional[str] = None
+ source_id: Optional[str] = None
+ realpath: Optional[str] = None
+ lines: list[str] = Field(default_factory = list)
+ cursor: Optional[str] = None
+ reset: bool = False
+ reset_reason: Optional[str] = None
+ dropped_bytes: int = 0
+ truncated_head: bool = False
+ # The reader stopped at the response cap and the rest arrives on the next
+ # poll. Without this the caller cannot tell a complete answer from a partial
+ # one, which is invisible in manual mode because no next poll is coming.
+ more_pending: bool = False
+ # File logging is off, so anything readable here is a PREVIOUS session and
+ # will never grow. The status stays "ok" because the content is real and
+ # worth reading; saying nothing made a stale log look live.
+ file_logging_disabled: bool = False
+ size_bytes: int = 0
+
+
[email protected]("/debug/logs/sources", response_model = DebugLogSourcesResponse)
+def get_debug_log_sources(
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> DebugLogSourcesResponse:
+ """Every log file the viewer may read, newest first within each family.
+
+ Individual files, not one entry per family: the llama runner writes one file
+ per load ATTEMPT, so after a retry the useful one is often not the newest.
+ """
+ from utils import debug_log_sources
+
+ sources = debug_log_sources.list_sources()
+ return DebugLogSourcesResponse(
+ sources = [DebugLogSourceModel(**vars(source)) for source in sources],
+ default_source_id = debug_log_sources.default_source_id(),
+ file_logging_disabled = debug_log_sources.file_logging_disabled(),
+ )
+
+
[email protected]("/debug/logs", response_model = DebugLogResponse)
+def get_debug_log(
+ source: Optional[str] = None,
+ cursor: Optional[str] = None,
+ lines: int = 1000,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> DebugLogResponse:
+ """The tail of one log, then only what was appended after `cursor`.
+
+ Every content state answers 200. This is polled once a second in Live mode,
+ and a 404 or a 500 on "the file is not there yet" would make the viewer
+ flash an error on every tick; the caller reads `status` instead.
+ """
+ from utils import debug_log_reader, debug_log_sources
+
+ source_id = source or debug_log_sources.default_source_id()
+ if not source_id:
+ disabled = debug_log_sources.file_logging_disabled()
+ return DebugLogResponse(
+ status = "disabled" if disabled else "missing",
+ reason = (
+ "File logging is turned off (UNSLOTH_STUDIO_NO_FILE_LOG=1)."
+ if disabled
+ else "No log files have been written yet."
+ ),
+ )
+
+ path = debug_log_sources.resolve_source_id(source_id)
+ if path is None:
+ # An id the enumeration no longer produces. 404 here (unlike the content
+ # states above) so a stale picker refetches its sources.
+ raise HTTPException(status_code = 404, detail = "Unknown log source.")
+
+ try:
+ result = debug_log_reader.read_since(path, cursor, lines)
+ except FileNotFoundError:
+ return DebugLogResponse(
+ status = "missing",
+ reason = "The log file was removed.",
+ source_id = source_id,
+ )
+ except (OSError, PermissionError) as exc:
+ # The message embeds the path, so it goes through redaction too.
+ from utils.log_redaction import redact_log_text
+ return DebugLogResponse(
+ status = "unreadable",
+ reason = redact_log_text(str(exc)),
+ source_id = source_id,
+ )
+
+ return DebugLogResponse(
+ status = "empty" if (result.size_bytes == 0 and not result.lines) else "ok",
+ source_id = source_id,
+ realpath = str(path),
+ lines = result.lines,
+ cursor = result.cursor,
+ reset = result.reset,
+ reset_reason = result.reset_reason,
+ dropped_bytes = result.dropped_bytes,
+ truncated_head = result.truncated_head,
+ more_pending = result.more_pending,
+ file_logging_disabled = debug_log_sources.source_is_frozen(source_id),
+ size_bytes = result.size_bytes,
+ )
diff --git a/studio/backend/tests/test_debug_log_reader.py b/studio/backend/tests/test_debug_log_reader.py
new file mode 100644
index 00000000000..28bd46b2e24
--- /dev/null
+++ b/studio/backend/tests/test_debug_log_reader.py
@@ -0,0 +1,280 @@
+# 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 reader has to stay cheap on a multi-GB session log (there is no rotation,
+only a startup prune of the newest 20 files) and it must not resend what the
+caller already has."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from utils.debug_log_reader import (
+ MAX_APPEND_BYTES,
+ MAX_TAIL_BYTES,
+ read_since,
+ read_tail,
+)
+
+
+def _write(
+ path: Path,
+ count: int,
+ prefix: str = "line",
+) -> None:
+ path.write_text("".join(f"{prefix}{i}\n" for i in range(count)), encoding = "utf-8")
+
+
+def test_an_empty_file_reads_as_no_lines(tmp_path):
+ path = tmp_path / "empty.log"
+ path.write_text("")
+ result = read_tail(path)
+ assert result.lines == []
+ assert result.size_bytes == 0
+
+
+def test_the_tail_is_the_newest_lines(tmp_path):
+ path = tmp_path / "a.log"
+ _write(path, 1001)
+ result = read_tail(path)
+ assert len(result.lines) == 1000
+ assert result.lines[0] == "line1"
+ assert result.lines[-1] == "line1000"
+
+
+def test_a_short_file_returns_everything(tmp_path):
+ path = tmp_path / "a.log"
+ _write(path, 999)
+ assert len(read_tail(path).lines) == 999
+
+
+def test_a_last_line_without_a_newline_is_still_shown(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("first\nno trailing newline")
+ assert read_tail(path).lines == ["first", "no trailing newline"]
+
+
+def test_a_huge_file_is_read_in_a_bounded_window(tmp_path, monkeypatch):
+ """The whole point: cost must not scale with the file."""
+ path = tmp_path / "big.log"
+ with open(path, "w", encoding = "utf-8") as handle:
+ for i in range(200_000):
+ handle.write(f"padding line {i} {'a' * 40}\n")
+ assert path.stat().st_size > 8 * MAX_TAIL_BYTES
+
+ read_bytes = {"total": 0}
+ real_open = open
+
+ class _Counting:
+ def __init__(self, handle):
+ self._handle = handle
+
+ def read(self, size = -1):
+ chunk = self._handle.read(size)
+ read_bytes["total"] += len(chunk)
+ return chunk
+
+ def __getattr__(self, name):
+ return getattr(self._handle, name)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return self._handle.__exit__(*exc)
+
+ def _counting_open(
+ file,
+ mode = "r",
+ *args,
+ **kwargs,
+ ):
+ handle = real_open(file, mode, *args, **kwargs)
+ return _Counting(handle) if "b" in mode else handle
+
+ monkeypatch.setattr("builtins.open", _counting_open)
+ result = read_tail(path)
+ monkeypatch.undo()
+
+ assert len(result.lines) == 1000
+ # One block of slack for the block-aligned backward scan.
+ assert read_bytes["total"] <= MAX_TAIL_BYTES + 65_536
+
+
+def test_only_appended_lines_come_back(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("a\nb\n")
+ first = read_tail(path)
+ with open(path, "a", encoding = "utf-8") as handle:
+ handle.write("c\nd\n")
+ second = read_since(path, first.cursor)
+ assert second.lines == ["c", "d"]
+ assert second.reset is False
+
+
+def test_an_idle_poll_is_empty_and_not_an_error(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("a\n")
+ first = read_tail(path)
+ second = read_since(path, first.cursor)
+ assert second.lines == []
+ assert second.reset is False
+ assert second.reset_reason is None
+
+
+def test_repeated_polls_never_resend(tmp_path):
+ """A poll loop that resends the tail every tick would look fine in a single
+ assertion and be unusable in the UI, so this walks 200 rounds."""
+ path = tmp_path / "a.log"
+ path.write_text("0\n")
+ cursor = read_tail(path).cursor
+ delivered = 0
+ for i in range(1, 201):
+ with open(path, "a", encoding = "utf-8") as handle:
+ handle.write(f"{i}\n")
+ result = read_since(path, cursor)
+ assert result.reset is False, f"unexpected reset on poll {i}"
+ cursor = result.cursor
+ delivered += len(result.lines)
+ assert delivered == 200
+
+
+def test_a_half_written_line_is_held_back_then_delivered_once(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("a\n")
+ cursor = read_tail(path).cursor
+ with open(path, "a", encoding = "utf-8") as handle:
+ handle.write("partial")
+ held = read_since(path, cursor)
+ assert held.lines == []
+ with open(path, "a", encoding = "utf-8") as handle:
+ handle.write(" line\n")
+ completed = read_since(path, held.cursor)
+ assert completed.lines == ["partial line"]
+ assert read_since(path, completed.cursor).lines == []
+
+
+def test_a_truncated_file_resets_instead_of_returning_garbage(tmp_path):
+ path = tmp_path / "a.log"
+ _write(path, 50)
+ cursor = read_tail(path).cursor
+ path.write_text("fresh\n")
+ result = read_since(path, cursor)
+ assert result.reset is True
+ assert result.reset_reason == "truncated"
+ assert result.lines == ["fresh"]
+
+
+def test_a_writer_outrunning_the_reader_is_bounded(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("x\n")
+ cursor = read_tail(path).cursor
+ with open(path, "a", encoding = "utf-8") as handle:
+ for i in range(60_000):
+ handle.write(f"flood {i} {'y' * 34}\n")
+ result = read_since(path, cursor)
+ assert result.dropped_bytes > 0
+ assert len(result.lines) <= 2000
+
+
+def test_an_unusable_cursor_gives_a_fresh_tail_not_an_error(tmp_path):
+ path = tmp_path / "a.log"
+ _write(path, 5)
+ result = read_since(path, "not-a-real-cursor")
+ assert result.reset is True
+ assert result.reset_reason == "cursor_stale"
+ assert len(result.lines) == 5
+
+
+def test_undecodable_bytes_do_not_raise(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_bytes(b"good\n\xff\xfe still readable\n")
+ assert len(read_tail(path).lines) == 2
+
+
+def test_crlf_is_normalised(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_bytes(b"one\r\ntwo\r\n")
+ assert read_tail(path).lines == ["one", "two"]
+
+
+def test_the_reader_redacts_so_a_caller_cannot_forget(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("using hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345 now\n")
+ assert "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345" not in read_tail(path).lines[0]
+
+
+def test_a_burst_larger_than_one_response_is_delivered_not_dropped(tmp_path):
+ """The response used to keep the NEWEST 2000 lines while advancing the
+ cursor past all of them, so a model load that logged more than that between
+ two polls lost the head of its own failure, and said dropped_bytes = 0."""
+ path = tmp_path / "a.log"
+ path.write_text("x\n")
+ cursor = read_tail(path).cursor
+ with open(path, "a", encoding = "utf-8") as handle:
+ for i in range(3000):
+ handle.write(f"appended{i}\n")
+
+ first = read_since(path, cursor)
+ assert len(first.lines) == 2000
+ assert first.lines[0] == "appended0", "the oldest of the burst must not be discarded"
+ assert first.more_pending is True
+
+ second = read_since(path, first.cursor)
+ assert second.lines == [f"appended{i}" for i in range(2000, 3000)]
+ assert second.more_pending is False
+ assert read_since(path, second.cursor).lines == []
+
+
+def test_a_record_larger_than_the_window_shows_its_tail_not_an_empty_pane(tmp_path):
+ """A single record bigger than the bounded read (a native dump, a \\r-only
+ progress run, a giant JSON line) filled the whole window, so dropping the
+ partial head left nothing: the viewer rendered an EMPTY pane on a log that
+ was megabytes long, and the cursor advanced past the record anyway."""
+ path = tmp_path / "a.log"
+ body = "Z" * (MAX_TAIL_BYTES + 100_000)
+ path.write_text("older line\n" + body + " END\n", encoding = "utf-8")
+
+ result = read_tail(path)
+ assert result.lines, "a non-empty log must never read as no lines at all"
+ assert result.lines[-1].endswith(" END")
+ assert result.truncated_head is True
+ # Still bounded: the tail of the record, not the whole record.
+ assert sum(len(line) for line in result.lines) <= MAX_TAIL_BYTES
+
+
+def test_an_unterminated_record_larger_than_the_window_still_shows(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("older line\n" + "Z" * (MAX_TAIL_BYTES + 100_000) + " LIVE", encoding = "utf-8")
+ result = read_tail(path)
+ assert result.lines and result.lines[-1].endswith(" LIVE")
+
+
+def test_an_oversized_append_with_no_newline_is_not_swallowed(tmp_path):
+ path = tmp_path / "a.log"
+ path.write_text("start\n")
+ cursor = read_tail(path).cursor
+ with open(path, "a", encoding = "utf-8") as handle:
+ handle.write("Q" * (MAX_APPEND_BYTES + 50_000) + " END\n")
+
+ result = read_since(path, cursor)
+ assert result.lines, "the append must not vanish while the cursor moves past it"
+ assert result.lines[-1].endswith(" END")
+ assert result.dropped_bytes > 0
+ assert read_since(path, result.cursor).lines == []
+
+
+def test_a_colorized_credential_is_masked_before_it_reaches_the_viewer(tmp_path):
+ """The pane strips ANSI before rendering, so an escape between the key and
+ its value used to defeat the redaction anchors and show a clean token."""
+ path = tmp_path / "a.log"
+ path.write_text(
+ "\x1b[36mhf_token\x1b[0m=\x1b[35mhf_AbCdEfGhIjKlMnOpQrStUvWxYz012345\x1b[0m\n",
+ encoding = "utf-8",
+ )
+ assert "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345" not in "\n".join(read_tail(path).lines)
diff --git a/studio/backend/tests/test_debug_log_redaction.py b/studio/backend/tests/test_debug_log_redaction.py
new file mode 100644
index 00000000000..ff2148a8522
--- /dev/null
+++ b/studio/backend/tests/test_debug_log_redaction.py
@@ -0,0 +1,291 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Credentials must not reach the log viewer, and ordinary log content must
+survive untouched. The negative cases carry the weight here: over-redaction
+hides the failure the user opened the log to read."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from utils.log_redaction import REDACTED, redact_log_text
+
+_SLACK_SHAPED = "xox" + "b-" + "1234567890" + "-ABCDEFGHIJKLMNOP"
+
+# (line, the substring that must be gone)
+SECRETS = [
+ (
+ "Downloading with token hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345",
+ "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345",
+ ),
+ (
+ 'GET /v1/chat -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg"',
+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg",
+ ),
+ (
+ "llama-server --api-key sk-proj-AbCdEf0123456789AbCdEf --port 8080",
+ "sk-proj-AbCdEf0123456789AbCdEf",
+ ),
+ ("HF_TOKEN=hf_zzzzzzzzzzzzzzzzzzzzzzzzzzz", "hf_zzzzzzzzzzzzzzzzzzzzzzzzzzz"),
+ ('{"event":"auth","api_key":"abcdef123456","model":"gpt-4o"}', "abcdef123456"),
+ ("AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE", "AKIAIOSFODNN7EXAMPLE"),
+ (
+ "https://cdn.example.com/m.gguf?X-Amz-Signature=deadbeef0123456789&X-Amz-Expires=900",
+ "deadbeef0123456789",
+ ),
+ (
+ "git clone https://dan:[email protected]/x/y",
+ "ghp_ABCDEFGHIJKLMNOPQRST0123",
+ ),
+ ("password: hunter2hunter2", "hunter2hunter2"),
+ # "_" is a word character, so a \b before the key name never fires inside an
+ # env-style name; all of these used to survive in the clear.
+ ("OPENAI_API_KEY=opaquevalue123456", "opaquevalue123456"),
+ ("TOGETHER_API_KEY=abc123def456ghi789", "abc123def456ghi789"),
+ (
+ "WANDB_API_KEY=0123456789abcdef0123456789abcdef01234567",
+ "0123456789abcdef0123456789abcdef01234567",
+ ),
+ ("DATABASE_PASSWORD=hunter2hunter2", "hunter2hunter2"),
+ ("training config: wandb_token='local-9f8e7d6c5b4a3210'", "local-9f8e7d6c5b4a3210"),
+ # The key/value rule captures the scheme word as the "value", so the
+ # credential after it was never looked at.
+ ("Authorization: Basic dXNlcm5hbWU6c3VwZXJzZWNyZXQ=", "dXNlcm5hbWU6c3VwZXJzZWNyZXQ="),
+ ("headers={'authorization': 'Basic dXNlcjpwdw=='}", "dXNlcjpwdw=="),
+ # Studio's UI session cookie gates these very endpoints.
+ ("Cookie: unsloth_session=8f3c9d1ab77e4f0a9c2b3d4e", "8f3c9d1ab77e4f0a9c2b3d4e"),
+ ("set-cookie: refresh=8f3c9d1ab77e4f0a9c2b; HttpOnly", "8f3c9d1ab77e4f0a9c2b"),
+ ("CI token glpat-ABCDEFGHIJKLMNOPQRST", "glpat-ABCDEFGHIJKLMNOPQRST"),
+ # Assembled, not written out: even an invented Slack-shaped literal trips
+ # GitHub push protection.
+ ("posting with " + _SLACK_SHAPED, _SLACK_SHAPED),
+ ("refreshed ya29.a0ARrdaM9xQZ1lKjHgFdSaQwErTyUiOp", "ya29.a0ARrdaM9xQZ1lKjHgFdSaQwErTyUiOp"),
+ # A numeric password is still a password, unlike numbers elsewhere.
+ ("password=1234567890123", "1234567890123"),
+ # A quoted passphrase with spaces: stopping at the first space left every
+ # word but the first in the clear while still printing <redacted>.
+ (
+ '{"event":"login_failed","password":"correct horse battery staple"}',
+ "horse battery staple",
+ ),
+ ("password='correct horse battery staple'", "horse battery staple"),
+ # The flag rule's value class rejected a leading quote, so this line
+ # survived untouched.
+ ('llama-server --api-key "abcdef ghijklmnop" --port 8080', "abcdef ghijklmnop"),
+]
+
+# Real log lines. Each one must come back byte for byte.
+KEEP = [
+ "unsloth/Llama-3.2-3B-Instruct-unsloth-bnb-4bit",
+ "blk.31.attn_q.weight q4_K [ 3072, 3072 ]",
+ "/home/dan/.unsloth/studio/cache/models/models--unsloth--gemma-3-4b-it/snapshots/9a2f1c8b7e6d5c4b3a2918f7e6d5c4b3a2918f7e",
+ "sha256:4f3c9a1b2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c",
+ "n_tokens = 4096",
+ "token_id=128009",
+ "slot 0 released, 512 tokens in cache",
+ "revision=a1b2c3d4e5f6",
+ "CUDA error: out of memory (device 0, 23.6 GiB free)",
+ "| Traceback (most recent call last):",
+ "| RuntimeError: Input type (float) and bias type (c10::BFloat16) should be the same",
+ "Bearer",
+ ' File "/opt/venv/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1518 in _call_impl',
+ "llama-server --port 8080 --n-gpu-layers 99 --ctx-size 32768",
+ '{"timestamp":"2026-08-13T09:00:00Z","level":"error","event":"llama_start_failed"}',
+ # Words a credential rule is tempted by, as Studio actually writes them.
+ # Blanking any of these hides the failure being diagnosed.
+ "provider rejected the request: Bearer credentials expired",
+ "Authorization header missing, expected Bearer authentication",
+ "manifest digest sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
+ "tokenizer: eos_token = <|eot_id|>, bos_token = <|begin_of_text|>",
+ "pad_token_id=128004 set from config",
+ "note: cookie support is disabled in this webview",
+ "reading secret_sauce_path from the recipe",
+ "hint: password authentication is not configured for this endpoint",
+ "downloaded checkpoint-sk-9f8a7b6c5d4e3f2a1b0c9d8e7f.safetensors",
+ "i18n: falling back from sk-SK to en",
+ # "key" in an object storage URL names the object, so it stays readable.
+ "https://cdn-lfs.hf.co/repos/ab/cd/model.gguf?download=true&key=publicfilename",
+ "provider config: api_key = None",
+]
+
+
[email protected]("line,secret", SECRETS, ids = [s[1][:18] for s in SECRETS])
+def test_a_credential_never_survives(line, secret):
+ out = redact_log_text(line)
+ assert secret not in out
+ assert "<redacted>" in out
+
+
[email protected]("line", KEEP, ids = [k[:28] for k in KEEP])
+def test_ordinary_log_content_is_untouched(line):
+ assert redact_log_text(line) == line
+
+
[email protected]("line", [s[0] for s in SECRETS] + KEEP)
+def test_redaction_is_idempotent(line):
+ once = redact_log_text(line)
+ assert redact_log_text(once) == once
+
+
+QUOTED = [
+ # (line, what the whole line must come back as)
+ ('password="correct horse battery staple"', 'password="<redacted>"'),
+ ("password='correct horse battery staple'", "password='<redacted>'"),
+ ('llama-server --api-key "abcdef ghijklmnop"', 'llama-server --api-key "<redacted>"'),
+ # The value ends at its own closing quote, so the fields after it survive.
+ (
+ '{"password": "correct horse battery staple", "model": "gpt-4o"}',
+ '{"password": "<redacted>", "model": "gpt-4o"}',
+ ),
+ # An escaped quote inside the value does not end it early.
+ ('password="corr\\"ect horse staple"', 'password="<redacted>"'),
+ # Quoting puts the scheme inside the value; it stays, the credential goes.
+ ('password: "Basic dXNlcjpwdw=="', 'password: "Basic <redacted>"'),
+]
+
+
[email protected]("line,expected", QUOTED, ids = [q[0][:24] for q in QUOTED])
+def test_a_quoted_credential_is_masked_whole(line, expected):
+ """The value patterns used to stop at whitespace, so a quoted credential
+ containing spaces was masked only up to its first space and the rest of the
+ secret was printed next to the <redacted> marker."""
+ assert redact_log_text(line) == expected
+
+
+def test_an_unterminated_quote_does_not_mask_the_next_line():
+ """\\n is outside the quoted value class, so a writer that opened a quote
+ and never closed it cannot blank the log lines that follow it."""
+ text = 'password="correct horse battery\nloading model from /models/x.gguf\n'
+ out = redact_log_text(text)
+ assert "loading model from /models/x.gguf" in out
+ assert "correct horse battery" not in out
+
+
+def test_an_empty_line_is_safe():
+ assert redact_log_text("") == ""
+
+
+COOKIE_PROSE = [
+ "Cookie: disabled by the browser",
+ "Cookie: not sent because the origin is cross-site",
+ "Set-Cookie: cleared on logout",
+]
+
+
[email protected]("line", COOKIE_PROSE)
+def test_a_cookie_diagnosis_is_not_mistaken_for_a_cookie(line):
+ """The cookie rule takes the whole rest of the line, so prose longer than
+ the token-length shortcut was being masked. A line explaining why a cookie
+ was not sent is the diagnosis, not the secret."""
+ assert redact_log_text(line) == line
+
+
+ "line,secret",
+ [
+ ("Cookie: unsloth_ui_session=abc123def456xyz", "abc123def456xyz"),
+ ("Set-Cookie: session=abc123def456xyz; HttpOnly", "abc123def456xyz"),
+ # Headers are normally logged as a dict, so the value opens with a
+ # quote. Anchoring the pair test on the bare value never matched it.
+ ('headers={"Cookie": "session=abc123def456xyz"}', "abc123def456xyz"),
+ ("Cookie: 'session=abc123def456xyz'", "abc123def456xyz"),
+ ],
+)
+def test_a_real_cookie_pair_is_still_masked(line, secret):
+ assert secret not in redact_log_text(line)
+
+
+# A credential that ran to the next space swallowed the closing quote and every
+# field behind it, so the pane lost the status and request id it was opened for.
+ "line,expected",
+ [
+ (
+ '{"Authorization":"Bearer abcdef123456","x-request-id":"req-42"}',
+ '{"Authorization":"Bearer <redacted>","x-request-id":"req-42"}',
+ ),
+ ("authorization: 'Basic dXNlcjpwdw=='", "authorization: 'Basic <redacted>'"),
+ (
+ 'headers={"Cookie": "session=abc123def456xyz", "accept": "*/*"}',
+ 'headers={"Cookie": "<redacted>", "accept": "*/*"}',
+ ),
+ ],
+)
+def test_the_fields_after_a_masked_header_survive(line, expected):
+ assert redact_log_text(line) == expected
+
+
+# A colorized writer puts an escape between the key and its value. Every rule is
+# anchored on a word boundary or lookbehind, and the "m" ending "\x1b[36m" is a
+# word character, so the anchor stopped matching and the credential went out in
+# the clear -- and the pane strips escapes, so the reader saw a clean token.
+ANSI_SECRETS = [
+ # structlog's ConsoleRenderer verbatim: colors default on even off-terminal,
+ # so this is what lands in the session log.
+ (
+ "\x1b[36mapi_key\x1b[0m=\x1b[35msk_live_abcdef123456\x1b[0m",
+ "sk_live_abcdef123456",
+ ),
+ (
+ "\x1b[36mhf_token\x1b[0m=\x1b[35mhf_AbCdEfGhIjKlMnOpQrStUvWxYz012345\x1b[0m",
+ "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345",
+ ),
+ (
+ "\x1b[31mAuthorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg\x1b[0m",
+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg",
+ ),
+ # An escape INSIDE the token, and the 8-bit CSI form.
+ ("hf_\x1b[31mAbCdEfGhIjKlMnOpQrStUvWxYz012345\x1b[0m", "AbCdEfGhIjKlMnOpQrStUvWxYz012345"),
+ ("\x9b36mapi_key\x9b0m=abcdef123456", "abcdef123456"),
+]
+
+
[email protected]("line,secret", ANSI_SECRETS, ids = ["kv", "hf", "auth", "mid", "c1"])
+def test_a_colorized_credential_is_still_masked(line, secret):
+ assert secret not in redact_log_text(line)
+
+
+def test_ordinary_colorized_content_keeps_its_text():
+ """Stripping the control sequences must not eat the log line with them."""
+ out = redact_log_text("\x1b[32mmodel loaded\x1b[0m from /models/qwen3-4b.gguf")
+ assert out == "model loaded from /models/qwen3-4b.gguf"
+
+
+def test_a_hyperlink_escape_does_not_swallow_the_line():
+ """OSC is matched before the two-character Fe class, which covers "]" and
+ would otherwise consume only the introducer and leave the payload behind."""
+ out = redact_log_text("open \x1b]8;;https://example.com\x07docs\x1b]8;;\x07 for help")
+ assert out == "open docs for help"
+
+
+def test_studio_s3_secret_key_spellings_are_masked():
+ """models/training.py:60 takes secret_access_key, alias secretAccessKey.
+
+ Neither reaches the bare "secret" alternative: its trailing \\b cannot fire
+ before "_access" or "Access", and an AWS secret key has no prefix of its own
+ for a shape rule to catch, so both spellings went out in the clear.
+ """
+ secret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
+ for line in (
+ f"secret_access_key={secret}",
+ f'{{"secretAccessKey":"{secret}"}}',
+ f"secret-access-key: {secret}",
+ f"--secret-access-key {secret}",
+ f"aws_secret_access_key={secret}",
+ ):
+ masked = redact_log_text(line)
+ assert secret not in masked, line
+ assert REDACTED in masked, line
+
+
+def test_talking_about_the_s3_key_without_a_value_survives():
+ line = "secret_access_key is required when use_iam_role is false"
+ assert redact_log_text(line) == line
diff --git a/studio/backend/tests/test_debug_log_routes.py b/studio/backend/tests/test_debug_log_routes.py
new file mode 100644
index 00000000000..e375ca95a4e
--- /dev/null
+++ b/studio/backend/tests/test_debug_log_routes.py
@@ -0,0 +1,232 @@
+# 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 Settings > Logs endpoints. These are polled once a second while the
+tab is open, so "the file is not there yet" has to be a 200 with a status, not
+an error the UI flashes on every tick."""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+import routes.settings as settings_route
+
+
+def client():
+ app = FastAPI()
+ app.include_router(settings_route.router, prefix = "/api/settings")
+ app.dependency_overrides[settings_route.get_current_subject] = lambda: "admin"
+ app.dependency_overrides[settings_route._require_ui_session] = lambda: None
+ return TestClient(app, raise_server_exceptions = False)
+
+
+def _seed_server_log(body: str = "hello\n") -> Path:
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / f"server-20260813-120000-pid{os.getpid()}.log"
+ path.write_text(body, encoding = "utf-8")
+ return path
+
+
+def test_the_sources_list_names_the_running_session(client):
+ path = _seed_server_log()
+ body = client.get("/api/settings/debug/logs/sources").json()
+ assert body["default_source_id"]
+ assert any(s["label"] == path.name and s["is_current"] for s in body["sources"])
+ assert any(s["realpath"] == str(path.resolve()) for s in body["sources"])
+
+
+def test_the_first_read_returns_the_tail_and_a_cursor(client):
+ _seed_server_log("".join(f"line{i}\n" for i in range(20)))
+ body = client.get("/api/settings/debug/logs").json()
+ assert body["status"] == "ok"
+ assert body["lines"][-1] == "line19"
+ assert body["reset"] is True
+ assert body["cursor"]
+ assert body["realpath"]
+
+
+def test_a_second_read_returns_only_what_was_appended(client):
+ path = _seed_server_log("a\n")
+ cursor = client.get("/api/settings/debug/logs").json()["cursor"]
+ with open(path, "a", encoding = "utf-8") as handle:
+ handle.write("b\nc\n")
+ body = client.get("/api/settings/debug/logs", params = {"cursor": cursor}).json()
+ assert body["lines"] == ["b", "c"]
+ assert body["reset"] is False
+
+
+def test_an_idle_poll_is_a_200_with_no_lines(client):
+ _seed_server_log("a\n")
+ cursor = client.get("/api/settings/debug/logs").json()["cursor"]
+ response = client.get("/api/settings/debug/logs", params = {"cursor": cursor})
+ assert response.status_code == 200
+ assert response.json()["lines"] == []
+
+
+def test_an_unknown_source_is_a_404_so_the_picker_refetches(client):
+ _seed_server_log()
+ response = client.get("/api/settings/debug/logs", params = {"source": "server:" + "0" * 16})
+ assert response.status_code == 404
+
+
+ "hostile",
+ ["server:../../../../etc/passwd", "../../etc/passwd", "nosuch:abcdef0123456789"],
+)
+def test_a_crafted_source_id_never_reads_a_file(client, hostile):
+ _seed_server_log()
+ response = client.get("/api/settings/debug/logs", params = {"source": hostile})
+ assert response.status_code == 404
+ assert "root:" not in response.text
+
+
+def test_no_logs_at_all_reports_a_reason_rather_than_an_empty_view(client):
+ body = client.get("/api/settings/debug/logs").json()
+ assert body["status"] in {"missing", "disabled"}
+ assert body["reason"]
+
+
+def test_file_logging_turned_off_says_so(client, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_NO_FILE_LOG", "1")
+ body = client.get("/api/settings/debug/logs").json()
+ assert body["status"] == "disabled"
+ assert "UNSLOTH_STUDIO_NO_FILE_LOG" in body["reason"]
+
+
+def test_a_deleted_file_is_not_a_500(client):
+ path = _seed_server_log()
+ cursor = client.get("/api/settings/debug/logs").json()["cursor"]
+ path.unlink()
+ response = client.get("/api/settings/debug/logs", params = {"cursor": cursor})
+ assert response.status_code in (200, 404)
+ assert response.status_code != 500
+
+
+def test_credentials_in_the_log_never_reach_the_response(client):
+ _seed_server_log(
+ "loading with hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345\n"
+ 'auth: {"api_key":"abcdef123456"}\n'
+ "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg\n"
+ )
+ text = client.get("/api/settings/debug/logs").text
+ for secret in (
+ "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345",
+ "abcdef123456",
+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg",
+ ):
+ assert secret not in text
+
+
+def test_an_api_key_session_cannot_read_the_logs():
+ """Log lines and a local realpath are UI-operator material, not something a
+ remote API key should be able to pull."""
+ app = FastAPI()
+ app.include_router(settings_route.router, prefix = "/api/settings")
+ app.dependency_overrides[settings_route.get_current_subject] = lambda: "admin"
+ app.dependency_overrides[settings_route.authenticated_via_api_key] = lambda: True
+ api_client = TestClient(app, raise_server_exceptions = False)
+ _seed_server_log()
+ assert api_client.get("/api/settings/debug/logs").status_code == 403
+ assert api_client.get("/api/settings/debug/logs/sources").status_code == 403
+
+
+def test_the_endpoints_stay_out_of_the_access_log():
+ """Load bearing, not tidiness. These paths are polled while the tab is open
+ and they read the very file the access log writes to, so without the
+ suppression each poll appends a line the next poll reads back."""
+ from loggers.handlers import _is_quiet_success
+
+ # Behaviour, not membership: these go through _SELF_READ_PATHS rather than
+ # _QUIET_SUCCESS_PATHS because --verbose must not lift them.
+ # test_debug_log_self_feedback.py proves it over the real middleware.
+ assert _is_quiet_success("GET", "/api/settings/debug/logs", 200, False) is True
+ assert _is_quiet_success("GET", "/api/settings/debug/logs/sources", 200, False) is True
+
+
+def test_a_stale_session_is_flagged_when_file_logging_is_off(client, monkeypatch):
+ """An old file with logging now off must not read as a live view.
+
+ Reported on the PR: with UNSLOTH_STUDIO_NO_FILE_LOG=1 and a log left over
+ from a previous run, the read path answered a plain "ok" and the viewer sat
+ there looking live while nothing would ever be appended to it again.
+ """
+ _seed_server_log("a previous session\n")
+ monkeypatch.setenv("UNSLOTH_STUDIO_NO_FILE_LOG", "1")
+ body = client.get("/api/settings/debug/logs").json()
+ assert body["status"] == "ok"
+ assert body["lines"] == ["a previous session"]
+ assert body["file_logging_disabled"] is True
+
+
+def test_file_logging_disabled_is_false_on_an_ordinary_read(client):
+ _seed_server_log()
+ assert client.get("/api/settings/debug/logs").json()["file_logging_disabled"] is False
+
+
+def test_a_burst_larger_than_one_response_says_more_is_pending(client):
+ """The remainder is delivered, and the caller is told to come back for it."""
+ from utils import debug_log_reader
+
+ path = _seed_server_log()
+ cursor = client.get("/api/settings/debug/logs").json()["cursor"]
+ burst = debug_log_reader.MAX_LINES_PER_RESPONSE + 500
+ with path.open("a", encoding = "utf-8") as handle:
+ handle.write("".join(f"line {index}\n" for index in range(burst)))
+
+ first = client.get("/api/settings/debug/logs", params = {"cursor": cursor}).json()
+ assert len(first["lines"]) == debug_log_reader.MAX_LINES_PER_RESPONSE
+ assert first["more_pending"] is True
+
+ second = client.get("/api/settings/debug/logs", params = {"cursor": first["cursor"]}).json()
+ assert second["more_pending"] is False
+ assert first["lines"] + second["lines"] == [f"line {index}" for index in range(burst)]
+
+
+def _seed_llama_log(body: str = "llama runner line\n") -> Path:
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "llama-server"
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / "llama-1786000000.log"
+ path.write_text(body, encoding = "utf-8")
+ return path
+
+
+def _source_id(client, family: str) -> str:
+ body = client.get("/api/settings/debug/logs/sources").json()
+ return next(s["id"] for s in body["sources"] if s["family"] == family)
+
+
+def test_a_runner_log_is_not_called_stale_when_only_the_server_tee_is_off(client, monkeypatch):
+ """UNSLOTH_STUDIO_NO_FILE_LOG only skips run.py's tee.
+
+ The llama and diffusion runners and the desktop shell keep writing, so
+ treating the setting as global told a user watching a live llama-server log
+ that it would not update while the failure was still being appended to it.
+ """
+ _seed_llama_log()
+ monkeypatch.setenv("UNSLOTH_STUDIO_NO_FILE_LOG", "1")
+ source_id = _source_id(client, "llama-server")
+ body = client.get("/api/settings/debug/logs", params = {"source": source_id}).json()
+ assert body["status"] == "ok"
+ assert body["lines"] == ["llama runner line"]
+ assert body["file_logging_disabled"] is False
+
+
+def test_the_server_log_is_still_called_stale(client, monkeypatch):
+ _seed_server_log()
+ _seed_llama_log()
+ monkeypatch.setenv("UNSLOTH_STUDIO_NO_FILE_LOG", "1")
+ source_id = _source_id(client, "server")
+ body = client.get("/api/settings/debug/logs", params = {"source": source_id}).json()
+ assert body["file_logging_disabled"] is True
diff --git a/studio/backend/tests/test_debug_log_self_feedback.py b/studio/backend/tests/test_debug_log_self_feedback.py
new file mode 100644
index 00000000000..3fac576859e
--- /dev/null
+++ b/studio/backend/tests/test_debug_log_self_feedback.py
@@ -0,0 +1,127 @@
+# 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 log viewer reads the file the access logger writes to.
+
+That is a feedback loop, and it is the one failure mode this feature can create
+on its own: if a poll logs a line, the next poll reads that line back and logs
+another, and the log the user opened the viewer to read fills with the viewer.
+So this exercises the real middleware over a real file rather than asserting on
+the contents of a set.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+import pytest
+import structlog
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+import routes.settings as settings_route
+from loggers.handlers import LoggingMiddleware, _is_quiet_success
+
+POLL_PATHS = ("/api/settings/debug/logs", "/api/settings/debug/logs/sources")
+
+
+def session_log(tmp_path, monkeypatch):
+ """A studio home whose server log is also where structlog writes.
+
+ run.py tees stdout into that file, so a record the middleware emits lands in
+ the file the viewer is reading. Reproduced here by pointing the logger
+ factory straight at it.
+ """
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ directory = tmp_path / "logs" / "server"
+ directory.mkdir(parents = True)
+ path = directory / f"server-20260813-120000-pid{os.getpid()}.log"
+ handle = path.open("w", encoding = "utf-8", buffering = 1)
+
+ previous = structlog.get_config()
+ structlog.configure(
+ processors = [structlog.processors.JSONRenderer()],
+ logger_factory = structlog.PrintLoggerFactory(file = handle),
+ cache_logger_on_first_use = False,
+ )
+ monkeypatch.setattr("loggers.handlers.logger", structlog.get_logger("access"))
+ try:
+ yield path
+ finally:
+ structlog.configure(**previous)
+ handle.close()
+
+
+def client():
+ app = FastAPI()
+ app.include_router(settings_route.router, prefix = "/api/settings")
+ app.dependency_overrides[settings_route.get_current_subject] = lambda: "admin"
+ app.dependency_overrides[settings_route._require_ui_session] = lambda: None
+ app.add_middleware(LoggingMiddleware)
+ return TestClient(app, raise_server_exceptions = False)
+
+
+def test_polling_the_viewer_does_not_grow_the_log_it_reads(session_log, client):
+ session_log.write_text("a line that was there before the viewer opened\n")
+ before = session_log.stat().st_size
+
+ cursor = None
+ for _ in range(25):
+ params = {"cursor": cursor} if cursor else {}
+ cursor = client.get("/api/settings/debug/logs", params = params).json()["cursor"]
+ client.get("/api/settings/debug/logs/sources")
+
+ assert session_log.stat().st_size == before
+ assert "request_completed" not in session_log.read_text()
+
+
+def test_the_viewer_only_ever_returns_content_it_did_not_write(session_log, client):
+ session_log.write_text("first\n")
+ first = client.get("/api/settings/debug/logs").json()
+ assert first["lines"] == ["first"]
+ for _ in range(10):
+ body = client.get("/api/settings/debug/logs", params = {"cursor": first["cursor"]}).json()
+ # A line here would be the viewer reading its own access record.
+ assert body["lines"] == []
+
+
[email protected]("path", POLL_PATHS)
+def test_verbose_does_not_lift_the_suppression_for_these_two(path, monkeypatch):
+ """--verbose turning the suppressor off is fine everywhere else, because
+ everywhere else the extra lines only go to a file. These come back at the
+ reader, and --verbose is what someone debugging turns on."""
+ monkeypatch.setattr("loggers.handlers._VERBOSE_ACCESS_LOG", True)
+ assert _is_quiet_success("GET", path, 200, False) is True
+
+
+def test_verbose_still_lifts_it_for_an_ordinary_quiet_path(monkeypatch):
+ monkeypatch.setattr("loggers.handlers._VERBOSE_ACCESS_LOG", True)
+ assert _is_quiet_success("GET", "/api/hub/download-status", 200, False) is False
+
+
[email protected]("path", POLL_PATHS)
+def test_a_failure_on_the_viewer_endpoints_still_logs(path):
+ # A poll carries no signal; a 404 or a 500 does.
+ assert _is_quiet_success("GET", path, 404, False) is False
+ assert _is_quiet_success("GET", path, 500, False) is False
+ assert _is_quiet_success("POST", path, 200, False) is False
+
+
+def test_the_suppression_is_an_exact_path_match(session_log, client):
+ """Neither a prefix nor a suffix of these paths may be silenced by them."""
+ for path in ("/api/settings", "/api/settings/debug", "/api/settings/debug/logs/x"):
+ assert _is_quiet_success("GET", path, 200, False) is False
+
+ # A neighbouring settings GET still logs, so the suppression cannot have
+ # widened to the router.
+ before = session_log.stat().st_size
+ assert client.get("/api/settings/upload-limit").status_code == 200
+ assert "/api/settings/upload-limit" in session_log.read_text()[before:]
diff --git a/studio/backend/tests/test_debug_log_sources.py b/studio/backend/tests/test_debug_log_sources.py
new file mode 100644
index 00000000000..2dd359c30c4
--- /dev/null
+++ b/studio/backend/tests/test_debug_log_sources.py
@@ -0,0 +1,332 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Discovery decides what the log viewer is allowed to open, so it is also the
+whole path-traversal defence. The conftest _isolate_studio_home fixture already
+points UNSLOTH_STUDIO_HOME at a tmp dir."""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from utils import debug_log_sources
+
+
+def _home() -> Path:
+ return Path(os.environ["UNSLOTH_STUDIO_HOME"])
+
+
+def _seed(
+ family_dir: str,
+ name: str,
+ body: str = "hello\n",
+) -> Path:
+ directory = _home() / "logs" / family_dir
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / name
+ path.write_text(body, encoding = "utf-8")
+ return path
+
+
+def test_all_three_families_are_found():
+ _seed("server", f"server-20260813-101010-pid{os.getpid()}.log")
+ _seed("llama-server", "llama-1765000000-port-8080.log")
+ _seed("diffusion-server", "diffusion-1765000000-port-8081.log")
+ families = {source.family for source in debug_log_sources.list_sources()}
+ assert families == {"server", "llama-server", "diffusion-server"}
+
+
+def test_ids_are_stable_across_calls_and_unique_per_file():
+ _seed("llama-server", "llama-1765000001-port-8080.log")
+ _seed("llama-server", "llama-1765000002-port-8081.log")
+ first = {s.label: s.id for s in debug_log_sources.list_sources()}
+ second = {s.label: s.id for s in debug_log_sources.list_sources()}
+ assert first == second
+ assert len(set(first.values())) == len(first)
+
+
+def test_an_id_resolves_back_to_the_file_it_named():
+ path = _seed("llama-server", "llama-1765000003-port-8080.log")
+ source = next(s for s in debug_log_sources.list_sources() if s.label == path.name)
+ assert debug_log_sources.resolve_source_id(source.id) == Path(os.path.realpath(path))
+
+
+ "hostile",
+ [
+ "server:../../../../etc/passwd",
+ "../../etc/passwd",
+ "server:" + "0" * 16,
+ "nosuchfamily:abcdef0123456789",
+ "server",
+ "",
+ ":",
+ ],
+)
+def test_a_hostile_source_id_resolves_to_nothing(hostile):
+ assert debug_log_sources.resolve_source_id(hostile) is None
+
+
+def test_a_symlink_out_of_the_log_dir_is_not_readable(tmp_path):
+ """The one way an attacker could turn this into an arbitrary file reader."""
+ secret = tmp_path / "id_rsa"
+ secret.write_text("PRIVATE KEY\n")
+ directory = _home() / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ link = directory / "server-20260813-999999-pid1.log"
+ try:
+ link.symlink_to(secret)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks unavailable")
+ labels = [s.label for s in debug_log_sources.list_sources()]
+ assert link.name not in labels
+
+
+def test_a_missing_family_directory_is_not_an_error():
+ _seed("server", f"server-20260813-101011-pid{os.getpid()}.log")
+ sources = debug_log_sources.list_sources()
+ assert all(source.family != "diffusion-server" for source in sources)
+
+
+def test_another_installations_logs_are_not_offered(monkeypatch, tmp_path):
+ """With UNSLOTH_STUDIO_HOME set, the runners write under it, so the legacy
+ ~/.unsloth/studio belongs to a different install and must stay invisible."""
+ legacy = tmp_path / "legacy"
+ (legacy / ".unsloth" / "studio" / "logs" / "diffusion-server").mkdir(parents = True)
+ (
+ legacy / ".unsloth" / "studio" / "logs" / "diffusion-server" / "diffusion-1-port-1.log"
+ ).write_text("someone else's log\n", encoding = "utf-8")
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: legacy))
+
+ _seed("server", f"server-20260813-101014-pid{os.getpid()}.log")
+ labels = [source.label for source in debug_log_sources.list_sources()]
+ assert "diffusion-1-port-1.log" not in labels
+
+
+def test_the_running_session_is_marked_current():
+ path = _seed("server", f"server-20260813-101012-pid{os.getpid()}.log")
+ source = next(s for s in debug_log_sources.list_sources() if s.label == path.name)
+ assert source.is_current is True
+
+
+def test_a_retained_log_whose_pid_merely_starts_with_ours_is_not_current():
+ """Retention keeps the newest 20 session logs, so a file from pid 12345 can
+ still be sitting there while we are pid 1234. A substring test called both
+ of them the running session and could hand the picker the wrong default."""
+ ours = _seed("server", f"server-20260813-101012-pid{os.getpid()}.log")
+ other = _seed("server", f"server-20260101-090000-pid{os.getpid()}9.log")
+ current = {s.label: s.is_current for s in debug_log_sources.list_sources()}
+ assert current[ours.name] is True
+ assert current[other.name] is False
+
+
+def test_only_the_newest_files_per_family_are_offered():
+ for i in range(debug_log_sources.MAX_SOURCES_PER_FAMILY + 4):
+ path = _seed("llama-server", f"llama-17650001{i:02d}-port-8080.log")
+ os.utime(path, (1_765_000_000 + i, 1_765_000_000 + i))
+ llama = [s for s in debug_log_sources.list_sources() if s.family == "llama-server"]
+ assert len(llama) == debug_log_sources.MAX_SOURCES_PER_FAMILY
+ assert llama[0].modified_at >= llama[-1].modified_at
+
+
+def test_a_runtime_log_under_the_other_root_is_still_found(monkeypatch, tmp_path):
+ """studio_root() infers a root from the installer venv and the llama runner
+ does not, so on such an install the two disagree. Scanning one root only
+ would lose exactly the logs a failed model load writes."""
+ other_home = tmp_path / "legacy-home"
+ (other_home / "logs" / "llama-server").mkdir(parents = True)
+ stray = other_home / "logs" / "llama-server" / "llama-1765009999-port-9099.log"
+ stray.write_text("child runtime output\n", encoding = "utf-8")
+
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(
+ debug_log_sources,
+ "candidate_roots",
+ lambda: [Path(os.environ["UNSLOTH_STUDIO_HOME"]), other_home],
+ )
+ labels = [s.label for s in debug_log_sources.list_sources()]
+ assert stray.name in labels
+
+
+def test_the_default_source_prefers_the_running_session():
+ _seed("llama-server", "llama-1765000500-port-8080.log")
+ path = _seed("server", f"server-20260813-101013-pid{os.getpid()}.log")
+ default = debug_log_sources.default_source_id()
+ assert default is not None
+ assert debug_log_sources.resolve_source_id(default) == Path(os.path.realpath(path))
+
+
+def test_containment_survives_a_windows_extended_length_prefix(monkeypatch):
+ """ntpath.realpath decides per call whether to keep the \\\\?\\ prefix, so
+ the directory and the file in it can come back spelled differently. pathlib
+ reads that as two different drives, and the whole family disappears with no
+ error anywhere."""
+ import ntpath
+
+ monkeypatch.setattr(os.path, "normcase", ntpath.normcase)
+ monkeypatch.setattr(os, "sep", "\\")
+
+ directory = "C:\\Users\\dan\\.unsloth\\studio\\logs\\server"
+ entry = "\\\\?\\C:\\Users\\dan\\.unsloth\\studio\\logs\\server\\server-1-pid2.log"
+ assert debug_log_sources._is_inside(entry, directory) is True
+ # The protection it exists for must still hold under the same spelling.
+ assert debug_log_sources._is_inside("\\\\?\\C:\\Users\\dan\\.ssh\\id_rsa", directory) is False
+ assert debug_log_sources._is_inside("C:\\Users\\dan\\.ssh\\id_rsa", directory) is False
+ # A sibling directory whose name merely starts with ours is not inside it.
+ assert debug_log_sources._is_inside(directory + "-old\\x.log", directory) is False
+
+
+def test_a_case_insensitive_volume_does_not_list_a_file_twice(monkeypatch):
+ """On APFS or NTFS a home reached as /Users/Bob and as /Users/bob is one
+ directory. Case-sensitive dedup offered every log twice, under two ids."""
+ import ntpath
+
+ monkeypatch.setattr(os.path, "normcase", ntpath.normcase)
+ lower = "c:\\users\\dan\\studio\\logs\\server\\server-1-pid2.log"
+ upper = "C:\\Users\\Dan\\Studio\\Logs\\Server\\Server-1-pid2.log"
+ assert debug_log_sources._identity(lower) == debug_log_sources._identity(upper)
+
+
+def test_posix_identity_stays_case_sensitive():
+ """The same fold on Linux would merge two genuinely different files."""
+ if os.name != "posix":
+ pytest.skip("posix only")
+ assert debug_log_sources._identity("/a/Server.log") != debug_log_sources._identity(
+ "/a/server.log"
+ )
+
+
+DESKTOP_FIXTURES = [
+ ("desktop-backend", "logs", "backend-backend-1786344247254-2-s01.log"),
+ ("desktop-install", "logs", "install-1786344247254-2-s01.log"),
+ ("desktop-update", "logs", "update-1786344247254-2-s01.log"),
+ ("desktop-repair", "logs", "repair-repair-1-2-update-update-3-s01.log"),
+ ("desktop-shell", "", "tauri.log"),
+ ("desktop-shell", "", "tauri.log.1"),
+]
+
+
+ "family,subdir,name", DESKTOP_FIXTURES, ids = [f[2] for f in DESKTOP_FIXTURES]
+)
+def test_the_desktop_shell_logs_are_offered(family, subdir, name):
+ """The Tauri shell writes these beside the Python logs, and backend-*.log is
+ the ONLY record when the backend dies before its own file logging starts.
+ Without them a user whose app failed to start is told nothing was logged."""
+ directory = _home() / subdir if subdir else _home()
+ directory.mkdir(parents = True, exist_ok = True)
+ (directory / name).write_text("desktop output\n", encoding = "utf-8")
+ sources = debug_log_sources.list_sources()
+ assert any(
+ s.label == name and s.family == family for s in sources
+ ), f"{name} not offered; got {[(s.family, s.label) for s in sources]}"
+
+
+def test_a_desktop_log_resolves_and_reads_back():
+ directory = _home() / "logs"
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / "backend-backend-1786344247254-2-s01.log"
+ path.write_text("the backend died before it could open its own log\n", encoding = "utf-8")
+ source = next(s for s in debug_log_sources.list_sources() if s.label == path.name)
+ assert debug_log_sources.resolve_source_id(source.id) == Path(os.path.realpath(path))
+
+
+def test_a_python_log_is_not_claimed_by_a_desktop_family():
+ """logs/ now has both flat desktop files and the per-family subdirectories,
+ so the globs must not overlap."""
+ _seed("server", f"server-20260813-101015-pid{os.getpid()}.log")
+ (_home() / "logs").mkdir(parents = True, exist_ok = True)
+ (_home() / "logs" / "backend-backend-1-2-s01.log").write_text("x\n", encoding = "utf-8")
+ by_family = {}
+ for source in debug_log_sources.list_sources():
+ by_family.setdefault(source.family, []).append(source.label)
+ assert all(label.startswith("server-") for label in by_family.get("server", []))
+ assert all(label.startswith("backend-") for label in by_family.get("desktop-backend", []))
+
+
+def test_a_huge_directory_does_not_stat_every_file(monkeypatch):
+ """logs/llama-server is never pruned and reaches five figures on a real
+ install, while this endpoint is polled once a second."""
+ directory = _home() / "logs" / "llama-server"
+ directory.mkdir(parents = True, exist_ok = True)
+ for i in range(400):
+ (directory / f"llama-17660000{i:03d}-port-8080.log").write_text("x\n", encoding = "utf-8")
+
+ real_stat = Path.stat
+ calls = {"n": 0}
+
+ def _counting_stat(self, *args, **kwargs):
+ calls["n"] += 1
+ return real_stat(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "stat", _counting_stat)
+ files = debug_log_sources._family_files("llama-server")
+ assert len(files) == debug_log_sources.MAX_SOURCES_PER_FAMILY
+ # Cost must track the presort slice (MAX * 3 candidates, an is_file plus a
+ # stat each), not the 400 files present.
+ ceiling = debug_log_sources.MAX_SOURCES_PER_FAMILY * 3 * 2 + 8
+ assert (
+ calls["n"] <= ceiling
+ ), f"stat called {calls['n']} times for 400 files; the presort is not working"
+ assert calls["n"] < 400, "cost still scales with the directory"
+
+
+def test_a_literal_tilde_home_is_scanned_both_ways(tmp_path, monkeypatch):
+ """The writer and the reader disagreed about the tilde.
+
+ _swa_cache_path builds Path(home) raw, so a value passed literally (systemd
+ EnvironmentFile, dotenv) makes the runners write into a directory NAMED
+ "~", while expanduser sent discovery to the real home. Scanning one of the
+ two lost the llama logs the viewer exists to reach.
+ """
+ monkeypatch.chdir(tmp_path)
+ literal = tmp_path / "~" / "studio"
+ (literal / "logs" / "llama-server").mkdir(parents = True)
+ (literal / "logs" / "llama-server" / "llama-1786000000.log").write_text("x", encoding = "utf-8")
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", "~/studio")
+
+ labels = [source.label for source in debug_log_sources.list_sources()]
+ assert "llama-1786000000.log" in labels
+
+
+def test_no_live_session_defaults_to_the_newest_log_not_an_old_server_one(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ server_dir = tmp_path / "logs" / "server"
+ llama_dir = tmp_path / "logs" / "llama-server"
+ server_dir.mkdir(parents = True)
+ llama_dir.mkdir(parents = True)
+ # A retained log from a previous run: a pid that is not ours.
+ old = server_dir / "server-20260101-000000-pid1.log"
+ old.write_text("previous run\n", encoding = "utf-8")
+ newest = llama_dir / "llama-1786000000.log"
+ newest.write_text("the failure\n", encoding = "utf-8")
+ os.utime(old, (1_000_000, 1_000_000))
+ os.utime(newest, (2_000_000, 2_000_000))
+
+ chosen = debug_log_sources.resolve_source_id(debug_log_sources.default_source_id())
+ assert chosen == newest
+
+
+def test_a_live_server_session_still_wins(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ server_dir = tmp_path / "logs" / "server"
+ llama_dir = tmp_path / "logs" / "llama-server"
+ server_dir.mkdir(parents = True)
+ llama_dir.mkdir(parents = True)
+ current = server_dir / f"server-20260101-000000-pid{os.getpid()}.log"
+ current.write_text("this session\n", encoding = "utf-8")
+ newer = llama_dir / "llama-1786000000.log"
+ newer.write_text("a runner\n", encoding = "utf-8")
+ os.utime(current, (1_000_000, 1_000_000))
+ os.utime(newer, (2_000_000, 2_000_000))
+
+ chosen = debug_log_sources.resolve_source_id(debug_log_sources.default_source_id())
+ assert chosen == current
diff --git a/studio/backend/tests/test_remote_access_settings.py b/studio/backend/tests/test_remote_access_settings.py
index 9808261054d..b8255448cbd 100644
--- a/studio/backend/tests/test_remote_access_settings.py
+++ b/studio/backend/tests/test_remote_access_settings.py
@@ -3,6 +3,7 @@
from __future__ import annotations
+import ast
import asyncio
import sys
import threading
@@ -268,8 +269,23 @@ def test_management_rejects_api_keys():
routes._require_ui_session(True)
assert exc.value.status_code == 403
assert remote_access.remote_access_status(_state())["streaming_supported"] is True
- source = Path(routes.__file__).read_text(encoding = "utf-8")
- assert source.count("_ui_session: None = Depends(_require_ui_session)") == 4
+ # Every /remote-access handler must carry the gate. Scoped to those routes
+ # because a file-wide count breaks whenever an unrelated endpoint adopts
+ # _require_ui_session, as the Settings > Logs log endpoints did.
+ tree = ast.parse(Path(routes.__file__).read_text(encoding = "utf-8"))
+ gated = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ routed = [ast.unparse(d) for d in node.decorator_list if "router." in ast.unparse(d)]
+ if not any("'/remote-access" in d for d in routed):
+ continue
+ args = node.args.args + node.args.kwonlyargs
+ gated[node.name] = any(a.arg == "_ui_session" for a in args)
+ assert len(gated) == 4, f"expected 4 remote-access handlers, found {sorted(gated)}"
+ assert all(
+ gated.values()
+ ), f"ungated remote-access handlers: {sorted(k for k, v in gated.items() if not v)}"
def test_remote_stop_returns_terminal_state(monkeypatch):
diff --git a/studio/backend/utils/debug_log_reader.py b/studio/backend/utils/debug_log_reader.py
new file mode 100644
index 00000000000..b2eafad83a5
--- /dev/null
+++ b/studio/backend/utils/debug_log_reader.py
@@ -0,0 +1,228 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Bounded reads of a log file for the Settings > Logs viewer.
+
+The active session log is never rotated and only pruned at startup (run.py
+retains the newest 20 files), so it can be many GB by the time someone opens
+this. Everything here seeks from the end and reads a bounded window, so cost
+does not scale with file size.
+
+read_tail and read_since return REDACTED lines. The raw reader is private so a
+later caller cannot forget.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Optional
+
+from utils.log_redaction import redact_log_text
+
+BLOCK_BYTES = 65_536
+DEFAULT_TAIL_LINES = 1_000
+MAX_TAIL_LINES = 2_000 # == MAX_LINES_PER_RESPONSE: a larger ?lines= was silently capped
+# /api is not gzipped (GZipMiddleware is scoped to the assets sub-app), so this
+# is what actually goes on the wire on the first paint.
+MAX_TAIL_BYTES = 1_048_576
+MAX_APPEND_BYTES = 524_288
+MAX_LINE_BYTES = 32_768
+MAX_LINES_PER_RESPONSE = 2_000
+
+_CURSOR_PREFIX = "c1."
+
+
+@dataclass
+class ReadResult:
+ lines: list[str] = field(default_factory = list)
+ cursor: Optional[str] = None
+ reset: bool = False
+ reset_reason: Optional[str] = None
+ dropped_bytes: int = 0
+ truncated_head: bool = False
+ more_pending: bool = False
+ size_bytes: int = 0
+
+
+def _file_key(stat: os.stat_result, name: str) -> str:
+ # Identity only: nothing here may change on append. st_ctime_ns does (on
+ # Linux it is the metadata change time), which made every poll look like a
+ # rotation and resend the whole tail. st_ino can be 0 on some Windows
+ # filesystems, so name and device carry the identity there; truncation is
+ # caught separately by the offset > size check.
+ return f"{name}|{stat.st_dev}|{stat.st_ino}"
+
+
+def encode_cursor(key: str, offset: int) -> str:
+ raw = json.dumps({"k": key, "o": int(offset)}, separators = (",", ":")).encode("utf-8")
+ return _CURSOR_PREFIX + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def decode_cursor(cursor: Optional[str]) -> Optional[tuple[str, int]]:
+ """None for anything unusable: a foreign cursor is answered with a fresh
+ tail, never an error, so a poll loop cannot flash failures."""
+ if not cursor or not isinstance(cursor, str) or not cursor.startswith(_CURSOR_PREFIX):
+ return None
+ body = cursor[len(_CURSOR_PREFIX) :]
+ try:
+ padded = body + "=" * (-len(body) % 4)
+ payload = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
+ key = payload["k"]
+ offset = int(payload["o"])
+ except Exception:
+ return None
+ if not isinstance(key, str) or offset < 0:
+ return None
+ return key, offset
+
+
+def _split_lines(data: bytes, *, drop_partial_head: bool) -> tuple[list[str], bool]:
+ truncated_head = False
+ if drop_partial_head:
+ first = data.find(b"\n")
+ remainder = b"" if first == -1 else data[first + 1 :]
+ if not remainder:
+ # The whole window sits inside ONE record (no line break, or only
+ # the terminator at the end), so dropping the partial head left
+ # nothing: a record bigger than the window (native dump, \r-only
+ # progress run, giant JSON line) rendered an EMPTY pane on a
+ # megabyte log while the cursor still advanced past it. Keep the
+ # record's tail, which is the end everyone is reading for.
+ body = data if first == -1 else data[:first]
+ remainder = body[-MAX_LINE_BYTES:]
+ data = remainder
+ truncated_head = True
+ text = data.decode("utf-8", errors = "replace")
+ raw = text.split("\n")
+ if raw and raw[-1] == "":
+ raw.pop()
+ lines: list[str] = []
+ for line in raw:
+ line = line.rstrip("\r")
+ # An enormous line is split rather than dropped, so nothing is lost.
+ while len(line) > MAX_LINE_BYTES:
+ lines.append(line[:MAX_LINE_BYTES])
+ line = line[MAX_LINE_BYTES:]
+ lines.append(line)
+ return lines, truncated_head
+
+
+def _redact(lines: list[str]) -> list[str]:
+ return [redact_log_text(line) for line in lines]
+
+
+def read_tail(path: Path, max_lines: int = DEFAULT_TAIL_LINES) -> ReadResult:
+ max_lines = max(1, min(int(max_lines), MAX_TAIL_LINES))
+ stat = path.stat()
+ size = stat.st_size
+ result = ReadResult(size_bytes = size)
+ result.cursor = encode_cursor(_file_key(stat, path.name), size)
+ result.reset = True
+ if size == 0:
+ return result
+
+ chunks: list[bytes] = []
+ pos = size
+ newlines = 0
+ scanned = 0
+ with open(path, "rb") as handle:
+ while pos > 0 and newlines <= max_lines and scanned < MAX_TAIL_BYTES:
+ step = min(BLOCK_BYTES, pos, MAX_TAIL_BYTES - scanned)
+ pos -= step
+ handle.seek(pos)
+ block = handle.read(step)
+ if not block:
+ break
+ chunks.insert(0, block)
+ newlines += block.count(b"\n")
+ scanned += len(block)
+
+ data = b"".join(chunks)
+ lines, truncated = _split_lines(data, drop_partial_head = pos > 0)
+ result.truncated_head = truncated
+ if len(lines) > max_lines:
+ lines = lines[-max_lines:]
+ result.truncated_head = True
+ result.lines = _redact(lines[-MAX_LINES_PER_RESPONSE:])
+ return result
+
+
+def read_since(
+ path: Path,
+ cursor: Optional[str],
+ max_lines: int = DEFAULT_TAIL_LINES,
+) -> ReadResult:
+ """Appended lines only, or a fresh tail when the cursor cannot apply."""
+ decoded = decode_cursor(cursor)
+ if decoded is None:
+ result = read_tail(path, max_lines)
+ result.reset_reason = "initial" if not cursor else "cursor_stale"
+ return result
+
+ key, offset = decoded
+ stat = path.stat()
+ current_key = _file_key(stat, path.name)
+ size = stat.st_size
+
+ if current_key != key:
+ result = read_tail(path, max_lines)
+ result.reset_reason = "rotated"
+ return result
+ if offset > size:
+ # Reopened in "w" mode, or truncated underneath us.
+ result = read_tail(path, max_lines)
+ result.reset_reason = "truncated"
+ return result
+
+ result = ReadResult(size_bytes = size)
+ if offset == size:
+ result.cursor = encode_cursor(current_key, offset)
+ return result
+
+ start = offset
+ pending = size - offset
+ if pending > MAX_APPEND_BYTES:
+ start = size - MAX_APPEND_BYTES
+ result.dropped_bytes = start - offset
+ with open(path, "rb") as handle:
+ handle.seek(start)
+ data = handle.read(size - start)
+
+ # Stop at the last newline and leave the cursor before the partial line, so a
+ # half-written record is never emitted twice. An unterminated remainder past
+ # a line's worth is flushed, else a writer that never emits a newline stalls
+ # the viewer for good.
+ last_newline = data.rfind(b"\n")
+ if last_newline == -1:
+ if len(data) < MAX_LINE_BYTES:
+ result.cursor = encode_cursor(current_key, start)
+ return result
+ consumed = len(data)
+ body = data
+ else:
+ consumed = last_newline + 1
+ body = data[:consumed]
+
+ # Cap by BYTES, before decoding, so the cursor stops where the response
+ # stops. Slicing decoded lines instead threw away the oldest of a burst while
+ # advancing the cursor past them, so a model load logging more than
+ # MAX_LINES_PER_RESPONSE lines between polls lost the head of its own failure
+ # and still reported dropped_bytes = 0. The remainder now arrives next poll.
+ newline_count = body.count(b"\n")
+ if newline_count > MAX_LINES_PER_RESPONSE:
+ cut = -1
+ for _ in range(MAX_LINES_PER_RESPONSE):
+ cut = body.find(b"\n", cut + 1)
+ consumed = cut + 1
+ body = body[:consumed]
+ result.more_pending = True
+
+ lines, truncated = _split_lines(body, drop_partial_head = result.dropped_bytes > 0)
+ result.truncated_head = truncated
+ result.lines = _redact(lines)
+ result.cursor = encode_cursor(current_key, start + consumed)
+ return result
diff --git a/studio/backend/utils/debug_log_sources.py b/studio/backend/utils/debug_log_sources.py
new file mode 100644
index 00000000000..9d0261d3be6
--- /dev/null
+++ b/studio/backend/utils/debug_log_sources.py
@@ -0,0 +1,285 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Find the log files the Settings > Logs viewer is allowed to read.
+
+The client never names a path. It gets opaque ids from `list_sources` and hands
+one back; `resolve_source_id` re-runs this same walk and matches the digest, so
+the only paths that can ever reach open() are ones this module produced.
+"""
+
+from __future__ import annotations
+
+import fnmatch
+import hashlib
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+# (subdirectory under a studio home, filename glob).
+#
+# Python writers: run.py:_setup_server_disk_logging and the llama / diffusion
+# runners in core/inference/llama_cpp.py.
+#
+# The desktop families are written by the Tauri shell
+# (src-tauri/src/diagnostics/phase_log.rs) into the logs directory ITSELF, not a
+# subdirectory. backend-* is the shell's capture of the backend's stdout and the
+# only record that exists when the backend dies BEFORE
+# _setup_server_disk_logging runs; without it a user whose app failed to start
+# would be told nothing was logged. tauri.log sits at the home root and rotates
+# to tauri.log.1.
+FAMILIES: dict[str, tuple[str, str]] = {
+ "server": ("logs/server", "server-*.log"),
+ "llama-server": ("logs/llama-server", "llama-*.log"),
+ "diffusion-server": ("logs/diffusion-server", "diffusion-*.log"),
+ "desktop-backend": ("logs", "backend-*.log"),
+ "desktop-install": ("logs", "install-*.log"),
+ "desktop-update": ("logs", "update-*.log"),
+ "desktop-repair": ("logs", "repair-*.log"),
+ "desktop-shell": ("", "tauri.log*"),
+}
+
+# Per family, so a busy host cannot make the picker unusable. Several, not one:
+# the llama runner writes a file per load ATTEMPT, so after a retry the
+# interesting one is often the second to last.
+MAX_SOURCES_PER_FAMILY = 10
+
+_DIGEST_CHARS = 16
+
+
+@dataclass(frozen = True)
+class LogSource:
+ id: str
+ family: str
+ label: str
+ realpath: str
+ size_bytes: int
+ modified_at: float
+ is_current: bool
+
+
+def candidate_roots() -> list[Path]:
+ """Every studio home a log file might be under, most specific first.
+
+ studio_root() infers a root from the installer venv; the llama and diffusion
+ runners resolve their own base (llama_cpp.py:_swa_cache_path) and do NOT do
+ that inference. On a venv install with no env var set the two disagree, and
+ scanning only one of them loses exactly the runtime logs a user chasing a
+ failed model load came here for.
+ """
+ roots: list[Path] = []
+
+ def _add(path: Optional[Path]) -> None:
+ if path is None:
+ return
+ try:
+ resolved = Path(os.path.realpath(path))
+ except (OSError, ValueError):
+ return
+ # Folded, so a home differing from the inferred root only in case is not
+ # scanned twice on a case-insensitive volume.
+ if not any(_identity(resolved) == _identity(known) for known in roots):
+ roots.append(resolved)
+
+ try:
+ from utils.paths import studio_root
+ _add(studio_root())
+ except Exception:
+ pass
+
+ # Mirror _swa_cache_path exactly: env override if set, else the legacy home,
+ # never both. Both would pull a DIFFERENT installation's logs into this one.
+ env_home = (
+ os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or ""
+ ).strip()
+ if env_home:
+ # Both spellings, because the writer and the reader disagree about the
+ # tilde: _swa_cache_path builds Path(home) raw, so a value passed
+ # literally (a systemd EnvironmentFile or a dotenv line never runs the
+ # shell's expansion) makes the runners write to a directory NAMED "~",
+ # while expanduser sends discovery to the real home. Scanning one of
+ # them loses the llama and diffusion logs this viewer exists to reach.
+ # Not the earlier env-versus-legacy case: these are two spellings of one
+ # value, so neither can be another installation's home.
+ for spelling in (Path(env_home).expanduser(), Path(env_home)):
+ try:
+ _add(spelling)
+ except (OSError, ValueError):
+ pass
+ else:
+ try:
+ _add(Path.home() / ".unsloth" / "studio")
+ except (OSError, RuntimeError):
+ pass
+
+ return roots
+
+
+def _identity(path) -> str:
+ """One comparable spelling of a path, for containment and for dedup.
+
+ Two jobs, both platform quirks:
+
+ os.path.realpath is called separately for the directory and for each entry,
+ and on Windows ntpath.realpath decides PER CALL whether to keep the
+ \\\\?\\ extended-length prefix (it strips it only if the short form still
+ resolves). With a deep studio home on a host without long-path support the
+ directory can come back as C:\\... while the file comes back as
+ \\\\?\\C:\\..., which pathlib reads as two different DRIVES: containment then
+ fails and the whole family is silently dropped.
+
+ normcase folds case on Windows and is the identity on POSIX, so a
+ case-insensitive volume stops yielding the same file twice under two
+ spellings while Linux keeps its case-sensitive comparison unchanged.
+ """
+ text = os.path.normcase(str(path))
+ for prefix in ("\\\\?\\unc\\", "\\\\?\\UNC\\", "\\\\?\\"):
+ if text.startswith(prefix):
+ text = ("\\\\" if prefix.lower().endswith("unc\\") else "") + text[len(prefix) :]
+ break
+ return text
+
+
+def _is_inside(real, real_dir) -> bool:
+ inner, outer = _identity(real), _identity(real_dir)
+ return inner == outer or inner.startswith(outer.rstrip(os.sep) + os.sep)
+
+
+def _digest(realpath: str) -> str:
+ return hashlib.sha256(realpath.encode("utf-8", "surrogateescape")).hexdigest()[:_DIGEST_CHARS]
+
+
+def _family_files(family: str) -> list[Path]:
+ """Real, contained, regular files for one family, newest first."""
+ subdir, pattern = FAMILIES[family]
+ found: dict[str, tuple[Path, float]] = {}
+ for root in candidate_roots():
+ directory = root / subdir
+ try:
+ if not directory.is_dir():
+ continue
+ real_dir = Path(os.path.realpath(directory))
+ except OSError:
+ continue
+ try:
+ entries = list(directory.glob(pattern))
+ except OSError:
+ continue
+ # Nothing prunes logs/llama-server and one file is written per load
+ # ATTEMPT, so a real install reaches five figures (this host: 11,794).
+ # realpath + stat on every one cost ~356ms, at a 1 Hz poll. Every
+ # family's filename embeds its creation time (server-YYYYmmdd-HHMMSS,
+ # llama-<epoch>, diffusion-<epoch>, desktop ms epoch), so name order
+ # tracks time order and this presort leaves a handful to interrogate.
+ # Survivors are still ordered by real mtime below, and the slice is wide
+ # enough to keep a file whose mtime moved after it was written.
+ entries.sort(key = lambda entry: entry.name, reverse = True)
+ entries = entries[: MAX_SOURCES_PER_FAMILY * 3]
+ for entry in entries:
+ try:
+ real = Path(os.path.realpath(entry))
+ # The TARGET must stay inside: a symlink dropped into the log
+ # directory must not become a reader for ~/.ssh/id_rsa.
+ if not _is_inside(real, real_dir):
+ continue
+ if not real.is_file():
+ continue
+ if not fnmatch.fnmatch(real.name, pattern):
+ continue
+ stat = real.stat()
+ except (OSError, ValueError):
+ continue
+ # Keyed on the folded spelling so a case-insensitive volume cannot
+ # list the same file twice; the first spelling seen is kept, so the
+ # id digest stays over the real path.
+ found.setdefault(_identity(real), (real, stat.st_mtime))
+ ordered = sorted(found.values(), key = lambda item: item[1], reverse = True)
+ return [path for path, _ in ordered[:MAX_SOURCES_PER_FAMILY]]
+
+
+def _is_current(family: str, path: Path, newest: Optional[Path]) -> bool:
+ if family == "server":
+ # uvicorn runs single process here, so our own pid is in the active
+ # session's filename: an exact match, not a newest-file guess. Anchored
+ # on the suffix because run.py writes server-{stamp}-pid{pid}, and a
+ # substring test for "pid1234" also matches a retained ...-pid12345.log.
+ return path.name.endswith(f"-pid{os.getpid()}.log")
+ return newest is not None and path == newest
+
+
+def list_sources() -> list[LogSource]:
+ sources: list[LogSource] = []
+ for family in FAMILIES:
+ files = _family_files(family)
+ newest = files[0] if files else None
+ for path in files:
+ try:
+ stat = path.stat()
+ except OSError:
+ continue
+ real = str(path)
+ sources.append(
+ LogSource(
+ id = f"{family}:{_digest(real)}",
+ family = family,
+ label = path.name,
+ realpath = real,
+ size_bytes = stat.st_size,
+ modified_at = stat.st_mtime,
+ is_current = _is_current(family, path, newest),
+ )
+ )
+ return sources
+
+
+def resolve_source_id(source_id: str) -> Optional[Path]:
+ """Opaque id back to a path, by rebuilding the allowlist and matching.
+
+ Deliberately not a decode: nothing the caller sends is ever turned into a
+ path, so there is no string that can traverse anywhere.
+ """
+ if not isinstance(source_id, str):
+ return None
+ family, sep, digest = source_id.partition(":")
+ if not sep or family not in FAMILIES or len(digest) != _DIGEST_CHARS:
+ return None
+ for path in _family_files(family):
+ if _digest(str(path)) == digest:
+ return path
+ return None
+
+
+def default_source_id() -> Optional[str]:
+ """The active server session if we have one, else the newest log we found."""
+ sources = list_sources()
+ if not sources:
+ return None
+ for source in sources:
+ if source.family == "server" and source.is_current:
+ return source.id
+ # No live session: the newest file across every family, NOT any retained
+ # server log. Preferring a stale server log opened the tab on a previous
+ # run while the llama log holding the failure sat one entry down, which is
+ # the state after UNSLOTH_STUDIO_NO_FILE_LOG=1 or a failed log setup, the
+ # two cases where a user is most likely to be looking.
+ return max(sources, key = lambda s: s.modified_at).id
+
+
+def file_logging_disabled() -> bool:
+ return os.environ.get("UNSLOTH_STUDIO_NO_FILE_LOG") == "1"
+
+
+def source_is_frozen(source_id: Optional[str]) -> bool:
+ """Whether nothing will ever be appended to this source again.
+
+ UNSLOTH_STUDIO_NO_FILE_LOG only skips _setup_server_disk_logging in run.py.
+ The llama and diffusion runners and the Tauri shell keep writing their own
+ files, so treating the setting as global told a user watching a live
+ llama-server log that it was an earlier session and would not update while
+ the failure they came for was still being appended to it.
+ """
+ if not file_logging_disabled():
+ return False
+ family = (source_id or "").partition(":")[0]
+ return family == "server"
diff --git a/studio/backend/utils/log_redaction.py b/studio/backend/utils/log_redaction.py
new file mode 100644
index 00000000000..3819084b4e5
--- /dev/null
+++ b/studio/backend/utils/log_redaction.py
@@ -0,0 +1,237 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Mask credentials in log text before it leaves the process.
+
+Nothing redacts secrets today: loggers/handlers.py:filter_sensitive_data only
+masks native path leases, and raw output (faulthandler dumps, uvicorn, third
+party prints) never passes through a structlog processor at all. The log viewer
+invites users to copy lines into a bug report, so the masking happens on read.
+
+Every pattern is anchored on a known credential prefix or a key name. There is
+deliberately NO generic "long high entropy string" rule: that would eat sha256
+blob digests, HF revisions, snapshot paths and GGUF tensor names, which is
+exactly the content someone opened the log to read.
+"""
+
+from __future__ import annotations
+
+import re
+
+REDACTED = "<redacted>"
+
+# Terminal control sequences, stripped BEFORE anything is matched. A colorized
+# writer puts an escape between the key and its value (structlog's ConsoleRenderer
+# renders "\x1b[36mapi_key\x1b[0m=\x1b[35m<secret>\x1b[0m", and colors default on
+# even off-terminal); the "m" ending "\x1b[36m" is a word character, so every
+# anchored rule below stops matching and the credential goes out untouched.
+#
+# Order matters: OSC (\x1b]) comes before the single-character Fe class, which
+# covers 0x5C-0x5F and would otherwise swallow the "]" and leave the payload.
+# ECMA-48 5.4 (CSI) and 5.6 (OSC / DCS / SOS / PM / APC).
+_ANSI_RE = re.compile(
+ r"\x1b\][\s\S]*?(?:\x07|\x1b\\|\x9c)" # OSC ... BEL / ST
+ r"|\x1b[P^_X][\s\S]*?(?:\x1b\\|\x9c)" # DCS / PM / APC / SOS ... ST
+ r"|\x1b\[[0-?]*[ -/]*[@-~]" # CSI (colors, cursor moves)
+ r"|\x1b[@-Z\\-_]" # other two-character Fe escapes
+ r"|\x9b[0-?]*[ -/]*[@-~]" # 8-bit CSI
+ r"|[\x9d\x90\x98\x9e\x9f][\s\S]*?(?:\x07|\x9c)" # 8-bit OSC / DCS / SOS / PM / APC
+)
+_ANSI_INTRODUCER_RE = re.compile(r"[\x1b\x90\x98\x9b\x9d-\x9f]")
+
+# Key names whose VALUE is a secret. "token" alone is absent on purpose, so
+# n_tokens = 4096 and token_id=128009 survive.
+_SECRET_KEYS = (
+ "authorization|x-api-key|api[-_]?key|apikey|hf[-_]?token|access[-_]?token|"
+ "refresh[-_]?token|auth[-_]?token|bearer[-_]?token|client[-_]?secret|"
+ "aws_secret_access_key|aws_session_token|wandb[-_]?token|hub[-_]?token|"
+ # Studio's own S3 field (models/training.py:60) and its camelCase request
+ # alias. Neither is reachable through the bare "secret" alternative: the
+ # trailing \b cannot fire before "_access" or "Access", and an AWS secret
+ # key has no prefix of its own for a shape rule to catch.
+ "secret[-_]?access[-_]?key|"
+ "password|passwd|secret"
+)
+
+# No leading \b: "_" is a word character, so \b never fires inside
+# OPENAI_API_KEY / db_password, the shape an env dump or argv line carries. The
+# trailing \b stays, so eos_token_id and secret_sauce_path are left alone.
+_KEY_START = r"(?<![A-Za-z0-9])"
+
+_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
+ # Hugging Face
+ (re.compile(r"\bhf_[A-Za-z0-9]{20,}"), "hf_" + REDACTED),
+ # OpenAI and other sk- keys (project, Anthropic, OpenRouter). Not \b: that
+ # also fires after a hyphen, eating checkpoint-sk-9f8a... in a filename.
+ (
+ re.compile(r"(?<![A-Za-z0-9-])sk-(?:proj-|ant-api\d{2}-|or-v1-)?[A-Za-z0-9_-]{16,}"),
+ "sk-" + REDACTED,
+ ),
+ # Other vendor prefixes
+ (
+ re.compile(
+ r"\b(?:gsk_|xai-|ghp_|gho_|ghu_|ghs_|ghr_|github_pat_|glpat-|"
+ r"xox[abpsr]-|ya29\.)[A-Za-z0-9_.-]{16,}"
+ ),
+ REDACTED,
+ ),
+ (re.compile(r"\bAIza[0-9A-Za-z_-]{30,}"), REDACTED),
+ (re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), REDACTED),
+ # JWTs, including the desktop access token
+ (re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}"), REDACTED),
+ # user:password@host in a URL
+ (re.compile(r"://[^/\s:@]+:[^/\s@]+@"), "://" + REDACTED + "@"),
+ # Presigned URL parameters. Bare "key" is deliberately absent: in an object
+ # storage URL it names the object, and blanking it hides WHICH download
+ # failed. Google's ?key=AIza... is caught by the AIza rule above.
+ (
+ re.compile(
+ r"(?i)([?&](?:token|api[-_]key|apikey|sig|signature|x-amz-signature|"
+ r"x-amz-credential|x-amz-security-token|access_token)=)[^&\s\"']+"
+ ),
+ r"\1" + REDACTED,
+ ),
+)
+
+# key = value / "key": "value" / --api-key value
+#
+# The QUOTED branch wins whenever an opening quote is there, so a quoted
+# credential is consumed to its CLOSING quote instead of stopping at the first
+# space. Stopping at whitespace turned password="correct horse battery staple"
+# into password="<redacted> horse battery staple", which reads as masked while
+# leaking all but the first word. Passphrases with spaces are the realistic
+# shape, and a partially masked one invites pasting the line into a bug report.
+#
+# "[^\"'\\\n]|\\." rather than a lazy ".*?" so an escaped quote does not end the
+# value early; \n is excluded so an unterminated quote cannot run the mask past
+# its own line.
+_QUOTED_VALUE = r"(?:[^\"'\\\n]|\\.){6,}"
+_KV_RE = re.compile(
+ r"(?i)" + _KEY_START + r"(?P<key>" + _SECRET_KEYS + r")\b"
+ r"(?P<sep>[\"']?\s*[:=]\s*(?P<q>[\"'])?)"
+ r"(?P<val>(?(q)" + _QUOTED_VALUE + r"|[^\"'\s,}\]]{6,}))"
+)
+_FLAG_RE = re.compile(
+ r"(?i)(?P<key>--(?:" + _SECRET_KEYS + r"))"
+ r"(?P<sep>\s+(?P<q>[\"'])?)"
+ r"(?P<val>(?(q)" + _QUOTED_VALUE + r"|[^\s\"']{6,}))"
+)
+
+# An Authorization value, whatever the scheme. The key/value rule cannot reach
+# it: for "Authorization: Basic dXNlcjpwdw==" the value it captures is "Basic",
+# leaving the credential behind it. Same for a Cookie, which for Studio is the
+# UI session that gates these very endpoints.
+_SCHEMES = ("bearer", "basic", "digest", "token", "apikey")
+# A scheme word only introduces a credential when an Authorization header put it
+# there. Bare "digest sha256:..." and "token hf_..." are ordinary log content,
+# and firing on the word alone blanked the digest a user came here to read.
+# The credential stops at a quote or a structural delimiter rather than at the
+# next space: \S+ swallowed the closing quote and every field behind it, so a
+# compact header dict came back as {"Authorization":"Bearer <redacted> with the
+# request id and status the user opened the pane to read gone with it.
+_CREDENTIAL = r"[^\s\"',}\]]+"
+_AUTH_HEADER_RE = re.compile(
+ r"(?i)((?:proxy-)?authorization[\"']?\s*[:=]\s*[\"']?"
+ r"(?:" + "|".join(_SCHEMES) + r"))(\s+)(" + _CREDENTIAL + r")"
+)
+# Bearer is not an English word that shows up in a log on its own, so it keeps
+# a header-less rule; the shape guard still spares "Bearer credentials expired".
+_SCHEME_RE = re.compile(r"(?i)\b(Bearer)(\s+)(" + _CREDENTIAL + r")")
+# MULTILINE: this also runs over exception text, where the header is not on the
+# last line. The optional quote matters: headers are usually logged as a dict,
+# and an anchored pair test on a value that opened with one never matched, so
+# the session cookie gating these very endpoints went out in the clear.
+_COOKIE_RE = re.compile(
+ r"(?i)\b(?P<key>(?:set-)?cookie)(?P<sep>[\"']?\s*[:=]\s*(?P<q>[\"'])?)(?P<val>\S.*)$",
+ re.MULTILINE,
+)
+
+# Keys whose value is a secret even when it is all digits (a numeric password is
+# still a password); everywhere else a bare number is a count or an id.
+_NUMERIC_IS_STILL_SECRET = re.compile(r"(?i)pass(word|wd)?$|secret$")
+
+
+def _looks_like_credential(value: str) -> bool:
+ """Token-shaped rather than an English word.
+
+ Guards the rules keyed on a weak name. "Bearer credentials were not
+ accepted" and "Cookie: disabled" are log content someone opened the viewer
+ to read, and blanking them hides the failure being diagnosed.
+ """
+ if len(value) < 8:
+ return False
+ if len(value) >= 20:
+ return True
+ has_digit = any(char.isdigit() for char in value)
+ has_symbol = any(char in "._-+/=~" for char in value)
+ mixed_case = any(char.isupper() for char in value) and any(char.islower() for char in value)
+ return has_digit or has_symbol or mixed_case
+
+
+def _redact_kv(match: re.Match[str]) -> str:
+ # Named groups: the quoted/unquoted branch adds a group, so positional
+ # numbering is not stable.
+ value = match.group("val")
+ # A numeric value is a count or an id, never a credential.
+ if value.isdigit() and not _NUMERIC_IS_STILL_SECRET.search(match.group("key")):
+ return match.group(0)
+ # Quoting puts the scheme inside the value ('authorization': 'Basic abc').
+ # Step over it rather than abandon the match: the rest is still the
+ # credential, and blanking the scheme reads as if the header were the secret.
+ scheme, sep, rest = value.partition(" ")
+ if scheme.lower() in _SCHEMES:
+ if not sep or not rest.strip():
+ return match.group(0)
+ return f"{match.group('key')}{match.group('sep')}{scheme}{sep}{REDACTED}"
+ return f"{match.group('key')}{match.group('sep')}{REDACTED}"
+
+
+def _redact_shaped(match: re.Match[str]) -> str:
+ if not _looks_like_credential(match.group(3)):
+ return match.group(0)
+ return f"{match.group(1)}{match.group(2)}{REDACTED}"
+
+
+# A cookie header is name=value pairs. _COOKIE_RE takes the rest of the line, so
+# without this "Cookie: not sent because the origin is cross-site" is 20-odd
+# characters and the length shortcut reads it as a token, masking the diagnosis.
+_COOKIE_PAIR_RE = re.compile(r"^[A-Za-z0-9_.\-]+=\S")
+
+
+def _redact_cookie(match: re.Match[str]) -> str:
+ value, tail = match.group("val"), ""
+ # A quoted value ends at its closing quote, so the fields behind it in a
+ # header dict survive instead of disappearing into the mask.
+ quote = match.group("q")
+ if quote:
+ end = value.find(quote)
+ if end != -1:
+ value, tail = value[:end], value[end:]
+ if not _COOKIE_PAIR_RE.match(value.strip()):
+ return match.group(0)
+ return f"{match.group('key')}{match.group('sep')}{REDACTED}{tail}"
+
+
+def redact_log_text(text: str) -> str:
+ """Mask credentials. Idempotent, and a no-op on ordinary log content."""
+ if not text:
+ return text
+ # Nothing anchored below survives an escape between a key and its value, so
+ # strip first, guarded by one introducer scan: ordinary content is untouched.
+ if _ANSI_INTRODUCER_RE.search(text):
+ text = _ANSI_RE.sub("", text)
+ for pattern, replacement in _PATTERNS:
+ text = pattern.sub(replacement, text)
+ # Before the key/value rules: _KV_RE captures "Basic" from "Authorization:
+ # Basic dXNlcjpwdw==", masking the scheme and leaving the credential clear.
+ text = _AUTH_HEADER_RE.sub(_redact_shaped, text)
+ text = _SCHEME_RE.sub(_redact_shaped, text)
+ text = _COOKIE_RE.sub(_redact_cookie, text)
+ text = _KV_RE.sub(_redact_kv, text)
+ text = _FLAG_RE.sub(_redact_kv, text)
+ try:
+ from utils.native_path_leases import redact_native_paths
+ text = redact_native_paths(text)
+ except Exception:
+ pass
+ return text
diff --git a/studio/frontend/src/features/settings/api/debug-logs.ts b/studio/frontend/src/features/settings/api/debug-logs.ts
new file mode 100644
index 00000000000..cc8e18c99da
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/debug-logs.ts
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+import { DebugLogRequestError } from "../lib/debug-log-error";
+
+export { DebugLogRequestError } from "../lib/debug-log-error";
+
+export type DebugLogStatus =
+ | "ok"
+ | "empty"
+ | "missing"
+ | "unreadable"
+ | "disabled";
+
+export interface DebugLogSource {
+ id: string;
+ family: string;
+ label: string;
+ realpath: string;
+ sizeBytes: number;
+ modifiedAt: number;
+ isCurrent: boolean;
+}
+
+export interface DebugLogSources {
+ sources: DebugLogSource[];
+ defaultSourceId: string | null;
+ fileLoggingDisabled: boolean;
+}
+
+export interface DebugLogPage {
+ status: DebugLogStatus;
+ reason: string | null;
+ sourceId: string | null;
+ realpath: string | null;
+ lines: string[];
+ cursor: string | null;
+ reset: boolean;
+ resetReason: string | null;
+ droppedBytes: number;
+ truncatedHead: boolean;
+ morePending: boolean;
+ fileLoggingDisabled: boolean;
+ sizeBytes: number;
+}
+
+export async function loadDebugLogSources(
+ signal?: AbortSignal,
+): Promise<DebugLogSources> {
+ const response = await authFetch("/api/settings/debug/logs/sources", {
+ signal,
+ });
+ if (!response.ok) {
+ throw new Error(
+ await readFastApiError(response, "Could not list the log files."),
+ );
+ }
+ const body = await response.json();
+ return {
+ sources: (body.sources ?? []).map((source: Record<string, unknown>) => ({
+ id: String(source.id),
+ family: String(source.family),
+ label: String(source.label),
+ realpath: String(source.realpath),
+ sizeBytes: Number(source.size_bytes ?? 0),
+ modifiedAt: Number(source.modified_at ?? 0),
+ isCurrent: Boolean(source.is_current),
+ })),
+ defaultSourceId: body.default_source_id ?? null,
+ fileLoggingDisabled: Boolean(body.file_logging_disabled),
+ };
+}
+
+export async function loadDebugLog(
+ options: {
+ sourceId?: string | null;
+ cursor?: string | null;
+ signal?: AbortSignal;
+ } = {},
+): Promise<DebugLogPage> {
+ const params = new URLSearchParams();
+ if (options.sourceId) params.set("source", options.sourceId);
+ if (options.cursor) params.set("cursor", options.cursor);
+ const query = params.toString();
+ const response = await authFetch(
+ `/api/settings/debug/logs${query ? `?${query}` : ""}`,
+ {
+ signal: options.signal,
+ },
+ );
+ if (!response.ok) {
+ throw new DebugLogRequestError(
+ await readFastApiError(response, "Could not read the log."),
+ response.status,
+ );
+ }
+ const body = await response.json();
+ return {
+ status: body.status,
+ reason: body.reason ?? null,
+ sourceId: body.source_id ?? null,
+ realpath: body.realpath ?? null,
+ lines: body.lines ?? [],
+ cursor: body.cursor ?? null,
+ reset: Boolean(body.reset),
+ resetReason: body.reset_reason ?? null,
+ droppedBytes: Number(body.dropped_bytes ?? 0),
+ truncatedHead: Boolean(body.truncated_head),
+ morePending: Boolean(body.more_pending),
+ fileLoggingDisabled: Boolean(body.file_logging_disabled),
+ sizeBytes: Number(body.size_bytes ?? 0),
+ };
+}
diff --git a/studio/frontend/src/features/settings/lib/debug-log-buffer.ts b/studio/frontend/src/features/settings/lib/debug-log-buffer.ts
new file mode 100644
index 00000000000..96ed2189357
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/debug-log-buffer.ts
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Buffer and polling maths for the Settings > Logs log viewer. Kept free
+ * of React so it can be tested: the tab component pulls in the router, motion
+ * and hugeicons and cannot be imported under node:test.
+ */
+
+export type RefreshMode = "live" | "3s" | "manual";
+
+export const DEFAULT_REFRESH_MODE: RefreshMode = "3s";
+export const REFRESH_MODE_STORAGE_KEY = "unsloth_debug_log_refresh_mode";
+
+/** The request backstop fired. Distinct from an AbortError because the two
+ * arrive as the same rejection: the timer aborts the very controller an unmount
+ * or a source switch uses, and those are silent by design. Sharing the name
+ * made a hung tunnel silent too, so the pane stopped updating and said nothing,
+ * which is the failure this viewer exists to make visible.
+ *
+ * Here rather than beside the other error types because this module is imported
+ * by the node:test runner, which resolves no extensionless src import.
+ */
+export class DebugLogTimeoutError extends Error {
+ constructor(timeoutMs: number) {
+ super(`Request timed out after ${Math.round(timeoutMs / 1000)}s.`);
+ this.name = "DebugLogTimeoutError";
+ }
+}
+
+export function isRequestTimeout(error: unknown): boolean {
+ return error instanceof DebugLogTimeoutError;
+}
+
+/** What `fetch` rejects with on an abort. Built by hand rather than taken from
+ * a cancelled request, for the tie where the deadline won the race but the
+ * caller had already asked to stop. */
+function abortError(): Error {
+ const error = new Error("Aborted.");
+ error.name = "AbortError";
+ return error;
+}
+
+/** Generous next to a 1s poll: this is the "this request will never answer"
+ * backstop, not a latency budget. A remote tunnel can legitimately be slow. */
+export const REQUEST_TIMEOUT_MS = 20_000;
+
+/** Bounds on what the viewer holds. The server already caps a response; this
+ * caps the accumulation across a long session. */
+export const MAX_CLIENT_LINES = 2000;
+export const MAX_CLIENT_CHARS = 400_000;
+
+export interface DebugLogChunk {
+ lines: string[];
+ cursor: string | null;
+ reset: boolean;
+}
+
+export interface LogBufferState {
+ lines: string[];
+ cursor: string | null;
+}
+
+export const EMPTY_BUFFER: LogBufferState = { lines: [], cursor: null };
+
+/** Poll delay for a mode, or null when the user drives it by hand. "live" polls
+ * rather than opening a socket: Cloudflare quick tunnels buffer
+ * text/event-stream and only flush at close, which is why the export log polls too.
+ */
+export function pollDelayMs(mode: RefreshMode): number | null {
+ switch (mode) {
+ case "live":
+ return 1000;
+ case "3s":
+ return 3000;
+ case "manual":
+ return null;
+ }
+}
+
+export function parseRefreshMode(value: unknown): RefreshMode {
+ return value === "live" || value === "3s" || value === "manual"
+ ? value
+ : DEFAULT_REFRESH_MODE;
+}
+
+/** Run a request under the "this will never answer" backstop, linked to the
+ * caller's signal.
+ *
+ * EVERY request the viewer awaits needs this, not just the tail read: the auth
+ * client passes `init` straight to `fetch` and adds no timeout, so a request
+ * that opens and never settles hangs its awaiter for good. The poll loop awaits
+ * the source rescan first, so an unanswered /sources froze the pane. Signals are
+ * linked by hand because `AbortSignal.any` is Safari 17.4 against a 16.4 floor.
+ *
+ * The deadline is RACED rather than awaited behind the abort, because aborting
+ * only settles work that watches the signal. `authFetch` awaits
+ * `refreshSession()` on a 401 and hands it no signal, so an expired token plus a
+ * hung refresh left this promise pending for good: the caller's in-flight guard
+ * stayed pinned and the pane froze, which is precisely what the backstop is for.
+ */
+export async function withRequestTimeout<T>(
+ task: (signal: AbortSignal) => Promise<T>,
+ timeoutMs: number,
+ signal?: AbortSignal,
+): Promise<T> {
+ const local = new AbortController();
+ if (signal?.aborted) local.abort();
+ const relay = () => local.abort();
+ signal?.addEventListener("abort", relay);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const running = task(local.signal);
+ // The loser of the race can still reject afterwards, and an unobserved
+ // rejection is a console error (a process-level crash under node:test).
+ running.catch(() => {});
+ const deadline = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ // Reject BEFORE aborting. `local.abort()` settles an abort-aware task
+ // synchronously, and that rejection would then win the race and arrive
+ // as an ordinary AbortError, which the poll loop drops in silence: the
+ // deadline would announce itself only for work that ignores the signal.
+ reject(new DebugLogTimeoutError(timeoutMs));
+ local.abort();
+ }, timeoutMs);
+ });
+ try {
+ return await Promise.race([running, deadline]);
+ } catch (error) {
+ // The caller's own abort wins the tie: an unmount or a source switch is
+ // silent by design, and it can race the timer on a request that was
+ // already doomed. Only a backstop with no caller abort behind it is a
+ // fault the user needs told about.
+ if (signal?.aborted && isRequestTimeout(error)) throw abortError();
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", relay);
+ }
+}
+
+/** Whether a response that has just landed still belongs on screen.
+ *
+ * `selection` counts source changes. A manual refresh carries no abort signal,
+ * so a slow read of source A can answer after the user picked B; comparing
+ * source ids does not catch it, since the answer really is A's and it is the
+ * view underneath that moved. Counting also covers A -> B -> A, where the id
+ * matches again but the buffer was reset and A's old cursor would rewind it.
+ */
+export function isPageStale(page: {
+ requestSelection: number;
+ currentSelection: number;
+ requestSourceId: string | null;
+ pageSourceId: string | null;
+}): boolean {
+ if (page.requestSelection !== page.currentSelection) return true;
+ // The server answers an unset source with its default, so only disagree when
+ // both ends named one.
+ return Boolean(
+ page.requestSourceId &&
+ page.pageSourceId &&
+ page.requestSourceId !== page.pageSourceId,
+ );
+}
+
+/** Whether the "some lines were skipped" warning shows after this response.
+ *
+ * Sticky, because the gap it reports stays in the buffer: recomputing from the
+ * newest response alone cleared the warning on the next poll (1s in live mode)
+ * while the pane was still missing those lines. Only a reset clears it, since
+ * that replaces everything on screen with a fresh tail.
+ */
+export function nextDroppedState(
+ previous: boolean,
+ page: { droppedBytes: number; reset: boolean },
+): boolean {
+ if (page.droppedBytes > 0) return true;
+ return page.reset ? false : previous;
+}
+
+/** Drop from the front until the buffer is within both caps. */
+export function trimBuffer(lines: string[]): string[] {
+ let trimmed =
+ lines.length > MAX_CLIENT_LINES ? lines.slice(-MAX_CLIENT_LINES) : lines;
+ let chars = 0;
+ for (const line of trimmed) chars += line.length + 1;
+ if (chars <= MAX_CLIENT_CHARS) return trimmed;
+ let start = 0;
+ while (start < trimmed.length && chars > MAX_CLIENT_CHARS) {
+ chars -= trimmed[start].length + 1;
+ start += 1;
+ }
+ trimmed = trimmed.slice(start);
+ return trimmed;
+}
+
+/** Fold one response into the buffer. Returns the SAME object when the chunk
+ * carries nothing new, so the caller can skip a re-render: at a 1s poll on a
+ * quiet server almost every tick is empty.
+ */
+export function applyLogChunk(
+ previous: LogBufferState,
+ chunk: DebugLogChunk,
+): LogBufferState {
+ if (chunk.reset) {
+ return { lines: trimBuffer(chunk.lines.slice()), cursor: chunk.cursor };
+ }
+ if (chunk.lines.length === 0) {
+ if (chunk.cursor === previous.cursor) return previous;
+ return { lines: previous.lines, cursor: chunk.cursor };
+ }
+ return {
+ lines: trimBuffer(previous.lines.concat(chunk.lines)),
+ cursor: chunk.cursor,
+ };
+}
diff --git a/studio/frontend/src/features/settings/lib/debug-log-error.ts b/studio/frontend/src/features/settings/lib/debug-log-error.ts
new file mode 100644
index 00000000000..35df3c40a43
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/debug-log-error.ts
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** A leaf module with no imports, so the recovery rule can be tested without
+ * pulling the auth client (and the assets behind it) into the test runner. */
+
+/** Carries the HTTP status because only one is recoverable: the log endpoint
+ * answers every content state 200 with a `status` field, and keeps 404 for
+ * "that source id is no longer one I enumerate". */
+export class DebugLogRequestError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = "DebugLogRequestError";
+ this.status = status;
+ }
+}
+
+/** True when the selected log is gone and the picker should rebuild: removed,
+ * or pushed out of the per-family window by a run of failed load attempts. */
+export function isLogSourceGone(error: unknown): boolean {
+ return error instanceof DebugLogRequestError && error.status === 404;
+}
+
+export function isAbort(error: unknown): boolean {
+ return (error as Error | undefined)?.name === "AbortError";
+}
diff --git a/studio/frontend/src/features/settings/settings-dialog.tsx b/studio/frontend/src/features/settings/settings-dialog.tsx
index e090c508aff..a7b902f742c 100644
--- a/studio/frontend/src/features/settings/settings-dialog.tsx
+++ b/studio/frontend/src/features/settings/settings-dialog.tsx
@@ -17,6 +17,7 @@ import {
BotIcon,
Cancel01Icon,
CloudIcon,
+ ComputerTerminal01Icon,
CpuIcon,
DatabaseSettingIcon,
Globe02Icon,
@@ -52,6 +53,7 @@ import { AppearanceTab } from "./tabs/appearance-tab";
import { ChatTab } from "./tabs/chat-tab";
import { ConnectionsTab } from "./tabs/connections-tab";
import { DataTab } from "./tabs/data-tab";
+import { DebuggingTab } from "./tabs/debugging-tab";
import { GeneralTab } from "./tabs/general-tab";
import { ProfileTab } from "./tabs/profile-tab";
import { ResourcesTab } from "./tabs/resources-tab";
@@ -117,6 +119,11 @@ const TABS: TabDef[] = [
icon: DatabaseSettingIcon,
badgeKey: "common.new",
},
+ {
+ id: "debugging",
+ labelKey: "settings.tabs.debugging",
+ icon: ComputerTerminal01Icon,
+ },
{ id: "about", labelKey: "settings.tabs.about", icon: HelpCircleIcon },
];
@@ -152,6 +159,8 @@ function renderTab(tab: SettingsTab) {
return <ApiKeysTab />;
case "agents":
return <AgentsTab />;
+ case "debugging":
+ return <DebuggingTab />;
case "about":
return <AboutTab />;
}
@@ -264,6 +273,7 @@ export function SettingsDialog() {
data: null,
"api-keys": null,
agents: null,
+ debugging: null,
about: null,
});
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 3ef1d8df162..e2e1f42748a 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -146,6 +146,14 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.voice.readAloud.volumeLabel",
"settings.voice.readAloud.previewLabel",
],
+ debugging: [
+ "settings.debugging.logSection",
+ "settings.debugging.source",
+ "settings.debugging.path",
+ "settings.debugging.refreshSection",
+ "settings.debugging.mode",
+ "settings.debugging.keywords",
+ ],
about: [
"settings.about.updates",
"settings.about.releaseNotes",
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 6f4e696b854..a17b83da6cd 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -14,6 +14,7 @@ export type SettingsTab =
| "data"
| "api-keys"
| "agents"
+ | "debugging"
| "about";
export type SettingsScrollTarget = "about-updates" | "appearance-sidebar-nav";
@@ -75,6 +76,7 @@ function loadInitialTab(): SettingsTab {
"data",
"api-keys",
"agents",
+ "debugging",
"about",
];
return valid.includes(stored as SettingsTab)
diff --git a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
new file mode 100644
index 00000000000..da120d7f8e9
--- /dev/null
+++ b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
@@ -0,0 +1,410 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import { useCopyFeedback } from "@/features/hub/hooks/use-copy-feedback";
+import { useT } from "@/i18n";
+import { stripAnsi } from "@/lib/strip-ansi";
+import { Tick02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ type DebugLogSource,
+ loadDebugLog,
+ loadDebugLogSources,
+} from "../api/debug-logs";
+import { SettingsRow } from "../components/settings-row";
+import { SettingsSection } from "../components/settings-section";
+import {
+ DEFAULT_REFRESH_MODE,
+ EMPTY_BUFFER,
+ type LogBufferState,
+ REFRESH_MODE_STORAGE_KEY,
+ REQUEST_TIMEOUT_MS,
+ type RefreshMode,
+ applyLogChunk,
+ isPageStale,
+ nextDroppedState,
+ parseRefreshMode,
+ isRequestTimeout,
+ pollDelayMs,
+ withRequestTimeout,
+} from "../lib/debug-log-buffer";
+import { isAbort, isLogSourceGone } from "../lib/debug-log-error";
+
+const MODES: RefreshMode[] = ["live", "3s", "manual"];
+
+// Rescan cadence for log files that did not exist when the tab was opened.
+// Slower than the poll: a directory walk rather than a tail read.
+const SOURCE_RESCAN_MS = 10_000;
+
+function readStoredMode(): RefreshMode {
+ if (typeof window === "undefined") return DEFAULT_REFRESH_MODE;
+ try {
+ return parseRefreshMode(
+ window.localStorage.getItem(REFRESH_MODE_STORAGE_KEY),
+ );
+ } catch {
+ return DEFAULT_REFRESH_MODE;
+ }
+}
+
+export function DebuggingTab() {
+ const t = useT();
+ const [sources, setSources] = useState<DebugLogSource[]>([]);
+ const [sourceId, setSourceId] = useState<string | null>(null);
+ const [mode, setMode] = useState<RefreshMode>(readStoredMode);
+ const [buffer, setBuffer] = useState<LogBufferState>(EMPTY_BUFFER);
+ const [realpath, setRealpath] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [dropped, setDropped] = useState(false);
+ // Reported by the reader, and until now read by nobody: a burst larger than
+ // one response continues on the next poll, which in manual mode never comes
+ // unless the user knows to ask for it.
+ const [morePending, setMorePending] = useState(false);
+ // File logging is off and an older session's log is still on disk, so the
+ // pane shows real content that will never grow. Without saying so, a stale
+ // log is indistinguishable from a live one.
+ const [staleSession, setStaleSession] = useState(false);
+ const { copied, copy } = useCopyFeedback();
+
+ // In a ref as well as state: the poll loop must not restart per line arrived.
+ const cursorRef = useRef<string | null>(null);
+ // Counts source changes, so an in-flight request can tell its view was
+ // replaced.
+ const selectionRef = useRef(0);
+ // The selection in flight, not a bare flag: a poll for the newly picked source
+ // must not be swallowed by a slow read of the one the user just left, or the
+ // new pane stays empty (in manual mode, for good).
+ const inFlightRef = useRef<number | null>(null);
+ const paneRef = useRef<HTMLPreElement | null>(null);
+ const pinnedRef = useRef(true);
+ const lastSourceScanRef = useRef(Date.now());
+
+ useEffect(() => {
+ try {
+ window.localStorage.setItem(REFRESH_MODE_STORAGE_KEY, mode);
+ } catch {
+ // A blocked localStorage must not stop the viewer working.
+ }
+ }, [mode]);
+
+ const refreshSources = useCallback(
+ async (options: { signal?: AbortSignal; reselect?: boolean } = {}) => {
+ try {
+ // Bounded like the tail read: the poll loop and its failure recovery
+ // both await this, so an unanswered /sources would freeze both.
+ const result = await withRequestTimeout(
+ (signal) => loadDebugLogSources(signal),
+ REQUEST_TIMEOUT_MS,
+ options.signal,
+ );
+ setSources(result.sources);
+ setSourceId((current) =>
+ options.reselect
+ ? result.defaultSourceId
+ : (current ?? result.defaultSourceId),
+ );
+ } catch {
+ // The log read reports the real reason; this just leaves the picker empty.
+ }
+ },
+ [],
+ );
+
+ useEffect(() => {
+ const controller = new AbortController();
+ void refreshSources({ signal: controller.signal });
+ return () => controller.abort();
+ }, [refreshSources]);
+
+ const onPollFailed = useCallback(
+ async (error: unknown, signal?: AbortSignal) => {
+ if (isAbort(error)) return;
+ if (isRequestTimeout(error)) {
+ // Not the raw message: the backstop is an internal number and the user
+ // needs the consequence, not the duration.
+ setNotice(t("settings.debugging.timeout"));
+ return;
+ }
+ if (isLogSourceGone(error)) {
+ // The id we hold is no longer enumerated (file removed, or pushed out of
+ // the per-family window). The backend sends 404 precisely so the picker
+ // rebuilds; without this the loop re-polls a dead id forever.
+ // Reselecting the server's default terminates: it comes from the same
+ // walk, and "nothing at all" is a 200 with a status, not another 404.
+ cursorRef.current = null;
+ await refreshSources({ signal, reselect: true });
+ return;
+ }
+ setNotice((error as Error).message);
+ },
+ [refreshSources, t],
+ );
+
+ // The llama runner writes a NEW file per load attempt, so a list fetched at
+ // mount goes stale exactly when it matters: fail a load with the tab open and
+ // that failure's log is not offered. It is three directory listings, hence the
+ // slower cadence than the tail poll.
+ const rescanSourcesIfStale = useCallback(
+ async (signal?: AbortSignal) => {
+ if (Date.now() - lastSourceScanRef.current < SOURCE_RESCAN_MS) return;
+ lastSourceScanRef.current = Date.now();
+ await refreshSources({ signal });
+ },
+ [refreshSources],
+ );
+
+ const poll = useCallback(
+ async (signal?: AbortSignal) => {
+ const selection = selectionRef.current;
+ if (inFlightRef.current === selection) return;
+ inFlightRef.current = selection;
+ // Without the timeout a request that never settles pins inFlightRef
+ // forever: every poll returns at the guard above and the pane freezes with
+ // no error, since the catch never runs. A dropped tunnel is enough.
+ try {
+ const page = await withRequestTimeout(
+ (requestSignal) =>
+ loadDebugLog({
+ sourceId,
+ cursor: cursorRef.current,
+ signal: requestSignal,
+ }),
+ REQUEST_TIMEOUT_MS,
+ signal,
+ );
+ // A manual refresh carries no abort signal, so one in flight across a
+ // source switch would land the old file's lines under the new pick.
+ if (
+ isPageStale({
+ requestSelection: selection,
+ currentSelection: selectionRef.current,
+ requestSourceId: sourceId,
+ pageSourceId: page.sourceId,
+ })
+ )
+ return;
+ cursorRef.current = page.cursor;
+ if (page.realpath) setRealpath(page.realpath);
+ setDropped((previous) => nextDroppedState(previous, page));
+ setMorePending(page.morePending);
+ setStaleSession(page.fileLoggingDisabled);
+ setNotice(
+ page.status === "ok" || page.status === "empty"
+ ? null
+ : (page.reason ?? t(`settings.debugging.${page.status}` as never)),
+ );
+ setBuffer((previous) =>
+ applyLogChunk(previous, {
+ lines: page.lines,
+ cursor: page.cursor,
+ reset: page.reset,
+ }),
+ );
+ } catch (error) {
+ if (selection === selectionRef.current)
+ await onPollFailed(error, signal);
+ } finally {
+ // Only if a poll for a newer selection has not taken the slot.
+ if (inFlightRef.current === selection) inFlightRef.current = null;
+ }
+ },
+ [onPollFailed, sourceId, t],
+ );
+
+ // Switching source starts a fresh read rather than appending to the old file.
+ useEffect(() => {
+ selectionRef.current += 1;
+ cursorRef.current = null;
+ setBuffer(EMPTY_BUFFER);
+ setRealpath(null);
+ // Every notice below describes the file being left, so all of them go with
+ // it. Clearing only `dropped` let a failed first read on the new source
+ // keep claiming the OLD one's state, and in manual mode nothing retries to
+ // correct it: the pane would sit there calling a live log a frozen session.
+ setDropped(false);
+ setMorePending(false);
+ setStaleSession(false);
+ setNotice(null);
+ }, [sourceId]);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ let timer: number | undefined;
+ let stopped = false;
+
+ // A self-scheduling timeout, not setInterval: the next poll is queued only
+ // once the previous settled, so a slow link builds no backlog.
+ const tick = async () => {
+ if (stopped) return;
+ if (
+ typeof document === "undefined" ||
+ document.visibilityState !== "hidden"
+ ) {
+ await rescanSourcesIfStale(controller.signal);
+ await poll(controller.signal);
+ }
+ if (stopped) return;
+ const delay = pollDelayMs(mode);
+ if (delay !== null) timer = window.setTimeout(tick, delay);
+ };
+
+ void tick();
+ return () => {
+ stopped = true;
+ controller.abort();
+ if (timer !== undefined) window.clearTimeout(timer);
+ };
+ }, [mode, poll, rescanSourcesIfStale]);
+
+ const text = useMemo(
+ () => stripAnsi(buffer.lines.join("\n")),
+ [buffer.lines],
+ );
+
+ useEffect(() => {
+ const pane = paneRef.current;
+ if (pane && pinnedRef.current) pane.scrollTop = pane.scrollHeight;
+ }, [text]);
+
+ const onScroll = useCallback(() => {
+ const pane = paneRef.current;
+ if (!pane) return;
+ // Stop chasing the bottom once the user scrolls up, so a traceback stays
+ // readable while the app keeps logging.
+ pinnedRef.current =
+ pane.scrollHeight - pane.scrollTop - pane.clientHeight < 40;
+ }, []);
+
+ return (
+ <div className="flex flex-col gap-6">
+ <SettingsSection
+ title={t("settings.debugging.logSection")}
+ description={t("settings.debugging.sourceHint")}
+ >
+ <SettingsRow label={t("settings.debugging.source")}>
+ <select
+ data-testid="debug-log-source"
+ className="max-w-[22rem] rounded-md border border-border/60 bg-background px-2 py-1 text-xs"
+ value={sourceId ?? ""}
+ onChange={(event) => setSourceId(event.target.value || null)}
+ >
+ {sources.map((source) => (
+ <option key={source.id} value={source.id}>
+ {source.family} / {source.label}
+ {source.isCurrent ? " *" : ""}
+ </option>
+ ))}
+ </select>
+ </SettingsRow>
+ <SettingsRow label={t("settings.debugging.path")} alignTop={true}>
+ <div className="flex items-center gap-2">
+ <code className="max-w-[22rem] truncate text-ui-11 text-muted-foreground">
+ {realpath ?? "-"}
+ </code>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={!realpath}
+ onClick={() => realpath && copy(realpath)}
+ >
+ {copied ? (
+ <HugeiconsIcon icon={Tick02Icon} className="size-3.5" />
+ ) : (
+ t("settings.debugging.pathCopy")
+ )}
+ </Button>
+ </div>
+ </SettingsRow>
+ </SettingsSection>
+
+ <SettingsSection title={t("settings.debugging.refreshSection")}>
+ <SettingsRow label={t("settings.debugging.mode")}>
+ <div className="flex items-center gap-2">
+ <div className="flex overflow-hidden rounded-md border border-border/60">
+ {MODES.map((candidate) => (
+ <button
+ key={candidate}
+ type="button"
+ data-testid={`debug-log-mode-${candidate}`}
+ onClick={() => setMode(candidate)}
+ className={
+ candidate === mode
+ ? "bg-primary px-2 py-1 text-ui-11 text-primary-foreground"
+ : "px-2 py-1 text-ui-11 text-muted-foreground"
+ }
+ >
+ {t(
+ candidate === "live"
+ ? "settings.debugging.modeLive"
+ : candidate === "3s"
+ ? "settings.debugging.modeInterval"
+ : "settings.debugging.modeManual",
+ )}
+ </button>
+ ))}
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={mode !== "manual"}
+ onClick={() => {
+ void refreshSources();
+ void poll();
+ }}
+ >
+ {t("settings.debugging.refreshNow")}
+ </Button>
+ </div>
+ </SettingsRow>
+ </SettingsSection>
+
+ <div className="flex flex-col gap-2">
+ {notice ? (
+ <p className="text-xs text-amber-500" data-testid="debug-log-notice">
+ {notice}
+ </p>
+ ) : null}
+ {dropped ? (
+ <p className="text-xs text-amber-500">
+ {t("settings.debugging.droppedNotice")}
+ </p>
+ ) : null}
+ {morePending ? (
+ <p className="text-xs text-muted-foreground">
+ {t("settings.debugging.morePending")}
+ </p>
+ ) : null}
+ {staleSession ? (
+ <p className="text-xs text-amber-500">
+ {t("settings.debugging.staleSession")}
+ </p>
+ ) : null}
+ {/* One text surface, not an element per line: this repaints on every
+ poll and 1000 nodes per tick is what makes a log pane feel broken. */}
+ <pre
+ ref={paneRef}
+ onScroll={onScroll}
+ data-testid="debug-log-pane"
+ className="h-72 w-full overflow-auto [overflow-anchor:none] whitespace-pre-wrap break-words rounded-lg border border-border/40 bg-black/85 p-3 font-mono text-ui-11 leading-[1.45] text-emerald-200/90"
+ >
+ {text || t("settings.debugging.empty")}
+ </pre>
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-xs text-muted-foreground">
+ {t("settings.debugging.privacyNote")}
+ </p>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => copy(text)}
+ disabled={!text}
+ >
+ {t("settings.debugging.copyVisible")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 8222e282b8e..313612d81eb 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -154,8 +154,33 @@ export const ar = {
about: "حول",
data: "البيانات",
agents: "الوكلاء",
+ debugging: "السجلات",
voice: "الصوت",
},
+ debugging: {
+ logSection: "ملف السجل",
+ source: "ملف السجل",
+ sourceHint: "تكتب مشغّلات النماذج سجلاتها الخاصة، لذا غالبًا ما يكون سبب فشل التحميل أو التوليد موضّحًا فيها لا في سجل الخادم.",
+ path: "الموقع",
+ pathCopy: "نسخ المسار",
+ refreshSection: "التحديث",
+ mode: "الوضع",
+ modeLive: "مباشر",
+ modeInterval: "كل 3 ثوانٍ",
+ modeManual: "يدوي",
+ refreshNow: "تحديث الآن",
+ privacyNote: "تُخفى بيانات الاعتماد في هذا العرض. أما في الملف الموجود على القرص فلا تُخفى.",
+ copyVisible: "نسخ السجل الظاهر",
+ empty: "لم يُسجَّل أي شيء بعد.",
+ disabled: "التسجيل في ملف مُعطَّل (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "لم يُعثر على أي ملف سجل.",
+ unreadable: "تعذّرت قراءة ملف السجل.",
+ timeout: "انتهت مهلة طلب السجل. قد يتعذر الوصول إلى الخادم.",
+ droppedNotice: "تم تخطي بعض الأسطر: كُتب السجل بسرعة أكبر مما أمكن قراءته.",
+ morePending: "لا يزال يجري قراءة أسطر إضافية، وستظهر عند التحديث التالي.",
+ staleSession: "تسجيل الملفات معطل، لذا هذه جلسة سابقة ولن يتم تحديثها.",
+ keywords: "تصحيح الأخطاء سجل السجلات خطأ أخطاء تعطل تتبع تشخيص استكشاف الأخطاء debug log logs error",
+ },
voice: {
title: "الصوت",
description: "الميكروفون والإملاء وتحويل الكلام إلى نص والقراءة بصوت عالٍ",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index fdf18db3cc1..e2ab3b1867c 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -158,8 +158,33 @@ export const de = {
about: "Info",
data: "Daten",
agents: "Agenten",
+ debugging: "Protokolle",
voice: "Sprachfunktionen",
},
+ debugging: {
+ logSection: "Protokolldatei",
+ source: "Protokolldatei",
+ sourceHint: "Die Modell-Runner schreiben eigene Protokolle. Ein fehlgeschlagener Ladevorgang oder eine fehlgeschlagene Generierung wird deshalb oft dort erklärt und nicht im Server-Protokoll.",
+ path: "Speicherort",
+ pathCopy: "Pfad kopieren",
+ refreshSection: "Aktualisierung",
+ mode: "Modus",
+ modeLive: "Live",
+ modeInterval: "Alle 3 Sekunden",
+ modeManual: "Manuell",
+ refreshNow: "Jetzt aktualisieren",
+ privacyNote: "Zugangsdaten werden in dieser Ansicht maskiert. In der Datei auf dem Datenträger sind sie nicht maskiert.",
+ copyVisible: "Sichtbares Protokoll kopieren",
+ empty: "Es wurde noch nichts protokolliert.",
+ disabled: "Die Protokollierung in eine Datei ist deaktiviert (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "Es wurde keine Protokolldatei gefunden.",
+ unreadable: "Die Protokolldatei konnte nicht gelesen werden.",
+ timeout: "Die Protokollanfrage hat das Zeitlimit uberschritten. Der Server ist moglicherweise nicht erreichbar.",
+ droppedNotice: "Einige Zeilen wurden übersprungen: Das Protokoll wurde schneller geschrieben, als es gelesen werden konnte.",
+ morePending: "Weitere Zeilen werden noch gelesen; sie erscheinen bei der nachsten Aktualisierung.",
+ staleSession: "Die Protokollierung in Dateien ist deaktiviert, daher ist dies eine fruhere Sitzung und wird nicht aktualisiert.",
+ keywords: "Fehlersuche Debugging Protokoll Protokolle Log Logs Fehler Absturz Stacktrace Diagnose Problembehebung debug",
+ },
voice: {
title: "Sprachfunktionen",
description: "Mikrofon, Diktat, Spracherkennung und Vorlesen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 8bc2ed0f9cd..728e389dff8 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -152,8 +152,35 @@ export const en = {
data: "Data",
apiKeys: "API",
agents: "Agents",
+ debugging: "Logs",
about: "About",
},
+ debugging: {
+ logSection: "Log file",
+ source: "Log file",
+ sourceHint: "The model runners write their own logs, so a failed load or generation is often explained there rather than in the server log.",
+ path: "Location",
+ pathCopy: "Copy path",
+ refreshSection: "Refresh",
+ mode: "Mode",
+ modeLive: "Live",
+ modeInterval: "Every 3 seconds",
+ modeManual: "Manual",
+ refreshNow: "Refresh now",
+ privacyNote: "Credentials are masked in this view. The file on disk is not masked.",
+ copyVisible: "Copy visible log",
+ empty: "Nothing has been logged yet.",
+ disabled: "File logging is turned off (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "No log file was found.",
+ unreadable: "The log file could not be read.",
+ timeout: "The log request timed out. The server may be unreachable.",
+ droppedNotice: "Some lines were skipped: the log was written faster than it could be read.",
+ morePending: "More lines are still being read; they arrive on the next refresh.",
+ staleSession: "File logging is turned off, so this is an earlier session and will not update.",
+ // Not rendered: extra terms the settings search matches this tab on, so
+ // the pane is still reachable by searching for debug or an error.
+ keywords: "debug debugging log logs error errors crash traceback stack trace troubleshoot diagnostics failed",
+ },
voice: {
title: "Voice",
description: "Microphone, dictation, speech-to-text and read-aloud",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 38056302c97..4ca9eaed104 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -157,8 +157,33 @@ export const es = {
about: "Acerca de",
data: "Datos",
agents: "Agentes",
+ debugging: "Registros",
voice: "Voz",
},
+ debugging: {
+ logSection: "Archivo de registro",
+ source: "Archivo de registro",
+ sourceHint: "Los ejecutores de modelos escriben sus propios registros, así que un fallo al cargar o al generar suele explicarse ahí y no en el registro del servidor.",
+ path: "Ubicación",
+ pathCopy: "Copiar ruta",
+ refreshSection: "Actualización",
+ mode: "Modo",
+ modeLive: "En vivo",
+ modeInterval: "Cada 3 segundos",
+ modeManual: "Manual",
+ refreshNow: "Actualizar ahora",
+ privacyNote: "Las credenciales se enmascaran en esta vista. El archivo en disco no está enmascarado.",
+ copyVisible: "Copiar el registro visible",
+ empty: "Todavía no se ha registrado nada.",
+ disabled: "El registro en archivo está desactivado (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "No se encontró ningún archivo de registro.",
+ unreadable: "No se pudo leer el archivo de registro.",
+ timeout: "La solicitud del registro agoto el tiempo de espera. Puede que el servidor no este accesible.",
+ droppedNotice: "Se omitieron algunas líneas: el registro se escribió más rápido de lo que se podía leer.",
+ morePending: "Aun se estan leyendo mas lineas; llegaran en la proxima actualizacion.",
+ staleSession: "El registro en archivo esta desactivado, por lo que esta es una sesion anterior y no se actualizara.",
+ keywords: "depuracion depurar registro registros log logs error errores fallo traza diagnostico solucion de problemas debug",
+ },
voice: {
title: "Voz",
description: "Micrófono, dictado, voz a texto y lectura en voz alta",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index f23d133152d..d440340688c 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -158,8 +158,33 @@ export const fr = {
about: "À propos",
data: "Données",
agents: "Agents",
+ debugging: "Journaux",
voice: "Voix",
},
+ debugging: {
+ logSection: "Fichier journal",
+ source: "Fichier journal",
+ sourceHint: "Les exécuteurs de modèles écrivent leurs propres journaux : un chargement ou une génération en échec y est donc souvent expliqué plutôt que dans le journal du serveur.",
+ path: "Emplacement",
+ pathCopy: "Copier le chemin",
+ refreshSection: "Actualisation",
+ mode: "Mode",
+ modeLive: "En direct",
+ modeInterval: "Toutes les 3 secondes",
+ modeManual: "Manuel",
+ refreshNow: "Actualiser maintenant",
+ privacyNote: "Les identifiants sont masqués dans cette vue. Dans le fichier sur le disque, ils ne le sont pas.",
+ copyVisible: "Copier le journal visible",
+ empty: "Rien n'a encore été consigné.",
+ disabled: "La journalisation dans un fichier est désactivée (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "Aucun fichier journal n'a été trouvé.",
+ unreadable: "Le fichier journal n'a pas pu être lu.",
+ timeout: "La demande du journal a expire. Le serveur est peut-etre injoignable.",
+ droppedNotice: "Certaines lignes ont été ignorées : le journal a été écrit plus vite qu'il ne pouvait être lu.",
+ morePending: "D'autres lignes sont encore en cours de lecture ; elles arriveront au prochain rafraichissement.",
+ staleSession: "La journalisation dans un fichier est desactivee : il s'agit d'une session anterieure, qui ne sera pas mise a jour.",
+ keywords: "debogage deboguer journal journaux log logs erreur erreurs plantage trace diagnostic depannage debug",
+ },
voice: {
title: "Voix",
description: "Microphone, dictée, reconnaissance vocale et lecture à voix haute",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index f65bfc68f9b..426bc4daa33 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -157,8 +157,33 @@ export const hi = {
about: "परिचय",
data: "डेटा",
agents: "एजेंट",
+ debugging: "लॉग",
voice: "आवाज़",
},
+ debugging: {
+ logSection: "लॉग फ़ाइल",
+ source: "लॉग फ़ाइल",
+ sourceHint: "मॉडल रनर अपने अलग लॉग लिखते हैं, इसलिए लोड या जनरेशन विफल होने का कारण अक्सर सर्वर लॉग के बजाय वहीं मिलता है।",
+ path: "स्थान",
+ pathCopy: "पथ कॉपी करें",
+ refreshSection: "रिफ़्रेश",
+ mode: "मोड",
+ modeLive: "लाइव",
+ modeInterval: "हर 3 सेकंड",
+ modeManual: "मैन्युअल",
+ refreshNow: "अभी रिफ़्रेश करें",
+ privacyNote: "इस दृश्य में क्रेडेंशियल छिपा दिए जाते हैं। डिस्क पर मौजूद फ़ाइल में वे नहीं छिपाए जाते।",
+ copyVisible: "दिख रहा लॉग कॉपी करें",
+ empty: "अभी तक कुछ भी लॉग नहीं हुआ है।",
+ disabled: "फ़ाइल में लॉगिंग बंद है (UNSLOTH_STUDIO_NO_FILE_LOG=1)।",
+ missing: "कोई लॉग फ़ाइल नहीं मिली।",
+ unreadable: "लॉग फ़ाइल पढ़ी नहीं जा सकी।",
+ timeout: "लॉग अनुरोध का समय समाप्त हो गया। सर्वर तक पहुंच नहीं हो पा रही है।",
+ droppedNotice: "कुछ पंक्तियाँ छोड़ दी गईं: लॉग इतनी तेज़ी से लिखा गया कि उसे पढ़ा नहीं जा सका।",
+ morePending: "और पंक्तियां अभी पढ़ी जा रही हैं; वे अगले रिफ्रेश पर आएंगी।",
+ staleSession: "फ़ाइल लॉगिंग बंद है, इसलिए यह पुराना सत्र है और अपडेट नहीं होगा।",
+ keywords: "डिबग डिबगिंग लॉग त्रुटि गड़बड़ी क्रैश ट्रेसबैक निदान समस्या निवारण debug log logs error",
+ },
voice: {
title: "आवाज़",
description: "माइक्रोफ़ोन, डिक्टेशन, स्पीच-टू-टेक्स्ट और ज़ोर से पढ़ना",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index a9b2b81f19e..00d19600a88 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -122,8 +122,33 @@ export const it = {
data: "Dati",
apiKeys: "API",
agents: "Agenti",
+ debugging: "Log",
about: "Informazioni",
},
+ debugging: {
+ logSection: "File di log",
+ source: "File di log",
+ sourceHint: "I runner dei modelli scrivono i propri log, quindi un caricamento o una generazione non riusciti sono spesso spiegati lì anziché nel log del server.",
+ path: "Posizione",
+ pathCopy: "Copia il percorso",
+ refreshSection: "Aggiornamento",
+ mode: "Modalità",
+ modeLive: "In tempo reale",
+ modeInterval: "Ogni 3 secondi",
+ modeManual: "Manuale",
+ refreshNow: "Aggiorna ora",
+ privacyNote: "In questa vista le credenziali sono mascherate. Nel file su disco non lo sono.",
+ copyVisible: "Copia il log visibile",
+ empty: "Non è stato ancora registrato nulla.",
+ disabled: "La registrazione su file è disattivata (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "Nessun file di log trovato.",
+ unreadable: "Non è stato possibile leggere il file di log.",
+ timeout: "La richiesta del log e scaduta. Il server potrebbe non essere raggiungibile.",
+ droppedNotice: "Alcune righe sono state saltate: il log è stato scritto più velocemente di quanto potesse essere letto.",
+ morePending: "Altre righe sono ancora in lettura; arriveranno al prossimo aggiornamento.",
+ staleSession: "La registrazione su file e disattivata, quindi questa e una sessione precedente e non verra aggiornata.",
+ keywords: "debug log logs registro registri errore errori crash traccia diagnostica risoluzione dei problemi",
+ },
voice: {
title: "Voce",
description:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 6302772ba12..61d275cc407 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -157,6 +157,31 @@ export const ja = {
voice: "音声",
data: "データ",
agents: "エージェント",
+ debugging: "ログ",
+ },
+ debugging: {
+ logSection: "ログファイル",
+ source: "ログファイル",
+ sourceHint: "モデルランナーはそれぞれ独自のログを書き出すため、読み込みや生成の失敗の理由は、サーバーログではなくそちらに記録されていることがよくあります。",
+ path: "場所",
+ pathCopy: "パスをコピー",
+ refreshSection: "更新",
+ mode: "モード",
+ modeLive: "ライブ",
+ modeInterval: "3 秒ごと",
+ modeManual: "手動",
+ refreshNow: "今すぐ更新",
+ privacyNote: "この表示では認証情報をマスクしています。ディスク上のファイルはマスクされません。",
+ copyVisible: "表示中のログをコピー",
+ empty: "まだ何も記録されていません。",
+ disabled: "ファイルへのログ出力は無効です (UNSLOTH_STUDIO_NO_FILE_LOG=1)。",
+ missing: "ログファイルが見つかりませんでした。",
+ unreadable: "ログファイルを読み取れませんでした。",
+ timeout: "ログの取得がタイムアウトしました。サーバーに接続できない可能性があります。",
+ droppedNotice: "一部の行がスキップされました。ログの書き込みが読み取りに追いつきませんでした。",
+ morePending: "さらに行を読み込み中です。次回の更新時に表示されます。",
+ staleSession: "ファイルへのログ出力が無効なため、これは以前のセッションであり更新されません。",
+ keywords: "デバッグ ログ エラー クラッシュ トレースバック スタックトレース 診断 障害 調査 debug log logs error",
},
voice: {
title: "音声",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index e6e783a3565..6f12d6c7cca 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -154,8 +154,33 @@ export const ko = {
about: "정보",
data: "데이터",
agents: "에이전트",
+ debugging: "로그",
voice: "음성",
},
+ debugging: {
+ logSection: "로그 파일",
+ source: "로그 파일",
+ sourceHint: "모델 러너는 각자 자체 로그를 기록하므로, 로드나 생성이 실패한 이유는 서버 로그가 아니라 그쪽에 남아 있는 경우가 많습니다.",
+ path: "위치",
+ pathCopy: "경로 복사",
+ refreshSection: "새로 고침",
+ mode: "모드",
+ modeLive: "실시간",
+ modeInterval: "3초마다",
+ modeManual: "수동",
+ refreshNow: "지금 새로 고침",
+ privacyNote: "이 화면에서는 자격 증명이 가려집니다. 디스크에 저장된 파일에서는 가려지지 않습니다.",
+ copyVisible: "표시된 로그 복사",
+ empty: "아직 기록된 내용이 없습니다.",
+ disabled: "파일 로깅이 꺼져 있습니다 (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "로그 파일을 찾을 수 없습니다.",
+ unreadable: "로그 파일을 읽을 수 없습니다.",
+ timeout: "로그 요청 시간이 초과되었습니다. 서버에 연결할 수 없을 수 있습니다.",
+ droppedNotice: "일부 줄이 누락되었습니다. 로그를 읽는 속도보다 기록되는 속도가 빨랐습니다.",
+ morePending: "아직 더 많은 줄을 읽고 있습니다. 다음 새로 고침에 표시됩니다.",
+ staleSession: "파일 로깅이 꺼져 있으므로 이것은 이전 세션이며 업데이트되지 않습니다.",
+ keywords: "디버그 디버깅 로그 오류 에러 충돌 스택 추적 진단 문제 해결 debug log logs error",
+ },
voice: {
title: "음성",
description: "마이크, 받아쓰기, 음성 인식 및 소리 내어 읽기",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 6018586bd2e..9cee3ce8b02 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -157,6 +157,31 @@ export const ptBR = {
voice: "Voz",
data: "Dados",
agents: "Agentes",
+ debugging: "Registros",
+ },
+ debugging: {
+ logSection: "Arquivo de log",
+ source: "Arquivo de log",
+ sourceHint: "Os executores de modelos gravam os próprios logs, então uma falha ao carregar ou ao gerar costuma ser explicada ali, e não no log do servidor.",
+ path: "Local",
+ pathCopy: "Copiar caminho",
+ refreshSection: "Atualização",
+ mode: "Modo",
+ modeLive: "Ao vivo",
+ modeInterval: "A cada 3 segundos",
+ modeManual: "Manual",
+ refreshNow: "Atualizar agora",
+ privacyNote: "As credenciais são mascaradas nesta visualização. No arquivo em disco elas não são mascaradas.",
+ copyVisible: "Copiar log visível",
+ empty: "Nada foi registrado ainda.",
+ disabled: "O log em arquivo está desativado (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "Nenhum arquivo de log foi encontrado.",
+ unreadable: "Não foi possível ler o arquivo de log.",
+ timeout: "A solicitacao do registro expirou. O servidor pode estar inacessivel.",
+ droppedNotice: "Algumas linhas foram ignoradas: o log foi gravado mais rápido do que era possível ler.",
+ morePending: "Mais linhas ainda estao sendo lidas; elas chegam na proxima atualizacao.",
+ staleSession: "O registro em arquivo esta desativado, portanto esta e uma sessao anterior e nao sera atualizada.",
+ keywords: "depuracao depurar registro registros log logs erro erros falha rastreamento diagnostico solucao de problemas debug",
},
voice: {
title: "Voz",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 3d8b1cd2b00..cc8681a40ec 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -156,8 +156,33 @@ export const ru = {
about: "О программе",
data: "Данные",
agents: "Агенты",
+ debugging: "Журналы",
voice: "Голос",
},
+ debugging: {
+ logSection: "Файл журнала",
+ source: "Файл журнала",
+ sourceHint: "Средства запуска моделей ведут собственные журналы, поэтому причина неудачной загрузки или генерации чаще всего указана именно в них, а не в журнале сервера.",
+ path: "Расположение",
+ pathCopy: "Копировать путь",
+ refreshSection: "Обновление",
+ mode: "Режим",
+ modeLive: "В реальном времени",
+ modeInterval: "Каждые 3 секунды",
+ modeManual: "Вручную",
+ refreshNow: "Обновить сейчас",
+ privacyNote: "В этом окне учётные данные скрыты. В файле на диске они не скрыты.",
+ copyVisible: "Копировать видимую часть журнала",
+ empty: "Пока ничего не записано.",
+ disabled: "Запись журнала в файл отключена (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
+ missing: "Файл журнала не найден.",
+ unreadable: "Не удалось прочитать файл журнала.",
+ timeout: "Истекло время ожидания запроса журнала. Возможно, сервер недоступен.",
+ droppedNotice: "Часть строк пропущена: журнал записывался быстрее, чем его удавалось читать.",
+ morePending: "Ещё строки продолжают читаться; они появятся при следующем обновлении.",
+ staleSession: "Запись журнала в файл отключена, поэтому это предыдущий сеанс, который не будет обновляться.",
+ keywords: "отладка журнал журналы лог логи ошибка ошибки сбой трассировка диагностика поиск неисправностей debug log",
+ },
voice: {
title: "Голос",
description: "Микрофон, диктовка, распознавание речи и чтение вслух",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 0f3d50e778f..2b853b8eca4 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -153,6 +153,31 @@ export const zhCN = {
voice: "语音",
data: "数据",
agents: "智能体",
+ debugging: "日志",
+ },
+ debugging: {
+ logSection: "日志文件",
+ source: "日志文件",
+ sourceHint: "模型运行器会各自写入日志,因此加载或生成失败的原因通常记录在那里,而不是服务器日志中。",
+ path: "位置",
+ pathCopy: "复制路径",
+ refreshSection: "刷新",
+ mode: "模式",
+ modeLive: "实时",
+ modeInterval: "每 3 秒",
+ modeManual: "手动",
+ refreshNow: "立即刷新",
+ privacyNote: "此视图中的凭据已被遮蔽。磁盘上的文件不会被遮蔽。",
+ copyVisible: "复制可见日志",
+ empty: "目前还没有任何日志。",
+ disabled: "文件日志已关闭 (UNSLOTH_STUDIO_NO_FILE_LOG=1)。",
+ missing: "未找到日志文件。",
+ unreadable: "无法读取日志文件。",
+ timeout: "日志请求超时。服务器可能无法访问。",
+ droppedNotice: "已跳过部分行:日志的写入速度超过了读取速度。",
+ morePending: "仍在读取更多行,它们将在下次刷新时显示。",
+ staleSession: "文件日志已关闭,因此这是较早的会话,不会更新。",
+ keywords: "调试 日志 错误 崩溃 堆栈 跟踪 诊断 排查 故障 debug log logs error",
},
voice: {
title: "语音",
diff --git a/studio/frontend/tests/debug-log-buffer.test.ts b/studio/frontend/tests/debug-log-buffer.test.ts
new file mode 100644
index 00000000000..183317cd177
--- /dev/null
+++ b/studio/frontend/tests/debug-log-buffer.test.ts
@@ -0,0 +1,317 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ DEFAULT_REFRESH_MODE,
+ EMPTY_BUFFER,
+ MAX_CLIENT_LINES,
+ applyLogChunk,
+ isPageStale,
+ nextDroppedState,
+ parseRefreshMode,
+ pollDelayMs,
+ trimBuffer,
+ isRequestTimeout,
+ withRequestTimeout,
+} from "../src/features/settings/lib/debug-log-buffer.ts";
+import { isAbort } from "../src/features/settings/lib/debug-log-error.ts";
+
+test("three seconds is the default refresh mode", () => {
+ assert.equal(DEFAULT_REFRESH_MODE, "3s");
+ assert.equal(parseRefreshMode(null), "3s");
+ assert.equal(parseRefreshMode("nonsense"), "3s");
+ assert.equal(parseRefreshMode("live"), "live");
+ assert.equal(parseRefreshMode("manual"), "manual");
+});
+
+test("each mode maps to its poll delay, manual to none", () => {
+ assert.equal(pollDelayMs("live"), 1000);
+ assert.equal(pollDelayMs("3s"), 3000);
+ assert.equal(pollDelayMs("manual"), null);
+});
+
+test("a chunk appends to what is already there", () => {
+ const first = applyLogChunk(EMPTY_BUFFER, {
+ lines: ["a", "b"],
+ cursor: "c1",
+ reset: true,
+ });
+ const second = applyLogChunk(first, {
+ lines: ["c"],
+ cursor: "c2",
+ reset: false,
+ });
+ assert.deepEqual(second.lines, ["a", "b", "c"]);
+ assert.equal(second.cursor, "c2");
+});
+
+test("a reset replaces the buffer rather than appending to it", () => {
+ const first = applyLogChunk(EMPTY_BUFFER, {
+ lines: ["old"],
+ cursor: "c1",
+ reset: true,
+ });
+ const second = applyLogChunk(first, {
+ lines: ["fresh"],
+ cursor: "c2",
+ reset: true,
+ });
+ assert.deepEqual(second.lines, ["fresh"]);
+});
+
+test("an empty chunk returns the same object so React can skip the render", () => {
+ const first = applyLogChunk(EMPTY_BUFFER, {
+ lines: ["a"],
+ cursor: "c1",
+ reset: true,
+ });
+ const second = applyLogChunk(first, {
+ lines: [],
+ cursor: "c1",
+ reset: false,
+ });
+ assert.equal(second, first);
+});
+
+test("the buffer is capped and keeps the newest lines", () => {
+ const lines = Array.from(
+ { length: MAX_CLIENT_LINES + 500 },
+ (_, i) => `line${i}`,
+ );
+ const trimmed = trimBuffer(lines);
+ assert.equal(trimmed.length, MAX_CLIENT_LINES);
+ assert.equal(trimmed[trimmed.length - 1], `line${MAX_CLIENT_LINES + 499}`);
+});
+
+test("a few enormous lines are capped by characters, not just by count", () => {
+ const lines = Array.from({ length: 40 }, () => "x".repeat(20_000));
+ const trimmed = trimBuffer(lines);
+ const chars = trimmed.reduce((total, line) => total + line.length + 1, 0);
+ assert.ok(
+ chars <= 400_000,
+ `expected the buffer under the char cap, got ${chars}`,
+ );
+ assert.ok(trimmed.length < lines.length);
+});
+
+test("appending past the cap still keeps the tail", () => {
+ let state = applyLogChunk(EMPTY_BUFFER, {
+ lines: ["first"],
+ cursor: "c1",
+ reset: true,
+ });
+ for (let i = 0; i < MAX_CLIENT_LINES + 10; i += 1) {
+ state = applyLogChunk(state, {
+ lines: [`n${i}`],
+ cursor: `c${i}`,
+ reset: false,
+ });
+ }
+ assert.equal(state.lines.length, MAX_CLIENT_LINES);
+ assert.equal(state.lines[state.lines.length - 1], `n${MAX_CLIENT_LINES + 9}`);
+ assert.ok(!state.lines.includes("first"));
+});
+
+// A request that opens and never answers is the failure the viewer has to
+// survive: the auth client hands `init` to fetch and adds no timeout, so every
+// awaited request needs the backstop, not just the tail read.
+function neverAnswers(signal: AbortSignal): Promise<never> {
+ return new Promise((_resolve, reject) => {
+ const fail = () => {
+ const error = new Error("aborted");
+ error.name = "AbortError";
+ reject(error);
+ };
+ // fetch rejects straight away when handed an already aborted signal.
+ if (signal.aborted) fail();
+ else signal.addEventListener("abort", fail);
+ });
+}
+
+test("a request that never answers is cut off by the backstop", async () => {
+ const started = Date.now();
+ await assert.rejects(
+ () => withRequestTimeout(neverAnswers, 20),
+ (error: Error) => error.name === "DebugLogTimeoutError",
+ );
+ assert.ok(Date.now() - started < 2000);
+});
+
+test("a backstop rejection is not mistaken for a caller cancellation", async () => {
+ // The timer aborts the SAME controller an unmount uses, so both arrived as an
+ // AbortError and the poll loop swallowed them alike. A hung tunnel then left
+ // the pane stale with no notice at all, which is the failure this viewer is
+ // supposed to make visible.
+ await assert.rejects(
+ () => withRequestTimeout(neverAnswers, 20),
+ (error: Error) => isRequestTimeout(error) && !isAbort(error),
+ );
+});
+
+test("a caller abort stays silent even when the backstop races it", async () => {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 10);
+ await assert.rejects(
+ () => withRequestTimeout(neverAnswers, 10, controller.signal),
+ (error: Error) => isAbort(error) && !isRequestTimeout(error),
+ );
+});
+
+test("a request that answers in time is untouched by the backstop", async () => {
+ assert.equal(await withRequestTimeout(async () => "done", 1000), "done");
+});
+
+test("the source rescan cannot freeze the poll loop behind it", async () => {
+ // The loop awaits the rescan BEFORE the tail read, so an unanswered /sources
+ // used to hang the whole tick: no poll, no reschedule, a pane that stops
+ // updating while still looking live.
+ let polls = 0;
+ let ticks = 0;
+ const rescan = async () => {
+ try {
+ await withRequestTimeout(neverAnswers, 20);
+ } catch {
+ // What refreshSources does: a failed list just leaves the picker be.
+ }
+ };
+ const poll = async () => {
+ polls += 1;
+ };
+ await new Promise<void>((resolve) => {
+ const tick = async () => {
+ ticks += 1;
+ await rescan();
+ await poll();
+ if (ticks < 2) setTimeout(tick, 1);
+ else resolve();
+ };
+ void tick();
+ });
+ assert.equal(polls, 2);
+});
+
+test("the caller's signal still cancels, and the timer does not outlive a win", async () => {
+ const controller = new AbortController();
+ const cancelled = withRequestTimeout(neverAnswers, 60_000, controller.signal);
+ controller.abort();
+ await assert.rejects(
+ () => cancelled,
+ (error: Error) => error.name === "AbortError",
+ );
+
+ // An already aborted caller signal must not let the request start unguarded.
+ const alreadyGone = new AbortController();
+ alreadyGone.abort();
+ await assert.rejects(
+ () => withRequestTimeout(neverAnswers, 60_000, alreadyGone.signal),
+ (error: Error) => error.name === "AbortError",
+ );
+
+ // A request that wins leaves nothing behind that could abort a later one.
+ let seen: AbortSignal | null = null;
+ const value = await withRequestTimeout(async (signal) => {
+ seen = signal;
+ return "ok";
+ }, 20);
+ assert.equal(value, "ok");
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ assert.equal((seen as unknown as AbortSignal).aborted, false);
+});
+
+test("a response for the source the user just left is dropped", () => {
+ // A manual refresh of A, answered after the picker moved to B.
+ assert.equal(
+ isPageStale({
+ requestSelection: 1,
+ currentSelection: 2,
+ requestSourceId: "a",
+ pageSourceId: "a",
+ }),
+ true,
+ );
+ // A -> B -> A: the id matches again, but the cursor and buffer were reset.
+ assert.equal(
+ isPageStale({
+ requestSelection: 1,
+ currentSelection: 3,
+ requestSourceId: "a",
+ pageSourceId: "a",
+ }),
+ true,
+ );
+ // The ordinary poll, and the unset source the server answers with its default.
+ assert.equal(
+ isPageStale({
+ requestSelection: 2,
+ currentSelection: 2,
+ requestSourceId: "a",
+ pageSourceId: "a",
+ }),
+ false,
+ );
+ assert.equal(
+ isPageStale({
+ requestSelection: 2,
+ currentSelection: 2,
+ requestSourceId: null,
+ pageSourceId: "server-default",
+ }),
+ false,
+ );
+ // A server that answered with a different file than the one asked for.
+ assert.equal(
+ isPageStale({
+ requestSelection: 2,
+ currentSelection: 2,
+ requestSourceId: "a",
+ pageSourceId: "b",
+ }),
+ true,
+ );
+});
+
+test("the skipped-lines warning outlives the poll that raised it", () => {
+ const dropped = nextDroppedState(false, { droppedBytes: 4096, reset: false });
+ assert.equal(dropped, true);
+ // The next quiet poll: the gap is still in the buffer, so the warning stays.
+ assert.equal(
+ nextDroppedState(dropped, { droppedBytes: 0, reset: false }),
+ true,
+ );
+ // A reset replaces everything on screen with a fresh tail.
+ assert.equal(
+ nextDroppedState(dropped, { droppedBytes: 0, reset: true }),
+ false,
+ );
+ assert.equal(
+ nextDroppedState(false, { droppedBytes: 0, reset: false }),
+ false,
+ );
+});
+
+test("the deadline fires even when the work ignores the abort", async () => {
+ // authFetch awaits refreshSession() on a 401 and hands it no signal, so
+ // aborting settled nothing: the promise stayed pending, the caller's
+ // in-flight guard stayed pinned and the pane froze. Racing the deadline is
+ // what makes the backstop a backstop.
+ const deaf = () => new Promise<never>(() => {});
+ const started = Date.now();
+ await assert.rejects(
+ () => withRequestTimeout(deaf, 20),
+ (error: Error) => isRequestTimeout(error),
+ );
+ assert.ok(Date.now() - started < 2000);
+});
+
+test("a caller abort still reads as one when the work ignores it too", async () => {
+ const deaf = () => new Promise<never>(() => {});
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(
+ () => withRequestTimeout(deaf, 20, controller.signal),
+ (error: Error) => isAbort(error) && !isRequestTimeout(error),
+ );
+});
diff --git a/studio/frontend/tests/debug-log-source-gone.test.ts b/studio/frontend/tests/debug-log-source-gone.test.ts
new file mode 100644
index 00000000000..b260801fdd6
--- /dev/null
+++ b/studio/frontend/tests/debug-log-source-gone.test.ts
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A source id stops being enumerated once the file is removed or pushed out of
+// the per-family window. The backend answers that with a 404 (every other state
+// is a 200 with a status) so the picker can rebuild itself, which only works if
+// the status survives the client.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ DebugLogRequestError,
+ isAbort,
+ isLogSourceGone,
+} from "../src/features/settings/lib/debug-log-error.ts";
+
+test("a gone source is the one failure the picker can recover from", () => {
+ const gone = new DebugLogRequestError("Unknown log source.", 404);
+ assert.equal(isLogSourceGone(gone), true);
+ assert.equal(gone.name, "DebugLogRequestError");
+ assert.equal(gone.message, "Unknown log source.");
+ assert.ok(gone instanceof Error);
+});
+
+test("every other failure is reported rather than retried", () => {
+ for (const status of [400, 401, 403, 500, 502, 503]) {
+ assert.equal(
+ isLogSourceGone(new DebugLogRequestError("boom", status)),
+ false,
+ );
+ }
+ // A plain Error is what the sources call and anything unexpected throws.
+ assert.equal(isLogSourceGone(new Error("Could not read the log.")), false);
+ assert.equal(isLogSourceGone(undefined), false);
+ assert.equal(isLogSourceGone(null), false);
+ assert.equal(isLogSourceGone("404"), false);
+});
+
+test("an aborted poll is not a failure at all", () => {
+ const abort = new Error("aborted");
+ abort.name = "AbortError";
+ assert.equal(isAbort(abort), true);
+ assert.equal(isAbort(new Error("nope")), false);
+ assert.equal(isAbort(undefined), false);
+ // Unmounting the tab must not be reported as a log-source problem.
+ assert.equal(isLogSourceGone(abort), false);
+});