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: add a Download all logs button to Settings > Logs (#10719)

Daniel Hana19c9bda876e
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 01fb3fd3b9b..efae98c47a8 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -14,6 +14,8 @@ from typing import Any, Literal, Optional, get_args
from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, Depends, Header, HTTPException, Request
+from fastapi.responses import StreamingResponse
+from starlette.background import BackgroundTask
from pydantic import (
BaseModel,
ConfigDict,
@@ -3495,6 +3497,12 @@ class DebugLogSourcesResponse(BaseModel):
sources: list[DebugLogSourceModel]
default_source_id: Optional[str] = None
file_logging_disabled: bool = False
+ # Where the logs actually live, so a caller does not have to guess. The
+ # desktop "Open logs folder" button otherwise falls back to a hard-coded
+ # ~/.unsloth/studio, which is wrong whenever UNSLOTH_STUDIO_HOME or
+ # STUDIO_HOME is set AND there is no readable log to take a path from.
+ # Additive and optional: an older client ignores it.
+ log_root: Optional[str] = None
class DebugLogResponse(BaseModel):
@@ -3530,10 +3538,14 @@ def get_debug_log_sources(
from utils import debug_log_sources
sources = debug_log_sources.list_sources()
+ # The first candidate root is the one the walk prefers, so it is the
+ # directory a user opening "the log folder" expects to land in.
+ roots = debug_log_sources.candidate_roots()
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(),
+ log_root = str(roots[0]) if roots else None,
)
@@ -3604,6 +3616,75 @@ def get_debug_log(
)
+# One build at a time, process-wide. The route is a sync `def`, so it runs in
+# the 40-thread anyio pool shared with every other sync endpoint; a few
+# concurrent exports starve it, and anyio cannot cancel a running thread, so it
+# does not recover. A second caller is told to wait rather than queued.
+_DEBUG_LOG_EXPORT_LOCK = threading.Semaphore(1)
+
+
+@_owner_settings_router.get("/debug/logs/export")
+def export_debug_logs(
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session),
+) -> StreamingResponse:
+ """Every log the picker lists, redacted, as one ZIP.
+
+ Same two dependencies as the routes above: a bundle of logs and the paths
+ they came from is UI-operator material, so an API-key or keyless caller is
+ refused. On `_owner_settings_router` for the same reason they are, since
+ that router carries `_require_installation_owner`: on the bare `router` the
+ BUNDLE would be reachable by an account refused each log individually.
+
+ Built before the response exists rather than inside the generator, so a
+ failure is a 500 instead of a truncated download.
+ """
+ from utils import debug_log_export
+
+ if not _DEBUG_LOG_EXPORT_LOCK.acquire(blocking = False):
+ raise HTTPException(
+ status_code = 429,
+ detail = "A log export is already running. Wait for it to finish and try again.",
+ )
+ try:
+ archive = debug_log_export.build_log_archive()
+ finally:
+ _DEBUG_LOG_EXPORT_LOCK.release()
+
+ stamp = time.strftime("%Y%m%d-%H%M%S")
+
+ def _chunks():
+ try:
+ while True:
+ chunk = archive.read(debug_log_export.STREAM_CHUNK_BYTES)
+ if not chunk:
+ break
+ yield chunk
+ finally:
+ archive.close()
+
+ return StreamingResponse(
+ _chunks(),
+ media_type = "application/zip",
+ headers = {
+ # Neither shipping caller reads this back: the browser names the Blob
+ # itself and the desktop path names the file in Rust. It is here for
+ # a curl or address-bar caller, so do not assume the button uses it.
+ "Content-Disposition": f'attachment; filename="unsloth-logs-{stamp}.zip"',
+ # A stable authenticated GET is otherwise cacheable: the archive could
+ # outlive the download in the on-disk cache, and a second export could
+ # be answered from it rather than from the logs as they are now.
+ # `no-store` not `no-cache`: it must not be WRITTEN, not revalidated.
+ "Cache-Control": "no-store, no-cache, must-revalidate, private",
+ "Pragma": "no-cache",
+ },
+ # Belt and braces with the `finally` above: on a client abort Starlette
+ # cancels the task group without raising GeneratorExit, so that `finally`
+ # waits for a cyclic GC pass, holding up to SPOOL_MAX_BYTES meanwhile.
+ background = BackgroundTask(archive.close),
+ )
+
+
router.include_router(_account_settings_router)
router.include_router(_shared_settings_router)
router.include_router(_owner_settings_router)
diff --git a/studio/backend/tests/test_debug_log_export.py b/studio/backend/tests/test_debug_log_export.py
new file mode 100644
index 00000000000..584cfa64f03
--- /dev/null
+++ b/studio/backend/tests/test_debug_log_export.py
@@ -0,0 +1,845 @@
+# 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 "Download all logs" bundle. Two things have to hold whatever the host
+looks like: nothing in the archive names a path on this machine, and nothing in
+it is a credential. Everything else -- a log that rotates, is swapped for a
+link, or holds one record bigger than the budget -- is a warning, not a failed
+download."""
+
+from __future__ import annotations
+
+import io
+import os
+import sys
+import time
+import zipfile
+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
+from utils import debug_log_export, debug_log_sources
+
+
+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"
+ # newline = "": `write_text` otherwise translates \n to \r\n on Windows, which
+ # moves every byte offset the seek and budget tests below compute.
+ path.write_text(body, encoding = "utf-8", newline = "")
+ return path
+
+
+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", newline = "")
+ return path
+
+
+def _members() -> dict[str, bytes]:
+ """Build a bundle and read it back. testzip() on every call, so a member
+ left half written by a mid-read failure cannot pass unnoticed."""
+ handle = debug_log_export.build_log_archive()
+ try:
+ with zipfile.ZipFile(handle) as archive:
+ assert archive.testzip() is None
+ return {name: archive.read(name) for name in archive.namelist()}
+ finally:
+ handle.close()
+
+
+def test_member_names_are_relative_and_name_no_directory():
+ server = _seed_server_log()
+ llama = _seed_llama_log()
+ members = _members()
+ assert set(members) == {f"server/{server.name}", f"llama-server/{llama.name}"}
+ home = str(Path(os.environ["UNSLOTH_STUDIO_HOME"]))
+ for name in members:
+ assert not name.startswith("/")
+ assert ".." not in name
+ assert home not in name
+ assert "\\" not in name
+ # family + basename, and nothing else.
+ assert name.count("/") == 1
+
+
+def test_the_bundle_is_an_archive_the_stdlib_accepts():
+ _seed_server_log("a line\n")
+ handle = debug_log_export.build_log_archive()
+ try:
+ assert handle.tell() == 0
+ with zipfile.ZipFile(handle) as archive:
+ assert archive.testzip() is None
+ info = archive.infolist()[0]
+ assert info.compress_type == zipfile.ZIP_DEFLATED
+ finally:
+ handle.close()
+
+
+def test_a_planted_token_is_masked_in_the_archive():
+ """The whole point of reusing the viewer's redactor: what the tab would not
+ show you, the download does not carry either."""
+ path = _seed_server_log(
+ "loading with HF_TOKEN=hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345\n"
+ "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg\n"
+ )
+ members = _members()
+ body = members[f"server/{path.name}"].decode("utf-8")
+ assert "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345" not in body
+ assert "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefg" not in body
+ assert "<redacted>" in body
+ # Not just that member: every member. Scanning the raw archive bytes instead
+ # would prove nothing, since ZIP_DEFLATED means a cleartext token does not
+ # appear in them either way.
+ for name, content in members.items():
+ assert b"hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345" not in content, name
+
+
+def test_a_source_swapped_for_a_symlink_after_enumeration_is_refused(monkeypatch, tmp_path):
+ """The enumeration walk refuses an escaping link, but that ran earlier.
+ Anything can replace the entry before the export opens it."""
+ path = _seed_server_log("ordinary line\n")
+ # Not `secret`, for the CodeQL reason on the AWS test below.
+ link_target = tmp_path / "id_rsa"
+ link_target.write_text("PRIVATE KEY MATERIAL\n", encoding = "utf-8")
+ enumerate_sources = debug_log_sources.list_sources
+
+ def swap_then_return():
+ sources = enumerate_sources()
+ path.unlink()
+ path.symlink_to(link_target)
+ return sources
+
+ monkeypatch.setattr(debug_log_sources, "list_sources", swap_then_return)
+
+ members = _members()
+ assert f"server/{path.name}" not in members
+ for body in members.values():
+ assert b"PRIVATE KEY MATERIAL" not in body
+ warnings = members[debug_log_export.WARNINGS_MEMBER].decode("utf-8")
+ assert warnings.startswith(f"server/{path.name}: OSError (errno ")
+ assert str(tmp_path) not in warnings
+
+
+def test_a_file_replaced_between_the_stat_and_the_open_is_refused(monkeypatch):
+ """The narrow window the fstat compare exists for.
+
+ lstat says regular file, the entry is replaced, and the open lands on
+ something else. Comparing the descriptor's device and inode against the
+ stat we just took is what catches it.
+ """
+ path = _seed_server_log("ordinary line\n")
+ real_open = os.open
+ swapped: list[bool] = []
+
+ def open_after_a_swap(*args, **kwargs):
+ if not swapped and args and str(args[0]).endswith(path.name):
+ swapped.append(True)
+ # Renamed over the entry rather than unlinked and rewritten in place:
+ # freeing an inode and immediately creating a file in the same
+ # directory can hand the number straight back, which leaves the
+ # device/inode compare nothing to see and the test asserting on a
+ # coincidence. A rename of a file that already exists alongside is a
+ # different inode by construction, on every filesystem.
+ impostor = path.parent / "impostor.log"
+ impostor.write_text("SOMEONE ELSE'S FILE\n", encoding = "utf-8")
+ os.replace(impostor, path)
+ return real_open(*args, **kwargs)
+
+ monkeypatch.setattr(os, "open", open_after_a_swap)
+
+ members = _members()
+ assert swapped
+ for body in members.values():
+ assert b"SOMEONE ELSE'S FILE" not in body
+ warnings = members[debug_log_export.WARNINGS_MEMBER].decode("utf-8")
+ assert warnings.startswith(f"server/{path.name}: OSError (errno ")
+
+
+def test_a_file_truncated_mid_export_warns_without_naming_a_directory(monkeypatch):
+ """A log that rotates under the read costs its own tail, not the bundle.
+
+ The warning names the member, never `str(exc)`: OSError.__str__ appends the
+ filename, which would put a host path in the archive.
+ """
+ path = _seed_server_log("first line\nsecond line\n")
+ real_redact = debug_log_export.redact_log_text
+ truncated = []
+
+ def redact_then_truncate(text: str) -> str:
+ if not truncated:
+ truncated.append(True)
+ os.truncate(path, 0)
+ return real_redact(text)
+
+ monkeypatch.setattr(debug_log_export, "redact_log_text", redact_then_truncate)
+
+ members = _members()
+ warnings = members[debug_log_export.WARNINGS_MEMBER].decode("utf-8").strip()
+ assert warnings.startswith(f"server/{path.name}: OSError (errno ")
+ assert str(path.parent) not in warnings
+ # family + basename, so the only separator in the line is the family's.
+ assert warnings.count("/") == 1
+ # What was copied before the failure is kept.
+ assert members[f"server/{path.name}"].decode("utf-8").startswith("first line")
+
+
+def test_an_oversized_record_is_omitted_whole_rather_than_split():
+ """Splitting could cut a key away from its value, and the redactor is
+ anchored on the two being adjacent."""
+ filler = "X" * (debug_log_export.MAX_RECORD_BYTES + 5_000)
+ path = _seed_server_log(f"before\n{filler}\nafter\n")
+ body = _members()[f"server/{path.name}"].decode("utf-8")
+ assert body == f"before\n{debug_log_export.OVERSIZED_MARKER}\nafter\n"
+
+
+def test_an_oversized_record_at_end_of_file_is_still_omitted():
+ filler = "Y" * (debug_log_export.MAX_RECORD_BYTES + 5_000)
+ path = _seed_server_log(f"before\n{filler}")
+ body = _members()[f"server/{path.name}"].decode("utf-8")
+ assert body == f"before\n{debug_log_export.OVERSIZED_MARKER}\n"
+
+
+def test_a_record_with_no_trailing_newline_is_kept():
+ path = _seed_server_log("no trailing newline")
+ assert _members()[f"server/{path.name}"] == b"no trailing newline\n"
+
+
+def test_an_empty_export_is_still_a_valid_archive():
+ assert _members() == {}
+
+
+ ("label", "expected"),
+ [
+ ("server-1.log", "server-1.log"),
+ ("../../etc/passwd", "passwd"),
+ ("/var/log/syslog", "syslog"),
+ (r"C:\Users\me\tauri.log", "tauri.log"),
+ ("..", "log"),
+ ("", "log"),
+ ],
+)
+def test_a_label_can_never_become_a_path(label, expected):
+ assert debug_log_export._safe_basename(label) == expected
+
+
+def test_duplicate_labels_are_uniquified_by_a_loop():
+ """One studio home per spelling means two families can hold the same
+ filename, and a duplicated member extracts as whichever entry the tool
+ reaches last."""
+ used: set[str] = set()
+ assert debug_log_export._member_name("server", "a.log", used) == "server/a.log"
+ assert debug_log_export._member_name("server", "a.log", used) == "server/a-2.log"
+ assert debug_log_export._member_name("server", "a.log", used) == "server/a-3.log"
+ # The first candidate being taken by a real file is why it re-checks.
+ used.add("server/b-2.log")
+ assert debug_log_export._member_name("server", "b.log", used) == "server/b.log"
+ assert debug_log_export._member_name("server", "b.log", used) == "server/b-3.log"
+ # A label with no extension keeps its suffix at the end.
+ assert debug_log_export._member_name("desktop-shell", "tauri", used) == "desktop-shell/tauri"
+ assert debug_log_export._member_name("desktop-shell", "tauri", used) == "desktop-shell/tauri-2"
+
+
+def test_two_labels_differing_only_in_case_do_not_extract_over_each_other():
+ """The volume the archive is EXTRACTED on decides what collides: Windows and
+ default APFS fold case, so two members that differ only in case land on top
+ of each other there. The member keeps its spelling; only the key is folded.
+ """
+ used: set[str] = set()
+ assert debug_log_export._member_name("server", "s.log", used) == "server/s.log"
+ assert debug_log_export._member_name("server", "S.log", used) == "server/S-2.log"
+ assert debug_log_export._member_name("server", "s.LOG", used) == "server/s-3.LOG"
+ # And a member already present in the ZIP under a different case is still
+ # seen as taken.
+ used.add("server/t-2.log")
+ assert debug_log_export._member_name("server", "T.log", used) == "server/T.log"
+ assert debug_log_export._member_name("server", "t.log", used) == "server/t-3.log"
+
+
+def _filesystem_folds_case(directory: Path) -> bool:
+ """Whether this filesystem treats two spellings as one file.
+
+ Windows and default APFS do, which is the whole reason `_member_name` folds
+ its collision key -- and also why the two-file scenario below cannot be
+ BUILT there: the second write lands on the first file.
+ """
+ probe = directory / "CaseProbe.tmp"
+ try:
+ probe.write_text("x", encoding = "utf-8")
+ return (directory / "caseprobe.tmp").exists()
+ finally:
+ probe.unlink(missing_ok = True)
+
+
+def test_two_logs_differing_only_in_case_both_survive_the_round_trip(monkeypatch):
+ """The same property end to end, since that is where it would be lost.
+
+ `list_sources` is stubbed rather than driven off the real walk because the
+ enumeration is where the platforms differ: `Path.glob` is case-sensitive on
+ POSIX and case-INSENSITIVE on Windows, so the second spelling below is
+ invisible to the walk on this host and enumerated on the machine where the
+ collision actually bites. Stubbing is what lets a Linux runner exercise the
+ Windows shape; the files underneath are real, and so is the archive.
+ """
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ if _filesystem_folds_case(directory):
+ # The two files would be one file here, so there is nothing to pack
+ # twice. The property still holds and is covered without a filesystem by
+ # test_two_labels_differing_only_in_case_do_not_extract_over_each_other,
+ # which is the test that matters on exactly these platforms.
+ pytest.skip("case-insensitive filesystem cannot hold both spellings")
+ spellings = {
+ "server-20260101-120000-pid1.log": "lowercase spelling\n",
+ "Server-20260101-120000-pid1.log": "uppercase spelling\n",
+ }
+ sources = []
+ for name, body in spellings.items():
+ path = directory / name
+ path.write_text(body, encoding = "utf-8")
+ sources.append(
+ debug_log_sources.LogSource(
+ id = f"server:{name}",
+ family = "server",
+ label = name,
+ realpath = str(path),
+ size_bytes = path.stat().st_size,
+ modified_at = 0.0,
+ is_current = False,
+ )
+ )
+ monkeypatch.setattr(debug_log_sources, "list_sources", lambda: sources)
+
+ members = _members()
+ # Distinct after folding, so no case-insensitive extractor can collapse them.
+ folded = [name.lower() for name in members if name != debug_log_export.WARNINGS_MEMBER]
+ assert len(folded) == len(set(folded)), sorted(members)
+ bodies = b"".join(members.values())
+ assert b"lowercase spelling" in bodies
+ assert b"uppercase spelling" in bodies
+
+
+def test_the_route_streams_an_attachment(client):
+ path = _seed_server_log("route line\n")
+ response = client.get("/api/settings/debug/logs/export")
+ assert response.status_code == 200
+ assert response.headers["content-type"] == "application/zip"
+ disposition = response.headers["content-disposition"]
+ assert disposition.startswith('attachment; filename="unsloth-logs-')
+ assert disposition.endswith('.zip"')
+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
+ assert archive.testzip() is None
+ assert archive.read(f"server/{path.name}") == b"route line\n"
+
+
+def test_the_archive_is_never_written_to_the_browser_cache(client):
+ """A stable authenticated GET returning an attachment is cacheable unless it
+ says otherwise: the archive could outlive the download on disk, and a second
+ export could be answered from cache rather than from the logs as they are
+ now. `no-store` because it must not be written down at all.
+ """
+ _seed_server_log("cacheable?\n")
+ response = client.get("/api/settings/debug/logs/export")
+ assert response.status_code == 200
+ directives = {
+ part.strip().lower() for part in response.headers.get("cache-control", "").split(",")
+ }
+ assert "no-store" in directives, response.headers.get("cache-control")
+ assert "private" in directives, response.headers.get("cache-control")
+
+
+def test_the_export_is_owner_gated_exactly_like_the_routes_it_sits_beside():
+ """Per-account isolation put the two debug log routes behind
+ `_require_installation_owner`. The bundle has to sit behind the same guard,
+ or a non-owner account on a shared install can download EVERY log on the
+ host while being refused each one individually -- which is the wrong way
+ round. Asserted against the sibling routes rather than by naming the router,
+ so the three cannot drift apart again.
+ """
+ routers = {}
+ for path in ("/debug/logs", "/debug/logs/sources", "/debug/logs/export"):
+ for name in ("router", "_owner_settings_router"):
+ candidate = getattr(settings_route, name)
+ # getattr, not `route.path`: `.routes` also holds `_IncludedRouter`
+ # entries with no path, which raise on macOS and Windows runners while
+ # passing on this one purely by FastAPI version.
+ if any(getattr(route, "path", None) == path for route in candidate.routes):
+ routers[path] = name
+ assert routers["/debug/logs/export"] == routers["/debug/logs"] == routers["/debug/logs/sources"]
+ owner_router = settings_route._owner_settings_router
+ assert routers["/debug/logs/export"] == "_owner_settings_router"
+ # And that router is the one carrying the owner check.
+ assert any(
+ getattr(dependency.dependency, "__name__", "") == "_require_installation_owner"
+ for dependency in owner_router.dependencies
+ )
+
+
+def test_an_api_key_session_cannot_download_the_logs():
+ """A bundle of every log on the host is UI-operator material, exactly like
+ the single-file read next to it."""
+ 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/export").status_code == 403
+
+
+def test_a_log_larger_than_the_tail_keeps_its_end(monkeypatch):
+ """The 10-per-family cap bounds FILES, not bytes: the session log is never
+ rotated and runs to gigabytes, so the tail is the part worth carrying."""
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 512)
+ path = _seed_server_log("".join(f"line {index}\n" for index in range(400)))
+ assert path.stat().st_size > 512
+ body = _members()[f"server/{path.name}"].decode()
+ assert "skipped the first" in body.splitlines()[0]
+ # The end survived and the beginning is what went.
+ assert "line 399" in body
+ assert "line 0\n" not in body
+
+
+def test_a_truncated_log_never_starts_in_the_middle_of_a_record(monkeypatch):
+ """A read that begins mid-record hands out a credential whose key was left
+ behind in the skipped part, which is exactly what redaction relies on."""
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 300)
+ # Sized so the cut lands inside the secret-bearing record rather than on a
+ # boundary: the key is before the seek point, the value after it.
+ filler = "".join(f"padding line {index}\n" for index in range(40))
+ path = _seed_server_log(
+ f"{filler}HF_TOKEN=hf_abcdefghijklmnopqrstuvwxyz012345\n" + "tail line\n" * 12
+ )
+ body = _members()[f"server/{path.name}"].decode()
+ assert "hf_abcdefghijklmnopqrstuvwxyz012345" not in body
+ # Whatever survived is whole records only.
+ for line in body.splitlines()[1:]:
+ assert line == "" or line.startswith(("padding line", "tail line", "HF_TOKEN=", "["))
+
+
+def test_the_total_budget_names_what_it_left_out(monkeypatch):
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 64)
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 64)
+ _seed_server_log("server line\n" * 20)
+ _seed_llama_log("llama line\n" * 20)
+ members = _members()
+ warnings = members[debug_log_export.WARNINGS_MEMBER].decode()
+ assert "budget" in warnings or "no complete record" in warnings
+
+
+def test_a_log_inside_the_tail_is_not_truncated_or_warned_about():
+ path = _seed_server_log("short enough\n")
+ members = _members()
+ assert members[f"server/{path.name}"] == b"short enough\n"
+ assert debug_log_export.WARNINGS_MEMBER not in members
+
+
+def test_a_record_cut_by_the_allowance_is_marked_not_presented_as_whole():
+ """A read that stops on the ALLOWANCE leaves the front of a record, which
+ would read as a complete line. It is also the one place a credential reaches
+ the archive: `redact_log_text` needs several characters of value, so a cut
+ just past `password=` ships the first few in the clear. At EOF the same
+ trailing bytes ARE a whole record, so the two must not be treated alike.
+ """
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / "server-20260101-120000-pid1.log"
+ path.write_bytes(b"password=SECRETVALUE12345\n")
+
+ handle, fd = debug_log_export._open_verified(str(path))
+ with handle:
+ # 13 bytes stops inside the value, past the key.
+ cut = list(debug_log_export._redacted_records(handle, fd, 13, time.monotonic() + 30))
+ assert cut == [debug_log_export.CUT_MARKER], cut
+ assert not any("SECR" in record for record in cut)
+
+ # The same file read to its end keeps its last record, newline or not.
+ handle, fd = debug_log_export._open_verified(str(path))
+ with handle:
+ whole = list(debug_log_export._redacted_records(handle, fd, 1 << 20, time.monotonic() + 30))
+ assert debug_log_export.CUT_MARKER not in whole
+ assert whole and "password=" in whole[0]
+ assert "SECRETVALUE12345" not in whole[0]
+
+ # The boundary between the two, which is where marking this naively gets it
+ # wrong. An allowance landing EXACTLY on the last byte means the loop stops
+ # on the allowance and never gets the read that would report EOF -- but the
+ # record IS complete and must be kept, not marked. Asking the descriptor is
+ # what separates "the file ended here" from "there is more".
+ exact = directory / "server-20260101-120001-pid1.log"
+ exact.write_bytes(b"a whole final record with no newline")
+ handle, fd = debug_log_export._open_verified(str(exact))
+ with handle:
+ flush = list(
+ debug_log_export._redacted_records(
+ handle, fd, exact.stat().st_size, time.monotonic() + 30
+ )
+ )
+ assert flush == ["a whole final record with no newline"], flush
+
+
+def test_a_source_that_cannot_get_a_useful_tail_blames_the_budget_not_the_file(monkeypatch):
+ """With a handful of bytes left there is no room for a whole record, and
+ saying "no complete record in the last 4 bytes" reads as a fault in the log.
+ The budget is what ran out, so that is what the warning says -- and because
+ the no-boundary path deliberately does not spend `remaining`, the wrong
+ message would otherwise repeat for every source after it."""
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 4)
+ _seed_server_log("a line that does not fit\n")
+ _seed_llama_log("another line that does not fit\n")
+
+ warnings = _members()[debug_log_export.WARNINGS_MEMBER].decode()
+ assert "export size budget reached" in warnings
+ assert "no complete record" not in warnings, warnings
+
+
+def test_the_budget_is_spread_across_families_not_drained_by_one(monkeypatch):
+ """list_sources groups by family, so consuming it in order spends the whole
+ budget on the server logs and ships a bundle with no runner logs at all."""
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 200)
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 100)
+ _seed_server_log("server line\n" * 40)
+ _seed_llama_log("llama line\n" * 40)
+ members = _members()
+ families = {name.split("/")[0] for name in members if name != debug_log_export.WARNINGS_MEMBER}
+ assert families == {"server", "llama-server"}
+
+
+def test_round_robin_keeps_the_newest_of_each_family_first():
+ def source(family, label):
+ return debug_log_sources.LogSource(
+ id = f"{family}:{label}",
+ family = family,
+ label = label,
+ realpath = label,
+ size_bytes = 0,
+ modified_at = 0.0,
+ is_current = False,
+ )
+
+ grouped = [
+ source("server", "s1"),
+ source("server", "s2"),
+ source("server", "s3"),
+ source("llama-server", "l1"),
+ source("llama-server", "l2"),
+ ]
+ assert [s.label for s in debug_log_export._newest_first_across_families(grouped)] == [
+ "s1",
+ "l1",
+ "s2",
+ "l2",
+ "s3",
+ ]
+ assert debug_log_export._newest_first_across_families([]) == []
+
+
+def test_one_log_with_no_record_boundary_does_not_abandon_the_rest(monkeypatch):
+ """A tail window holding no newline is a property of THAT file. Spending the
+ whole budget on it drops every later source, including ones that fit."""
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 1000)
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 1000)
+ _seed_server_log("header line\n" + "a" * 4000)
+ llama = _seed_llama_log("llama line\n")
+ members = _members()
+ # The unusable one is named...
+ assert "no complete record" in members[debug_log_export.WARNINGS_MEMBER].decode()
+ # ...and the one that plainly fits is still in the bundle.
+ assert members[f"llama-server/{llama.name}"] == b"llama line\n"
+
+
+def test_a_log_being_appended_to_is_still_bounded(monkeypatch):
+ """The seek bounds where the read STARTS. A live log has no end, so without
+ a ceiling the loop follows the writer -- on the one file both caps exist for."""
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 4096)
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 8192)
+ path = _seed_server_log("start\n")
+
+ real_redact = debug_log_export.redact_log_text
+ state = {"appended": False}
+
+ def grow_once(text):
+ # Append far more than the allowance while the export is mid-read.
+ if not state["appended"]:
+ state["appended"] = True
+ with path.open("a", encoding = "utf-8") as handle:
+ handle.write("appended line\n" * 20000)
+ return real_redact(text)
+
+ monkeypatch.setattr(debug_log_export, "redact_log_text", grow_once)
+ body = _members()[f"server/{path.name}"]
+ assert path.stat().st_size > 200000, "the log really did grow during the export"
+ assert len(body) <= 4096 + 128, f"read ran past the allowance: {len(body)} bytes"
+
+
+def test_a_failed_read_still_spends_its_budget(monkeypatch):
+ """Bytes already redacted and written are spent whether or not the file
+ survived to EOF."""
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 1 << 20)
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 1 << 20)
+ path = _seed_server_log("kept line\n" * 200)
+ real_redact = debug_log_export.redact_log_text
+ state = {"hits": 0}
+
+ def truncate_midway(text):
+ state["hits"] += 1
+ if state["hits"] == 50:
+ os.truncate(path, 0)
+ return real_redact(text)
+
+ monkeypatch.setattr(debug_log_export, "redact_log_text", truncate_midway)
+ members = _members()
+ warnings = members[debug_log_export.WARNINGS_MEMBER].decode()
+ assert "OSError" in warnings or "errno" in warnings
+
+
+def test_a_record_straddling_the_seek_never_leaks_its_credential(monkeypatch):
+ """The seek must resync FORWARD to a real newline however far that is.
+
+ Giving up after one probe starts the read at an arbitrary mid-record offset,
+ and `redact_log_text` is anchored on the key: a record holding an AWS secret
+ whose KEY falls before that offset and whose VALUE falls after it arrives
+ masked of nothing. An AWS secret has no prefix for a shape rule to catch, so
+ the anchor is the only defence. The offsets below are laid out so the cut
+ lands exactly between the key and its value.
+ """
+ record_cap = 4096
+ monkeypatch.setattr(debug_log_export, "MAX_RECORD_BYTES", record_cap)
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 2 * record_cap)
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 1 << 20)
+
+ # Not `secret`/`key`: CodeQL's py/clear-text-storage-sensitive-data classifies
+ # a local by NAME, so those spellings make every fixture write a new
+ # high-severity alert. The value is a synthetic AWS example.
+ planted_value = "wJalrXUtnFEMIKSECRETDENGbPxRfiCYEXAMPLEKEY"
+ anchor = 'aws_secret_access_key="'
+ head = "x" * 200
+ # Solving len(head) + 1 + lead + len(anchor) == size - record_cap for the trailer.
+ trailer = record_cap - 1 - len(planted_value) - 1
+ lead = 5000
+ straddler = "a" * lead + anchor + planted_value + '"' + "b" * trailer
+ path = _seed_server_log(f"{head}\n{straddler}\n")
+
+ size = path.stat().st_size
+ cut = size - record_cap
+ anchor_end = len(head) + 1 + lead + len(anchor)
+ # The geometry this test exists to exercise: one record spanning the seek
+ # point, cut between its key and its value.
+ assert anchor_end == cut, (anchor_end, cut)
+ assert len(head) + 1 < size - 2 * record_cap
+
+ # Either the record survives whole and is masked, or it is refused for
+ # having no boundary. What must never happen is the value arriving without
+ # its key, which is what a mid-record start produces.
+ for name, body in _members().items():
+ assert planted_value.encode() not in body, f"credential leaked into {name}"
+
+
+def test_a_tail_with_no_record_boundary_is_refused_not_read_midway(monkeypatch):
+ monkeypatch.setattr(debug_log_export, "MAX_RECORD_BYTES", 512)
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 2048)
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 1 << 20)
+ planted_value = "wJalrXUtnFEMIKSECRETDENGbPxRfiCYEXAMPLEKEY"
+ path = _seed_server_log("head\n" + "c" * 5000 + f'aws_secret_access_key="{planted_value}"')
+ members = _members()
+ assert f"server/{path.name}" not in members
+ assert "no complete record" in members[debug_log_export.WARNINGS_MEMBER].decode()
+
+
+def test_an_undecodable_filename_does_not_take_the_export_down():
+ """Path.name hands back lone surrogates via surrogateescape; zipfile cannot
+ encode them, and the raise is not an OSError so both handlers miss it."""
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ try:
+ # fsdecode itself is the first thing that can refuse: Windows decodes
+ # filenames as utf-8/surrogatepass, which has no way to carry a lone
+ # 0xff, where POSIX surrogateescape does.
+ raw = os.fsdecode(b"server-\xff\xfe.log")
+ (directory / raw).write_bytes(b"a line\n")
+ except (OSError, UnicodeError):
+ # Tried rather than guessed from the platform: macOS has every POSIX
+ # call this would test for and still refuses the byte sequence, so the
+ # capability is the only honest gate.
+ pytest.skip("this platform cannot name a file with undecodable bytes")
+ members = _members()
+ assert any(name.startswith("server/") for name in members)
+
+
[email protected](os.name == "nt", reason = "Windows filenames cannot contain a newline")
+def test_a_label_cannot_forge_a_line_in_the_warnings_member():
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ (directory / "server-a\nforged: nothing was omitted\nb.log").write_bytes(b"x\n")
+ for name in _members():
+ assert "\n" not in name
+
+
+def test_the_warnings_member_does_not_stamp_the_host_clock(monkeypatch):
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 8)
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 64)
+ _seed_server_log("a line that is definitely longer than eight bytes\n")
+ handle = debug_log_export.build_log_archive()
+ try:
+ with zipfile.ZipFile(handle) as archive:
+ for info in archive.infolist():
+ assert info.date_time == (1980, 1, 1, 0, 0, 0), info.filename
+ assert info.comment == b"" and info.extra == b""
+ finally:
+ handle.close()
+
+
+def test_a_pathological_log_cannot_run_past_the_time_budget(monkeypatch):
+ """The byte budget assumes a throughput the redactor does not guarantee:
+ its ANSI rules backtrack quadratically, so a log of unterminated C1
+ introducers costs thousands of times what the same bytes of text do."""
+ monkeypatch.setattr(debug_log_export, "MAX_BUILD_SECONDS", 0.5)
+ real_redact = debug_log_export.redact_log_text
+
+ def slow(text):
+ time.sleep(0.05)
+ return real_redact(text)
+
+ monkeypatch.setattr(debug_log_export, "redact_log_text", slow)
+ _seed_server_log("a line\n" * 500)
+ _seed_llama_log("another line\n" * 500)
+
+ started = time.monotonic()
+ members = _members()
+ elapsed = time.monotonic() - started
+
+ assert elapsed < 10, f"build ran for {elapsed:.1f}s despite the budget"
+ warnings = members[debug_log_export.WARNINGS_MEMBER].decode()
+ truncated = any(debug_log_export.TRUNCATED_MARKER.encode() in body for body in members.values())
+ assert truncated or "time budget" in warnings
+
+
[email protected](not hasattr(os, "mkfifo"), reason = "no os.mkfifo on this platform")
+def test_a_fifo_in_the_log_directory_does_not_hang_the_export(monkeypatch):
+ """O_NOFOLLOW refuses a symlink but not a FIFO, and opening a FIFO with no
+ writer blocks forever -- before the fstat check gets a turn to reject it."""
+ path = _seed_server_log("ordinary line\n")
+ enumerate_sources = debug_log_sources.list_sources
+
+ def swap_for_a_fifo():
+ sources = enumerate_sources()
+ path.unlink()
+ os.mkfifo(path)
+ return sources
+
+ monkeypatch.setattr(debug_log_sources, "list_sources", swap_for_a_fifo)
+ started = time.monotonic()
+ members = _members()
+ assert time.monotonic() - started < 10, "the open blocked on the FIFO"
+ assert f"server/{path.name}" not in members
+ path.unlink()
+
+
+def test_a_second_export_is_refused_rather_than_queued(client, monkeypatch):
+ """The route is a sync def on a 40-thread pool shared with every other sync
+ endpoint, and a build is seconds of CPU."""
+ _seed_server_log("a line\n")
+ settings_route._DEBUG_LOG_EXPORT_LOCK.acquire()
+ try:
+ assert client.get("/api/settings/debug/logs/export").status_code == 429
+ finally:
+ settings_route._DEBUG_LOG_EXPORT_LOCK.release()
+ # Released again, so the next caller is served normally.
+ assert client.get("/api/settings/debug/logs/export").status_code == 200
+
+
+def test_a_utf16_log_never_ships_its_credentials():
+ """UTF-8 replacement decoding of UTF-16 leaves a NUL between every
+ character, so every masking rule stops matching and the record is copied
+ through with the credential still perfectly readable."""
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / "server-20260813-120000-utf16.log"
+ path.write_bytes("HF_TOKEN=hf_AbCdEfGhIjKlMnOpQrStUv012345\n".encode("utf-16-le"))
+ for name, body in _members().items():
+ assert b"hf_AbCdEfGhIjKlMnOpQrStUv012345" not in body, name
+ # And not readable with the NULs stripped either, which is all `strings`
+ # does.
+ assert b"hf_AbCdEfGhIjKlMnOpQrStUv012345" not in body.replace(b"\x00", b""), name
+
+
+def test_an_invalid_utf8_record_is_refused_rather_than_replaced():
+ directory = Path(os.environ["UNSLOTH_STUDIO_HOME"]) / "logs" / "server"
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / "server-20260813-120000-binary.log"
+ path.write_bytes(b"ordinary line\n" + b"\xff\xfe token=abcdef123456\n")
+ body = _members()[f"server/{path.name}"]
+ assert b"ordinary line" in body
+ assert debug_log_export.UNREADABLE_MARKER.encode() in body
+
+
+def test_valid_non_ascii_utf8_is_kept():
+ """The refusal is for what the redactor cannot read, not for anything that
+ is merely not ASCII."""
+ path = _seed_server_log("connexion établie vers le modèle 模型\n")
+ body = _members()[f"server/{path.name}"].decode("utf-8")
+ assert "établie" in body and "模型" in body
+
+
+def test_an_empty_log_is_an_empty_member_not_a_warning():
+ """(0, 0) satisfies `skipped >= size`, which blamed the export for a file
+ that simply has nothing in it yet."""
+ path = _seed_server_log("")
+ members = _members()
+ assert members[f"server/{path.name}"] == b""
+ assert debug_log_export.WARNINGS_MEMBER not in members
+
+
+def test_a_tail_landing_exactly_on_a_boundary_keeps_that_record(monkeypatch):
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 1 << 20)
+ # "keep me\n" is 8 bytes, and the allowance is exactly that, so `start`
+ # lands on the newline before it.
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 8)
+ path = _seed_server_log("dropped\nkeep me\n")
+ assert _members()[f"server/{path.name}"].decode().endswith("keep me\n")
+
+
+def test_the_tail_scan_does_not_follow_a_growing_log(monkeypatch):
+ """The forward scan must stop at the size taken from the descriptor. A live
+ log has no EOF: scanning to it follows the writer, which is the same
+ unbounded read the record loop is careful to avoid."""
+ monkeypatch.setattr(debug_log_export, "MAX_RECORD_BYTES", 512)
+ monkeypatch.setattr(debug_log_export, "MAX_SOURCE_TAIL_BYTES", 2048)
+ monkeypatch.setattr(debug_log_export, "MAX_TOTAL_SOURCE_BYTES", 1 << 20)
+ # No newline anywhere, so the scan runs the whole tail looking for one.
+ path = _seed_server_log("z" * 6000)
+ real_stat = os.fstat
+ grew = {"count": 0}
+
+ def grow_on_stat(fd):
+ result = real_stat(fd)
+ if grew["count"] < 200:
+ grew["count"] += 1
+ with path.open("a", encoding = "utf-8") as handle:
+ handle.write("y" * 4000)
+ return result
+
+ monkeypatch.setattr(os, "fstat", grow_on_stat)
+ started = time.monotonic()
+ _members()
+ assert time.monotonic() - started < 20, "the scan followed the writer"
diff --git a/studio/backend/utils/debug_log_export.py b/studio/backend/utils/debug_log_export.py
new file mode 100644
index 00000000000..3cee64c84f6
--- /dev/null
+++ b/studio/backend/utils/debug_log_export.py
@@ -0,0 +1,430 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Pack every log the viewer may read into one redacted ZIP.
+
+Same allowlist as the picker (`debug_log_sources.list_sources`) through the same
+`redact_log_text`, so the bundle can hold no file, and no credential, the tab
+would not have shown.
+
+The per-family cap upstream bounds FILES, not bytes, and the session log is
+never rotated. Hence two more bounds here, a tail per file and a budget across
+all of them, both cutting from the FRONT: the end of a log explains the problem.
+"""
+
+from __future__ import annotations
+
+import errno
+import os
+import stat
+import tempfile
+import time
+import zipfile
+from typing import IO, Iterator
+
+from utils import debug_log_sources
+from utils.log_redaction import redact_log_text
+
+# Beyond this the ZIP rolls from memory onto disk.
+SPOOL_MAX_BYTES = 8 * 1024 * 1024
+
+STREAM_CHUNK_BYTES = 64 * 1024
+
+_READ_CHUNK_BYTES = 256 * 1024
+
+# Dropped WHOLE, never split: the redactor is anchored on a key next to its
+# value, so a cut between the two hands out the credential. Matches the viewer's
+# MAX_LINE_BYTES because `_ANSI_RE` backtracks quadratically, so cost grows with
+# the SQUARE of what one call is handed.
+MAX_RECORD_BYTES = 32 * 1024
+OVERSIZED_MARKER = "[oversized log record omitted]"
+TRUNCATED_MARKER = "[export time budget reached, rest of this log omitted]"
+CUT_MARKER = "[export size budget reached, end of this record omitted]"
+UNREADABLE_MARKER = "[log record omitted: not UTF-8 text the redactor can mask]"
+
+# The tail kept from any one log; a session log runs to gigabytes.
+MAX_SOURCE_TAIL_BYTES = 8 * 1024 * 1024
+
+# Across every log together. Sized against the redactor's ~4.2 MB/s: the route
+# builds before it answers and DOWNLOAD_READ_TIMEOUT (native_file_dialogs.rs)
+# allows 30s for headers, so 32 MB is ~12s of that. Raising it without making
+# the redactor faster, or streaming the ZIP as it builds, times the caller out.
+# Also bounds the browser path, which holds the response in a Blob.
+MAX_TOTAL_SOURCE_BYTES = 32 * 1024 * 1024
+
+# The byte budget assumes a throughput the redactor does not guarantee: ANSI
+# rules backtrack quadratically, so 12 MB of unterminated C1 introducers takes
+# ~16 minutes without this and ~22s with it. Checked BEFORE each record, so the
+# build overshoots by one record (~2.5s worst case) and still lands inside
+# DOWNLOAD_READ_TIMEOUT, returning a short archive rather than a timeout.
+MAX_BUILD_SECONDS = 15.0
+
+WARNINGS_MEMBER = "EXPORT_WARNINGS.txt"
+
+
+def _safe_basename(label: str) -> str:
+ """The filename out of a label, with no way to reach a directory.
+
+ Both separators, not `Path(label).name`: a Windows-shaped label read on
+ POSIX keeps its backslashes, which some extractors treat as a path.
+ """
+ name = label.replace("\\", "/").rsplit("/", 1)[-1].strip()
+ # A newline would forge an entry in EXPORT_WARNINGS.txt, one line per source.
+ name = "".join(
+ "_" if character < " " or character == "\x7f" else character for character in name
+ )
+ # Lone surrogates from `surrogateescape` are not encodable by zipfile, and
+ # the raise lands outside both OSError handlers: a 500 for the whole export.
+ name = name.encode("utf-8", "replace").decode("utf-8")
+ if not name or name.strip(".") == "":
+ return "log"
+ return name
+
+
+def _member_name(family: str, label: str, used: set[str]) -> str:
+ """`family/basename`, made unique against everything already in the ZIP.
+
+ A duplicated member extracts as whichever entry the tool reaches last,
+ silently losing the other. The key is case-folded because the volume the
+ archive is EXTRACTED on decides what collides: Windows and default APFS
+ treat `Server.log` and `server.log` as one name. `.lower()` not
+ `.casefold()`, which over-folds for filenames (Turkish dotless i, sharp s);
+ only the KEY is folded, the member keeps its real name.
+ """
+ base = _safe_basename(label)
+ candidate = f"{family}/{base}"
+ if candidate.lower() not in used:
+ used.add(candidate.lower())
+ return candidate
+ stem, dot, extension = base.rpartition(".")
+ if not dot:
+ stem, extension = base, ""
+ else:
+ extension = dot + extension
+ index = 2
+ # Loops: the first suffix can itself be taken, by a real file or an earlier
+ # collision.
+ while f"{family}/{stem}-{index}{extension}".lower() in used:
+ index += 1
+ candidate = f"{family}/{stem}-{index}{extension}"
+ used.add(candidate.lower())
+ return candidate
+
+
+def _open_verified(path: str) -> tuple[IO[bytes], int]:
+ """Open a source without ever following a link, and prove what we opened.
+
+ The walk in `debug_log_sources` already refuses a symlink whose target
+ escapes the log directory, but that check ran at enumeration time; anything
+ can replace the entry before this open. So: lstat first and refuse a
+ non-regular file, open with O_NOFOLLOW, then fstat the DESCRIPTOR and
+ require it to be the same regular file. The fstat-versus-lstat compare is
+ the part that matters -- it is taken on the handle we are about to read, so
+ a swap after it cannot redirect us. `LogSource` carries no device or inode,
+ so the pre-open lstat here is the newest identity we have; that narrows the
+ window between enumeration and open without closing it entirely.
+
+ Returns the handle and its raw descriptor.
+
+ One residual, on Windows only, that this cannot close. `O_NOFOLLOW` is
+ POSIX-only, so the `getattr` above collapses to 0 there and the open follows
+ whatever the entry is. A true symlink is still refused -- CPython sets
+ `S_IFLNK` for a reparse point whose tag is `IO_REPARSE_TAG_SYMLINK`, and a
+ junction resolves to a directory and fails `S_ISREG`. But for any OTHER file
+ reparse tag (AppExecLink, a OneDrive placeholder, dedup), `win32_xstat` falls
+ back to traversing, so `before` describes the TARGET, the flagless open
+ reaches the same target, and the device/inode compare matches. Closing that
+ needs `CreateFileW` with `FILE_FLAG_OPEN_REPARSE_POINT`, which `os.open`
+ cannot express. It is bounded rather than open: `debug_log_sources` resolves
+ every entry with `realpath` and refuses a target outside the log directory,
+ so only the enumeration-to-open window is exposed -- and anyone who can write
+ to that directory can already hard-link a file into it, which no platform
+ here refuses.
+ """
+ before = os.stat(path, follow_symlinks = False)
+ if not stat.S_ISREG(before.st_mode):
+ raise OSError(errno.ELOOP, "not a regular file")
+ # O_NONBLOCK because O_NOFOLLOW refuses a symlink but NOT a FIFO, and
+ # opening a FIFO with no writer blocks forever -- before the fstat below
+ # ever gets a turn to reject it. On a regular file it does nothing; on a
+ # FIFO it returns immediately and the S_ISREG check then refuses it.
+ flags = (
+ os.O_RDONLY
+ | getattr(os, "O_BINARY", 0)
+ | getattr(os, "O_NOFOLLOW", 0)
+ | getattr(os, "O_NONBLOCK", 0)
+ )
+ fd = os.open(path, flags)
+ try:
+ after = os.fstat(fd)
+ if not stat.S_ISREG(after.st_mode):
+ raise OSError(errno.ELOOP, "not a regular file")
+ if (after.st_dev, after.st_ino) != (before.st_dev, before.st_ino):
+ raise OSError(errno.ESTALE, "file replaced during export")
+ except BaseException:
+ os.close(fd)
+ raise
+ # From the descriptor only. Re-opening by name would hand the read back to
+ # whatever the path points at now.
+ return os.fdopen(fd, "rb"), fd
+
+
+def _redact_record(raw: bytes) -> str:
+ """One record, masked, or refused if the redactor cannot read it.
+
+ `errors="replace"` is unsafe: a UTF-16 log decoded as UTF-8 keeps a NUL
+ between every character, so `HF_TOKEN=hf_...` stops matching every masking
+ rule and is copied through in the clear. PowerShell redirection writes
+ UTF-16LE by default. A record that cannot be masked must not ship.
+ """
+ if b"\x00" in raw:
+ return UNREADABLE_MARKER
+ try:
+ text = raw.decode("utf-8", errors = "strict")
+ except UnicodeDecodeError:
+ return UNREADABLE_MARKER
+ return redact_log_text(text.rstrip("\r"))
+
+
+def _seek_to_tail(handle: IO[bytes], fd: int, allowance: int) -> tuple[int, int]:
+ """Position at the last `allowance` bytes, on a record boundary.
+
+ Returns the bytes skipped (0 if the whole file fits) and the size, read from
+ the descriptor about to be used rather than re-stat'd later.
+
+ The boundary is not cosmetic: `redact_log_text` is anchored on a key beside
+ its value, so a read starting mid-record can emit a credential whose key was
+ in the skipped part. Whatever the seek lands inside is dropped.
+ """
+ size = os.fstat(fd).st_size
+ if size <= allowance:
+ return 0, size
+ start = size - allowance
+ # Already just after a newline: a boundary, so do not discard a whole record.
+ handle.seek(start - 1)
+ if handle.read(1) == b"\n":
+ return start, size
+ # Scan FORWARD to a real newline, however far. Giving up after one probe
+ # starts mid-record, which leaks: an `aws_secret_access_key="..."` whose key
+ # fell before that offset arrives masked of nothing, and an AWS secret has
+ # no prefix for a shape rule to catch. Bounded by the size taken from the
+ # descriptor, not by EOF -- a live log has none, so scanning to it follows
+ # the writer indefinitely.
+ scanned = start
+ while scanned < size:
+ probe = handle.read(min(MAX_RECORD_BYTES, size - scanned))
+ if not probe:
+ break
+ newline = probe.find(b"\n")
+ if newline != -1:
+ handle.seek(scanned + newline + 1)
+ return scanned + newline + 1, size
+ scanned += len(probe)
+ # No boundary in the tail: reading anyway is the same mid-record start, so
+ # refuse the file. The caller turns this into a warning, not a member.
+ handle.seek(size)
+ return size, size
+
+
+def _redacted_records(handle: IO[bytes], fd: int, limit: int, deadline: float) -> Iterator[str]:
+ """Every line of one log, masked, in bounded chunks, stopping after `limit`.
+
+ Never `handle.read()`: a runner log can be gigabytes.
+
+ `limit` is a different bound from the seek that positioned this read. The
+ seek says where to start; a log being APPENDED to has no end, so without a
+ ceiling the loop follows the writer -- on the session log, which is live by
+ definition while someone is exporting it.
+
+ `deadline` is per RECORD. Per source overruns because one pathological file
+ blows the whole build (the redactor's cost is quadratic in what it is
+ handed); per chunk overruns because one 256 KiB chunk holds thousands of
+ records.
+ """
+ buffer = b""
+ start = handle.tell()
+ consumed = start
+ # The current record blew the budget; everything to the next newline goes
+ # with it.
+ dropping = False
+ # Whether the read stopped at the FILE's end or the ALLOWANCE's. At EOF the
+ # trailing bytes are a real last record with no newline; at the allowance
+ # they are the front of one whose remainder was never read.
+ at_eof = False
+ while consumed - start < limit:
+ chunk = handle.read(min(_READ_CHUNK_BYTES, limit - (consumed - start)))
+ if not chunk:
+ # Shorter than what was read means it rotated or was truncated under
+ # us, so the tail does not line up. Growth is ordinary: it is live.
+ if os.fstat(fd).st_size < consumed:
+ raise OSError(errno.ESTALE, "log file shrank during export")
+ at_eof = True
+ break
+ consumed += len(chunk)
+ buffer += chunk
+ while True:
+ if time.monotonic() > deadline:
+ yield TRUNCATED_MARKER
+ return
+ newline = buffer.find(b"\n")
+ if newline == -1:
+ break
+ record, buffer = buffer[:newline], buffer[newline + 1 :]
+ if dropping:
+ # The rest of a record already given up on.
+ dropping = False
+ yield OVERSIZED_MARKER
+ elif len(record) > MAX_RECORD_BYTES:
+ # Terminated inside one chunk, so the buffer guard never saw it.
+ yield OVERSIZED_MARKER
+ else:
+ yield _redact_record(record)
+ if len(buffer) > MAX_RECORD_BYTES:
+ # A log with no newline at all must not be held in memory whole.
+ dropping = True
+ buffer = b""
+ # No size guard here: the in-loop one clears the buffer after every chunk.
+ if dropping:
+ yield OVERSIZED_MARKER
+ elif buffer:
+ # Whole record, or the front of one? `at_eof` alone cannot say: the loop
+ # stops as soon as the allowance is spent, so a file whose last byte
+ # lands exactly there never gets the read that reports EOF, and its
+ # final newline-less record is complete. The descriptor separates them.
+ #
+ # It matters because a cut record reads as a complete line, and
+ # `redact_log_text` needs several characters of value before it masks,
+ # so a cut just past a key ships the first few in the clear. Reachable:
+ # `_seek_to_tail`'s forward scan starts later than `size - allowance`,
+ # so on a log being appended to the read ends on the allowance, not EOF.
+ if at_eof:
+ cut = False
+ else:
+ try:
+ cut = os.fstat(fd).st_size > consumed
+ except OSError:
+ cut = True # cannot tell; take the side that cannot mislead
+ yield CUT_MARKER if cut else _redact_record(buffer)
+
+
+def _newest_first_across_families(
+ sources: list[debug_log_sources.LogSource],
+) -> list[debug_log_sources.LogSource]:
+ """Round-robin the families instead of draining them one at a time.
+
+ Consumed in `list_sources` order, a large session log spends the whole byte
+ budget on the server family and the bundle arrives with no runner logs --
+ usually the half that explains the problem. Round-robin means the budget
+ runs out on the oldest attempts rather than on a whole category.
+ """
+ by_family: dict[str, list[debug_log_sources.LogSource]] = {}
+ for source in sources:
+ by_family.setdefault(source.family, []).append(source)
+ ordered: list[debug_log_sources.LogSource] = []
+ for rank in range(max((len(group) for group in by_family.values()), default = 0)):
+ for group in by_family.values():
+ if rank < len(group):
+ ordered.append(group[rank])
+ return ordered
+
+
+def _warning_line(member: str, exc: BaseException) -> str:
+ """One failed source, named by its member, never by its path.
+
+ Not `str(exc)`: `OSError.__str__` appends the filename, which would put a
+ host path into the archive -- the one thing member names avoid.
+ """
+ code = getattr(exc, "errno", None)
+ return redact_log_text(
+ f"{member}: {type(exc).__name__} (errno {code if code is not None else 'unknown'})"
+ )
+
+
+def build_log_archive() -> tempfile.SpooledTemporaryFile:
+ """Every allowlisted log, redacted, as a ZIP rewound to its start.
+
+ The caller owns the returned file and must close it.
+ """
+ output = tempfile.SpooledTemporaryFile(max_size = SPOOL_MAX_BYTES, mode = "w+b")
+ try:
+ warnings: list[str] = []
+ used: set[str] = set()
+ remaining = MAX_TOTAL_SOURCE_BYTES
+ deadline = time.monotonic() + MAX_BUILD_SECONDS
+ with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive:
+ for source in _newest_first_across_families(debug_log_sources.list_sources()):
+ member = _member_name(source.family, source.label, used)
+ if remaining <= 0:
+ # Named, so the bundle says what is missing rather than
+ # looking complete.
+ warnings.append(f"{member}: omitted, export size budget reached")
+ continue
+ if time.monotonic() > deadline:
+ warnings.append(f"{member}: omitted, export time budget reached")
+ continue
+ try:
+ handle, fd = _open_verified(source.realpath)
+ except OSError as exc:
+ # One unreadable log does not cost the user the other nine.
+ warnings.append(_warning_line(member, exc))
+ continue
+ allowance = min(MAX_SOURCE_TAIL_BYTES, remaining)
+ try:
+ with handle:
+ skipped, size = _seek_to_tail(handle, fd, allowance)
+ # `size > 0` first: an empty log returns (0, 0), and
+ # calling that "no complete record" blames the file for
+ # being empty. An empty member is the honest answer.
+ if size > 0 and skipped >= size:
+ # No boundary in the tail, so nothing whole to keep
+ # and reading anyway starts mid-record. `remaining`
+ # is deliberately NOT spent: this is one file's
+ # property and the next source may still fit.
+ #
+ # Which cap produced the window decides the wording.
+ # Blaming the file when the budget shrank it would
+ # then repeat for every later source, since
+ # `remaining` is untouched here.
+ if allowance < MAX_SOURCE_TAIL_BYTES:
+ warnings.append(f"{member}: omitted, export size budget reached")
+ else:
+ warnings.append(
+ f"{member}: omitted, no complete record in the last "
+ f"{allowance} bytes"
+ )
+ continue
+ with archive.open(member, "w") as destination:
+ if skipped:
+ warnings.append(
+ f"{member}: kept the last {size - skipped} bytes, "
+ f"skipped the first {skipped}"
+ )
+ destination.write(
+ f"[skipped the first {skipped} bytes of this log]\n".encode()
+ )
+ before = handle.tell()
+ try:
+ for record in _redacted_records(handle, fd, allowance, deadline):
+ destination.write((record + "\n").encode("utf-8"))
+ finally:
+ # Charged even on a partial read: those bytes were
+ # still redacted and written. Inside the `with`,
+ # because tell() needs an open handle.
+ remaining -= max(0, handle.tell() - before)
+ except OSError as exc:
+ # Keeps whatever was copied first: a partial log is still
+ # worth reading, and the warning says why it stops.
+ warnings.append(_warning_line(member, exc))
+ if warnings:
+ # A bare ZipInfo, not the str overload: that one stamps
+ # time.localtime(), leaking the host's clock and UTC offset.
+ archive.writestr(
+ zipfile.ZipInfo(WARNINGS_MEMBER),
+ "\n".join(warnings) + "\n",
+ compress_type = zipfile.ZIP_DEFLATED,
+ )
+ except BaseException:
+ output.close()
+ raise
+ output.seek(0)
+ return output
diff --git a/studio/frontend/src/features/settings/api/debug-logs.ts b/studio/frontend/src/features/settings/api/debug-logs.ts
index cc8e18c99da..f84b849a201 100644
--- a/studio/frontend/src/features/settings/api/debug-logs.ts
+++ b/studio/frontend/src/features/settings/api/debug-logs.ts
@@ -1,8 +1,10 @@
// 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 { authFetch, getAuthToken, refreshSession } from "@/features/auth";
+import { apiUrl, isTauri } from "@/lib/api-base";
import { readFastApiError } from "@/lib/format-fastapi-error";
+import { browserDownload } from "@/lib/native-files";
import { DebugLogRequestError } from "../lib/debug-log-error";
export { DebugLogRequestError } from "../lib/debug-log-error";
@@ -28,6 +30,8 @@ export interface DebugLogSources {
sources: DebugLogSource[];
defaultSourceId: string | null;
fileLoggingDisabled: boolean;
+ /** Where the logs live. Null on a backend older than this field. */
+ logRoot: string | null;
}
export interface DebugLogPage {
@@ -70,6 +74,7 @@ export async function loadDebugLogSources(
})),
defaultSourceId: body.default_source_id ?? null,
fileLoggingDisabled: Boolean(body.file_logging_disabled),
+ logRoot: body.log_root ?? null,
};
}
@@ -113,3 +118,195 @@ export async function loadDebugLog(
sizeBytes: Number(body.size_bytes ?? 0),
};
}
+
+export const LOG_EXPORT_ENDPOINT = "/api/settings/debug/logs/export";
+
+/**
+ * outdated - no such route, so the backend predates the feature
+ * forbidden - the route rejects this caller (API key, keyless)
+ * failed - anything else; `message` carries the detail
+ */
+export type LogExportFailure = "outdated" | "forbidden" | "failed";
+
+export class LogExportError extends Error {
+ readonly failure: LogExportFailure;
+
+ constructor(failure: LogExportFailure, message: string) {
+ super(message);
+ this.name = "LogExportError";
+ this.failure = failure;
+ }
+}
+
+function failureForStatus(status: number): LogExportFailure {
+ if (status === 404) return "outdated";
+ if (status === 403) return "forbidden";
+ return "failed";
+}
+
+// Rust hands back a string, so the status is read out of it; only
+// `stream_url_to_path` produces this phrase. Anchored at the START because two
+// other errors can CONTAIN it -- "Failed to save {path}: {error}" embeds the
+// caller's filename, and desktop-auth embeds raw stderr -- which would turn a
+// disk-full error into a "forbidden" toast. A start anchor suffices: every
+// other reachable error begins with its own fixed prefix.
+const DESKTOP_STATUS_PATTERN = /^Download failed with status (\d{3})\./;
+
+// Desktop auth can answer "this account has to log in" instead of returning a
+// session (per-account isolation, shared installs). No request is made, so
+// there is no status: the command returns this exact sentence (`LOGIN_REQUIRED`
+// in native_file_dialogs.rs). Keep the two in step.
+const DESKTOP_LOGIN_REQUIRED = "Log export requires a signed-in Studio session.";
+
+function desktopExportError(error: unknown): LogExportError {
+ const message =
+ typeof error === "string"
+ ? error
+ : ((error as Error | undefined)?.message ?? String(error));
+ if (message === DESKTOP_LOGIN_REQUIRED) {
+ return new LogExportError("forbidden", message);
+ }
+ const status = Number(message.match(DESKTOP_STATUS_PATTERN)?.[1] ?? 0);
+ return new LogExportError(failureForStatus(status), message);
+}
+
+function desktopExportStatus(error: unknown): number {
+ const message =
+ typeof error === "string"
+ ? error
+ : ((error as Error | undefined)?.message ?? String(error));
+ return Number(message.match(DESKTOP_STATUS_PATTERN)?.[1] ?? 0);
+}
+
+function pad2(value: number): string {
+ return String(value).padStart(2, "0");
+}
+
+/** `unsloth-logs-<YYYYmmdd-HHMMSS>.zip`, local time so it sorts with the session. */
+export function logArchiveFilename(now: Date = new Date()): string {
+ const day = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}`;
+ const time = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`;
+ return `unsloth-logs-${day}-${time}.zip`;
+}
+
+/**
+ * Pack every log the picker lists into one ZIP. Returns the absolute path on
+ * desktop, where Rust streamed it; null in a browser, which alone knows where
+ * its downloads land.
+ */
+export async function exportAllLogs(): Promise<string | null> {
+ const filename = logArchiveFilename();
+
+ if (isTauri) {
+ // `filename` is one word because Tauri maps camelCase onto snake_case
+ // parameters. It is only a suggestion: the command picks the destination and
+ // the realpath it returns is the answer.
+ //
+ // `uiToken` is the fallback for a multi-account install, where
+ // `desktop-login` refuses to mint unconditionally because the desktop secret
+ // says which SHELL owns the backend, not which account is using it. The
+ // command prefers a minted session and only falls back to this, and it pins
+ // host, port and path, so the token can reach nothing the tab could not
+ // already reach itself.
+ const { invoke } = await import("@tauri-apps/api/core");
+ const run = (uiToken: string | null) =>
+ invoke<string>("download_logs_to_downloads", {
+ url: apiUrl(LOG_EXPORT_ENDPOINT),
+ filename,
+ uiToken,
+ });
+
+ try {
+ return await run(getAuthToken());
+ } catch (error) {
+ // Rust uses the token once and as-is, so it cannot retry a 401 by
+ // refreshing the way `authFetch` does; a desktop left idle past the
+ // access-token lifetime would fail while holding a good refresh token.
+ // Refreshing only HERE, rather than before every export, is what keeps a
+ // transient 500 on /api/auth/refresh from signing the whole app out:
+ // `refreshSession` clears both stored tokens on any non-2xx, so doing it
+ // speculatively would end the session of a user whose token was fine. A
+ // 401 means the token really was rejected, which is the one case where
+ // losing it costs nothing that was not already lost.
+ if (desktopExportStatus(error) !== 401) throw desktopExportError(error);
+ try {
+ if (!(await refreshSession())) throw error;
+ } catch {
+ throw desktopExportError(error);
+ }
+ try {
+ return await run(getAuthToken());
+ } catch (retryError) {
+ throw desktopExportError(retryError);
+ }
+ }
+ }
+
+ const response = await authFetch(LOG_EXPORT_ENDPOINT);
+ if (!response.ok) {
+ throw new LogExportError(
+ failureForStatus(response.status),
+ await readFastApiError(response, "Could not export the logs."),
+ );
+ }
+ browserDownload(await response.blob(), filename);
+ return null;
+}
+
+/**
+ * Reveal the directory the log picker actually reads from. Desktop only: in a
+ * browser the folder is on the server, not the user's machine, and the button
+ * is not rendered.
+ *
+ * `realpath` comes from the picker, which resolves UNSLOTH_STUDIO_HOME and
+ * STUDIO_HOME. `open_logs_dir` cannot: it hard-codes ~/.unsloth/studio, so on a
+ * custom home it opens an unrelated directory or errors on a missing one. It
+ * stays as the fallback for when no source is selected yet.
+ */
+export async function openLogsFolder(
+ realpath?: string | null,
+ logRoot?: string | null,
+): Promise<void> {
+ if (!isTauri) return;
+ const { invoke } = await import("@tauri-apps/api/core");
+ // The selected log's own directory first, then the root the backend reported.
+ // `open_logs_dir` is last because it hard-codes ~/.unsloth/studio and is
+ // simply wrong under a custom home -- which is also the case where there may
+ // be no readable log to take a path from, so neither of the first two can be
+ // dropped in favour of the other.
+ const directory = (realpath ? parentDirectory(realpath) : null) ?? logRoot ?? null;
+ if (directory) {
+ await invoke("open_models_dir", { path: directory });
+ return;
+ }
+ await invoke("open_logs_dir");
+}
+
+/** The directory part of a path, on either separator. Null when there is none. */
+function parentDirectory(path: string): string | null {
+ const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
+ if (separator < 0) return null;
+ const parent = path.slice(0, separator);
+ // The separator is kept where dropping it would change the meaning rather
+ // than tidy the path: "" is the Unix root and opening nothing is not the same
+ // as opening "/", and "C:" is the CURRENT directory on drive C:, which is not
+ // "C:\" and is very unlikely to be where the archive went.
+ if (parent === "" || /^[A-Za-z]:$/.test(parent)) {
+ return path.slice(0, separator + 1);
+ }
+ return parent;
+}
+
+/**
+ * Reveal the folder the archive was saved into. Not `openLogsFolder`, which
+ * opens ~/.unsloth/studio where the logs came FROM: naming one path and opening
+ * another is the bug this avoids. `open_models_dir` is the app's generic "open
+ * this directory" command (`open_existing_dir`), misnamed rather than misused.
+ */
+export async function revealSavedArchive(savedPath: string): Promise<void> {
+ if (!isTauri) return;
+ const directory = parentDirectory(savedPath);
+ if (!directory) return;
+ const { invoke } = await import("@tauri-apps/api/core");
+ await invoke("open_models_dir", { path: directory });
+}
diff --git a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
index 472e3b75e86..a05a1978dc0 100644
--- a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
@@ -4,14 +4,20 @@
import { Button } from "@/components/ui/button";
import { useCopyFeedback } from "@/features/hub/hooks/use-copy-feedback";
import { useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
import { stripAnsi } from "@/lib/strip-ansi";
+import { toast } from "@/lib/toast";
import { Tick02Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
type DebugLogSource,
+ LogExportError,
+ exportAllLogs,
loadDebugLog,
loadDebugLogSources,
+ openLogsFolder,
+ revealSavedArchive,
} from "../api/debug-logs";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
@@ -56,6 +62,9 @@ export function DebuggingTab() {
const [mode, setMode] = useState<RefreshMode>(readStoredMode);
const [buffer, setBuffer] = useState<LogBufferState>(EMPTY_BUFFER);
const [realpath, setRealpath] = useState<string | null>(null);
+ // Where the backend says the logs live, for the folder button when no source
+ // is selected yet, which is exactly the custom-home case that has no log.
+ const [logRoot, setLogRoot] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [dropped, setDropped] = useState(false);
// A burst larger than one response continues on the next poll, which in
@@ -64,6 +73,10 @@ export function DebuggingTab() {
// File logging is off and an older session's log is still on disk, so the pane shows real content
// that will never grow. Unsaid, a stale log is indistinguishable from a live one.
const [staleSession, setStaleSession] = useState(false);
+ // Each button tracks only its own request: the export takes seconds and must
+ // not lock out "Show in folder", which is how the user reaches the result.
+ const [exporting, setExporting] = useState(false);
+ const [revealing, setRevealing] = useState(false);
const { copied, copy } = useCopyFeedback();
// In a ref as well as state: the poll loop must not restart per line arrived.
@@ -97,6 +110,7 @@ export function DebuggingTab() {
options.signal,
);
setSources(result.sources);
+ setLogRoot(result.logRoot);
setSourceId((current) =>
options.reselect
? result.defaultSourceId
@@ -270,6 +284,65 @@ export function DebuggingTab() {
pane.scrollHeight - pane.scrollTop - pane.clientHeight < 40;
}, []);
+ const revealLogsFolder = useCallback(async () => {
+ setRevealing(true);
+ try {
+ // The selected log's own path, else the root the backend reported. Either
+ // resolves a custom UNSLOTH_STUDIO_HOME; open_logs_dir hard-codes
+ // ~/.unsloth/studio and cannot.
+ await openLogsFolder(realpath, logRoot);
+ } catch (error) {
+ toast.error(t("settings.debugging.openLogsFolderFailed"), {
+ description: (error as Error).message,
+ });
+ } finally {
+ setRevealing(false);
+ }
+ }, [t, realpath, logRoot]);
+
+ const downloadAllLogs = useCallback(async () => {
+ setExporting(true);
+ try {
+ const savedPath = await exportAllLogs();
+ // A path only comes back on desktop. In a browser the file is wherever
+ // that browser puts downloads, which we cannot name.
+ if (savedPath) {
+ toast.success(
+ t("settings.debugging.downloadedTo", { path: savedPath }),
+ {
+ action: {
+ label: t("settings.debugging.showInFolder"),
+ // The folder the archive went to, not the one the logs came from.
+ onClick: () => {
+ void revealSavedArchive(savedPath).catch((error: unknown) => {
+ toast.error(t("settings.debugging.openLogsFolderFailed"), {
+ description: (error as Error).message,
+ });
+ });
+ },
+ },
+ },
+ );
+ } else {
+ toast.success(t("settings.debugging.downloadedToBrowser"));
+ }
+ } catch (error) {
+ const failure =
+ error instanceof LogExportError ? error.failure : "failed";
+ if (failure === "outdated") {
+ toast.error(t("settings.debugging.exportTooOld"));
+ } else if (failure === "forbidden") {
+ toast.error(t("settings.debugging.exportForbidden"));
+ } else {
+ toast.error(t("settings.debugging.exportFailed"), {
+ description: (error as Error).message,
+ });
+ }
+ } finally {
+ setExporting(false);
+ }
+ }, [t]);
+
return (
<div className="flex flex-col gap-6">
<SettingsSection
@@ -388,15 +461,47 @@ export function DebuggingTab() {
<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 className="flex flex-wrap items-center justify-end gap-2">
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => copy(text)}
+ disabled={!text}
+ >
+ {t("settings.debugging.copyVisible")}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ data-testid="debug-log-download-all"
+ aria-busy={exporting}
+ disabled={exporting}
+ onClick={() => void downloadAllLogs()}
+ >
+ {exporting
+ ? t("settings.debugging.downloadingAllLogs")
+ : t("settings.debugging.downloadAllLogs")}
+ </Button>
+ {isTauri ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ data-testid="debug-log-open-folder"
+ aria-busy={revealing}
+ disabled={revealing}
+ onClick={() => void revealLogsFolder()}
+ >
+ {t("settings.debugging.openLogsFolder")}
+ </Button>
+ ) : null}
+ </div>
</div>
+ <p
+ className="text-xs text-muted-foreground"
+ data-testid="debug-log-export-note"
+ >
+ {t("settings.debugging.exportMaskedNote")}
+ </p>
</div>
</div>
);
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index ad0638a32f4..75872a70c19 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -494,6 +494,17 @@ export const ar = {
droppedNotice: "تم تخطي بعض الأسطر: كُتب السجل بسرعة أكبر مما أمكن قراءته.",
morePending: "لا يزال يجري قراءة أسطر إضافية، وستظهر عند التحديث التالي.",
staleSession: "تسجيل الملفات معطل، لذا هذه جلسة سابقة ولن يتم تحديثها.",
+ downloadAllLogs: "تنزيل كل السجلات (‎.zip)",
+ downloadingAllLogs: "يجري تجميع السجلات...",
+ exportMaskedNote: "تُخفى بيانات الاعتماد في الملفات المصدَّرة. تحتفظ السجلات الكبيرة بأحدث أسطرها فقط، وقد يُستبعد بعضها بالكامل؛ راجع ملف EXPORT_WARNINGS.txt داخل الأرشيف.",
+ downloadedTo: "حُفظ في {path}",
+ downloadedToBrowser: "بدأ التنزيل.",
+ showInFolder: "إظهار في المجلد",
+ openLogsFolder: "فتح مجلد السجلات",
+ openLogsFolderFailed: "تعذّر فتح مجلد السجلات.",
+ exportFailed: "تعذّر تنزيل السجلات.",
+ exportTooOld: "خادم Unsloth العامل أقدم من أن يدعم تصدير السجلات. حدِّثه وأعد تشغيله.",
+ exportForbidden: "يتطلب تنزيل كل السجلات جلسة Studio مسجّل الدخول إليها. لا يكفي مفتاح API.",
keywords: "تصحيح الأخطاء سجل السجلات خطأ أخطاء تعطل تتبع تشخيص استكشاف الأخطاء debug log logs error",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 4d1e437a175..1e71cdc2f15 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -498,6 +498,17 @@ export const de = {
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.",
+ downloadAllLogs: "Alle Protokolle herunterladen (.zip)",
+ downloadingAllLogs: "Protokolle werden gepackt...",
+ exportMaskedNote: "In den exportierten Dateien werden Zugangsdaten maskiert. Sehr große Logs behalten nur ihre neuesten Zeilen, und einzelne Logs können ganz fehlen; siehe EXPORT_WARNINGS.txt im Archiv.",
+ downloadedTo: "Gespeichert unter {path}",
+ downloadedToBrowser: "Download gestartet.",
+ showInFolder: "Im Ordner anzeigen",
+ openLogsFolder: "Protokollordner öffnen",
+ openLogsFolderFailed: "Der Protokollordner konnte nicht geöffnet werden.",
+ exportFailed: "Die Protokolle konnten nicht heruntergeladen werden.",
+ exportTooOld: "Das laufende Unsloth-Backend ist zu alt für den Protokollexport. Aktualisieren Sie dieses Backend und starten Sie es neu.",
+ exportForbidden: "Zum Herunterladen aller Protokolle ist eine angemeldete Studio-Sitzung erforderlich. Ein API-Schlüssel genügt nicht.",
keywords: "Fehlersuche Debugging Protokoll Protokolle Log Logs Fehler Absturz Stacktrace Diagnose Problembehebung debug",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 52744d4cd1d..414b8f6c033 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -494,6 +494,17 @@ export const en = {
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.",
+ downloadAllLogs: "Download all logs (.zip)",
+ downloadingAllLogs: "Packing logs...",
+ exportMaskedNote: "Credentials are masked in the exported files. Very large logs keep only their most recent lines, and some logs may be left out entirely; see EXPORT_WARNINGS.txt in the archive.",
+ downloadedTo: "Saved to {path}",
+ downloadedToBrowser: "Download started.",
+ showInFolder: "Show in folder",
+ openLogsFolder: "Open logs folder",
+ openLogsFolderFailed: "Could not open the logs folder.",
+ exportFailed: "Could not download the logs.",
+ exportTooOld: "Running Unsloth backend is too old to export logs. Update that backend and restart.",
+ exportForbidden: "Downloading all logs needs a signed-in Studio session. An API key is not enough.",
// Not rendered: extra terms the settings search matches this tab on.
keywords: "debug debugging log logs error errors crash traceback stack trace troubleshoot diagnostics failed",
},
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 066cff222d1..e51b4c53e60 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -497,6 +497,17 @@ export const es = {
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.",
+ downloadAllLogs: "Descargar todos los registros (.zip)",
+ downloadingAllLogs: "Empaquetando los registros...",
+ exportMaskedNote: "Las credenciales se enmascaran en los archivos exportados. Los registros muy grandes conservan solo sus líneas más recientes y algunos pueden quedar fuera por completo; consulta EXPORT_WARNINGS.txt en el archivo.",
+ downloadedTo: "Guardado en {path}",
+ downloadedToBrowser: "Descarga iniciada.",
+ showInFolder: "Mostrar en la carpeta",
+ openLogsFolder: "Abrir la carpeta de registros",
+ openLogsFolderFailed: "No se pudo abrir la carpeta de registros.",
+ exportFailed: "No se pudieron descargar los registros.",
+ exportTooOld: "El backend de Unsloth en ejecución es demasiado antiguo para exportar los registros. Actualízalo y reinícialo.",
+ exportForbidden: "Para descargar todos los registros hace falta una sesión de Studio iniciada. Una clave de API no basta.",
keywords: "depuracion depurar registro registros log logs error errores fallo traza diagnostico solucion de problemas debug",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 45f14458ce3..5a874c62af6 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -498,6 +498,17 @@ export const fr = {
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.",
+ downloadAllLogs: "Télécharger tous les journaux (.zip)",
+ downloadingAllLogs: "Préparation de l'archive...",
+ exportMaskedNote: "Les identifiants sont masqués dans les fichiers exportés. Les journaux très volumineux ne conservent que leurs lignes les plus récentes, et certains peuvent être omis entièrement ; voir EXPORT_WARNINGS.txt dans l'archive.",
+ downloadedTo: "Enregistré dans {path}",
+ downloadedToBrowser: "Téléchargement lancé.",
+ showInFolder: "Afficher dans le dossier",
+ openLogsFolder: "Ouvrir le dossier des journaux",
+ openLogsFolderFailed: "Le dossier des journaux n'a pas pu être ouvert.",
+ exportFailed: "Les journaux n'ont pas pu être téléchargés.",
+ exportTooOld: "Le backend Unsloth en cours d'exécution est trop ancien pour exporter les journaux. Mettez-le à jour et redémarrez-le.",
+ exportForbidden: "Le téléchargement de tous les journaux nécessite une session Studio connectée. Une clé d'API ne suffit pas.",
keywords: "debogage deboguer journal journaux log logs erreur erreurs plantage trace diagnostic depannage debug",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index fc88f4b6663..9ab1e655659 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -497,6 +497,17 @@ export const hi = {
droppedNotice: "कुछ पंक्तियाँ छोड़ दी गईं: लॉग इतनी तेज़ी से लिखा गया कि उसे पढ़ा नहीं जा सका।",
morePending: "और पंक्तियां अभी पढ़ी जा रही हैं; वे अगले रिफ्रेश पर आएंगी।",
staleSession: "फ़ाइल लॉगिंग बंद है, इसलिए यह पुराना सत्र है और अपडेट नहीं होगा।",
+ downloadAllLogs: "सभी लॉग डाउनलोड करें (.zip)",
+ downloadingAllLogs: "लॉग पैक किए जा रहे हैं...",
+ exportMaskedNote: "निर्यात की गई फ़ाइलों में क्रेडेंशियल छिपा दिए जाते हैं। बहुत बड़े लॉग केवल अपनी सबसे हाल की पंक्तियाँ रखते हैं, और कुछ लॉग पूरी तरह छूट सकते हैं; संग्रह में EXPORT_WARNINGS.txt देखें।",
+ downloadedTo: "{path} में सहेजा गया",
+ downloadedToBrowser: "डाउनलोड शुरू हो गया।",
+ showInFolder: "फ़ोल्डर में दिखाएँ",
+ openLogsFolder: "लॉग फ़ोल्डर खोलें",
+ openLogsFolderFailed: "लॉग फ़ोल्डर नहीं खोला जा सका।",
+ exportFailed: "लॉग डाउनलोड नहीं किए जा सके।",
+ exportTooOld: "चल रहा Unsloth बैकएंड लॉग निर्यात करने के लिए बहुत पुराना है। उस बैकएंड को अपडेट करें और पुनः आरंभ करें।",
+ exportForbidden: "सभी लॉग डाउनलोड करने के लिए साइन-इन किया हुआ Studio सत्र चाहिए। केवल API कुंजी पर्याप्त नहीं है।",
keywords: "डिबग डिबगिंग लॉग त्रुटि गड़बड़ी क्रैश ट्रेसबैक निदान समस्या निवारण debug log logs error",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 56020bd0b27..fd45c5c2bcd 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -462,6 +462,17 @@ export const it = {
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.",
+ downloadAllLogs: "Scarica tutti i log (.zip)",
+ downloadingAllLogs: "Creazione dell'archivio...",
+ exportMaskedNote: "Nei file esportati le credenziali sono mascherate. I log molto grandi conservano solo le righe più recenti e alcuni possono essere esclusi del tutto; vedi EXPORT_WARNINGS.txt nell'archivio.",
+ downloadedTo: "Salvato in {path}",
+ downloadedToBrowser: "Download avviato.",
+ showInFolder: "Mostra nella cartella",
+ openLogsFolder: "Apri la cartella dei log",
+ openLogsFolderFailed: "Non è stato possibile aprire la cartella dei log.",
+ exportFailed: "Non è stato possibile scaricare i log.",
+ exportTooOld: "Il backend Unsloth in esecuzione è troppo vecchio per esportare i log. Aggiornalo e riavvialo.",
+ exportForbidden: "Per scaricare tutti i log serve una sessione di Studio con accesso eseguito. Una chiave API non basta.",
keywords: "debug log logs registro registri errore errori crash traccia diagnostica risoluzione dei problemi",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 2290638faaa..efa0fe37fc6 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -496,6 +496,17 @@ export const ja = {
droppedNotice: "一部の行がスキップされました。ログの書き込みが読み取りに追いつきませんでした。",
morePending: "さらに行を読み込み中です。次回の更新時に表示されます。",
staleSession: "ファイルへのログ出力が無効なため、これは以前のセッションであり更新されません。",
+ downloadAllLogs: "すべてのログをダウンロード (.zip)",
+ downloadingAllLogs: "ログをまとめています...",
+ exportMaskedNote: "書き出したファイルでは認証情報をマスクします。非常に大きなログは直近の行だけを残し、一部のログはまったく含まれないことがあります。アーカイブ内の EXPORT_WARNINGS.txt を確認してください。",
+ downloadedTo: "{path} に保存しました",
+ downloadedToBrowser: "ダウンロードを開始しました。",
+ showInFolder: "フォルダーで表示",
+ openLogsFolder: "ログフォルダーを開く",
+ openLogsFolderFailed: "ログフォルダーを開けませんでした。",
+ exportFailed: "ログをダウンロードできませんでした。",
+ exportTooOld: "実行中の Unsloth バックエンドが古すぎるため、ログを書き出せません。バックエンドを更新して再起動してください。",
+ exportForbidden: "すべてのログをダウンロードするには、サインイン済みの Studio セッションが必要です。API キーだけでは実行できません。",
keywords: "デバッグ ログ エラー クラッシュ トレースバック スタックトレース 診断 障害 調査 debug log logs error",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 6f377c898e5..f1e33294ee2 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -494,6 +494,17 @@ export const ko = {
droppedNotice: "일부 줄이 누락되었습니다. 로그를 읽는 속도보다 기록되는 속도가 빨랐습니다.",
morePending: "아직 더 많은 줄을 읽고 있습니다. 다음 새로 고침에 표시됩니다.",
staleSession: "파일 로깅이 꺼져 있으므로 이것은 이전 세션이며 업데이트되지 않습니다.",
+ downloadAllLogs: "모든 로그 다운로드 (.zip)",
+ downloadingAllLogs: "로그를 묶는 중...",
+ exportMaskedNote: "내보낸 파일에서는 자격 증명이 가려집니다. 매우 큰 로그는 가장 최근 줄만 남으며, 일부 로그는 아예 빠질 수 있습니다. 아카이브의 EXPORT_WARNINGS.txt를 확인하세요.",
+ downloadedTo: "{path}에 저장했습니다",
+ downloadedToBrowser: "다운로드를 시작했습니다.",
+ showInFolder: "폴더에서 보기",
+ openLogsFolder: "로그 폴더 열기",
+ openLogsFolderFailed: "로그 폴더를 열 수 없습니다.",
+ exportFailed: "로그를 다운로드할 수 없습니다.",
+ exportTooOld: "실행 중인 Unsloth 백엔드가 너무 오래되어 로그를 내보낼 수 없습니다. 해당 백엔드를 업데이트한 뒤 다시 시작하세요.",
+ exportForbidden: "모든 로그를 다운로드하려면 로그인된 Studio 세션이 필요합니다. API 키만으로는 할 수 없습니다.",
keywords: "디버그 디버깅 로그 오류 에러 충돌 스택 추적 진단 문제 해결 debug log logs error",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 288bba50ecf..7751a513776 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -496,6 +496,17 @@ export const ptBR = {
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.",
+ downloadAllLogs: "Baixar todos os logs (.zip)",
+ downloadingAllLogs: "Compactando os logs...",
+ exportMaskedNote: "As credenciais são mascaradas nos arquivos exportados. Logs muito grandes mantêm apenas as linhas mais recentes, e alguns podem ficar de fora por completo; veja EXPORT_WARNINGS.txt no arquivo.",
+ downloadedTo: "Salvo em {path}",
+ downloadedToBrowser: "Download iniciado.",
+ showInFolder: "Mostrar na pasta",
+ openLogsFolder: "Abrir a pasta de logs",
+ openLogsFolderFailed: "Não foi possível abrir a pasta de logs.",
+ exportFailed: "Não foi possível baixar os logs.",
+ exportTooOld: "O backend do Unsloth em execução é antigo demais para exportar os logs. Atualize esse backend e reinicie.",
+ exportForbidden: "Para baixar todos os logs é preciso uma sessão do Studio conectada. Uma chave de API não basta.",
keywords: "depuracao depurar registro registros log logs erro erros falha rastreamento diagnostico solucao de problemas debug",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 5996d98f4d0..524390dcbfd 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -496,6 +496,17 @@ export const ru = {
droppedNotice: "Часть строк пропущена: журнал записывался быстрее, чем его удавалось читать.",
morePending: "Ещё строки продолжают читаться; они появятся при следующем обновлении.",
staleSession: "Запись журнала в файл отключена, поэтому это предыдущий сеанс, который не будет обновляться.",
+ downloadAllLogs: "Скачать все журналы (.zip)",
+ downloadingAllLogs: "Упаковка журналов...",
+ exportMaskedNote: "В экспортированных файлах учётные данные скрыты. Очень большие журналы сохраняют только самые свежие строки, а некоторые могут быть исключены целиком; смотрите EXPORT_WARNINGS.txt в архиве.",
+ downloadedTo: "Сохранено в {path}",
+ downloadedToBrowser: "Загрузка началась.",
+ showInFolder: "Показать в папке",
+ openLogsFolder: "Открыть папку журналов",
+ openLogsFolderFailed: "Не удалось открыть папку журналов.",
+ exportFailed: "Не удалось скачать журналы.",
+ exportTooOld: "Запущенный сервер Unsloth слишком старый для экспорта журналов. Обновите его и перезапустите.",
+ exportForbidden: "Для скачивания всех журналов нужен вход в сеанс Studio. Ключа API недостаточно.",
keywords: "отладка журнал журналы лог логи ошибка ошибки сбой трассировка диагностика поиск неисправностей debug log",
},
voice: {
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index d56e29474e5..16f21c6c317 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -492,6 +492,17 @@ export const zhCN = {
droppedNotice: "已跳过部分行:日志的写入速度超过了读取速度。",
morePending: "仍在读取更多行,它们将在下次刷新时显示。",
staleSession: "文件日志已关闭,因此这是较早的会话,不会更新。",
+ downloadAllLogs: "下载全部日志 (.zip)",
+ downloadingAllLogs: "正在打包日志...",
+ exportMaskedNote: "导出的文件中已遮蔽凭据。超大日志仅保留最近的行,部分日志可能被完全略去;请查看压缩包中的 EXPORT_WARNINGS.txt。",
+ downloadedTo: "已保存到 {path}",
+ downloadedToBrowser: "已开始下载。",
+ showInFolder: "在文件夹中显示",
+ openLogsFolder: "打开日志文件夹",
+ openLogsFolderFailed: "无法打开日志文件夹。",
+ exportFailed: "无法下载日志。",
+ exportTooOld: "正在运行的 Unsloth 后端版本过旧,无法导出日志。请更新该后端并重新启动。",
+ exportForbidden: "下载全部日志需要已登录的 Studio 会话,仅有 API 密钥不够。",
keywords: "调试 日志 错误 崩溃 堆栈 跟踪 诊断 排查 故障 debug log logs error",
},
voice: {
diff --git a/studio/frontend/src/lib/native-files.ts b/studio/frontend/src/lib/native-files.ts
index ddc002dc0c8..70f16cb98a1 100644
--- a/studio/frontend/src/lib/native-files.ts
+++ b/studio/frontend/src/lib/native-files.ts
@@ -52,7 +52,7 @@ export async function readNativeChatImportChunk(
: new Uint8Array(bytes);
}
-function browserDownload(blob: Blob, filename: string): void {
+export function browserDownload(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
diff --git a/studio/frontend/tests/debug-log-export.test.ts b/studio/frontend/tests/debug-log-export.test.ts
new file mode 100644
index 00000000000..ba2b51ce5c3
--- /dev/null
+++ b/studio/frontend/tests/debug-log-export.test.ts
@@ -0,0 +1,541 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Settings > Logs: "Download all logs (.zip)" and "Open logs folder".
+//
+// Both branches run in one process, which a plain import cannot do: `isTauri` is
+// decided once when lib/api-base evaluates. loadWithStubs re-runs the source per
+// test with the api-base it wants, and keeps "@tauri-apps/api/core" (resolvable
+// only inside a Tauri webview) out of the runner.
+//
+// The tab renders with react-dom/server, where effects never run and setState is
+// a no-op, so handlers are called off the recorded button props: what is asserted
+// is the request and the toast, not the disabled repaint.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import * as React from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import * as jsxRuntime from "react/jsx-runtime";
+
+import type * as DebugLogsApi from "../src/features/settings/api/debug-logs.ts";
+import * as debugLogBuffer from "../src/features/settings/lib/debug-log-buffer.ts";
+import * as debugLogError from "../src/features/settings/lib/debug-log-error.ts";
+import type * as DebuggingTabModule from "../src/features/settings/tabs/debugging-tab.tsx";
+import { en } from "../src/i18n/locales/en.ts";
+import * as formatFastApiError from "../src/lib/format-fastapi-error.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+const API_URL = new URL(
+ "../src/features/settings/api/debug-logs.ts",
+ import.meta.url,
+);
+const TAB_URL = new URL(
+ "../src/features/settings/tabs/debugging-tab.tsx",
+ import.meta.url,
+);
+const API_BASE = "http://127.0.0.1:7860";
+const UI_TOKEN = "ui-session-token";
+const REFRESHED_TOKEN = "ui-session-token-refreshed";
+const EXPORT_PATH = "/api/settings/debug/logs/export";
+const SAVED_PATH = "/home/tester/Downloads/unsloth-logs-20260910-101112.zip";
+const ARCHIVE_NAME = /^unsloth-logs-\d{8}-\d{6}\.zip$/;
+
+/** The shipped English message, so a renamed key fails here rather than silently. */
+function t(key: string, values?: Record<string, string>): string {
+ const message = key
+ .split(".")
+ .reduce<unknown>(
+ (node, part) => (node as Record<string, unknown> | undefined)?.[part],
+ en as unknown,
+ );
+ assert.equal(typeof message, "string", `no English message for "${key}"`);
+ return String(message).replace(/\{(\w+)\}/g, (match, name: string) =>
+ values && name in values ? values[name] : match,
+ );
+}
+
+type InvokeCall = { command: string; args: unknown };
+type ToastCall = {
+ kind: string;
+ title: string;
+ options: Record<string, unknown> | undefined;
+};
+type ButtonProps = Record<string, unknown>;
+
+/** Let every already-resolved promise in the handler chain settle. */
+async function flush(): Promise<void> {
+ for (let index = 0; index < 5; index += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+}
+
+function makeWorld(options: {
+ isTauri: boolean;
+ invoke?: (command: string, args: unknown) => Promise<unknown>;
+ respond?: () => Response;
+ refreshFails?: boolean;
+}) {
+ const invokes: InvokeCall[] = [];
+ const refreshes: boolean[] = [];
+ let storedToken: string | null = UI_TOKEN;
+ const requests: string[] = [];
+ const downloads: { filename: string; bytes: number }[] = [];
+ const toasts: ToastCall[] = [];
+ const buttons: ButtonProps[] = [];
+ let tauriImports = 0;
+
+ const tauriCore = {
+ invoke: async (command: string, args: unknown) => {
+ invokes.push({ command, args });
+ return options.invoke ? await options.invoke(command, args) : undefined;
+ },
+ };
+
+ const apiStubs: Record<string, unknown> = {
+ "@/features/auth": {
+ authFetch: async (input: string) => {
+ requests.push(input);
+ return options.respond?.() ?? new Response(new Blob(["PK"]));
+ },
+ getAuthToken: () => storedToken,
+ refreshSession: async () => {
+ refreshes.push(true);
+ if (options.refreshFails) {
+ // What the real one does on ANY non-2xx: clear the stored tokens and
+ // resolve false, without throwing. That is why nothing here refreshes
+ // speculatively -- it would sign the user out of the whole app.
+ storedToken = null;
+ return false;
+ }
+ storedToken = REFRESHED_TOKEN;
+ return true;
+ },
+ },
+ "@/lib/api-base": {
+ isTauri: options.isTauri,
+ apiUrl: (path: string) => `${API_BASE}${path}`,
+ },
+ "@/lib/format-fastapi-error": formatFastApiError,
+ "@/lib/native-files": {
+ browserDownload: async (blob: Blob, filename: string) => {
+ downloads.push({ filename, bytes: blob.size });
+ },
+ },
+ "../lib/debug-log-error": debugLogError,
+ };
+ // A getter, so "did the web build reach for Tauri at all?" is answerable:
+ // loadWithStubs reads the entry only when the module actually requires it.
+ Object.defineProperty(apiStubs, "@tauri-apps/api/core", {
+ enumerable: true,
+ get: () => {
+ tauriImports += 1;
+ return tauriCore;
+ },
+ });
+
+ const api = loadWithStubs<typeof DebugLogsApi>(API_URL, apiStubs);
+
+ const toast = {
+ success: (title: string, opts?: Record<string, unknown>) =>
+ toasts.push({ kind: "success", title, options: opts }),
+ error: (title: string, opts?: Record<string, unknown>) =>
+ toasts.push({ kind: "error", title, options: opts }),
+ };
+
+ const { DebuggingTab } = loadWithStubs<typeof DebuggingTabModule>(TAB_URL, {
+ react: React,
+ "react/jsx-runtime": jsxRuntime,
+ "@/components/ui/button": {
+ Button: (props: ButtonProps) => {
+ buttons.push(props);
+ return React.createElement(
+ "button",
+ {
+ type: "button",
+ disabled: props.disabled,
+ "aria-busy": props["aria-busy"],
+ "data-testid": props["data-testid"],
+ },
+ props.children as React.ReactNode,
+ );
+ },
+ },
+ "@/features/hub/hooks/use-copy-feedback": {
+ useCopyFeedback: () => ({ copied: false, copy: async () => {} }),
+ },
+ "@/i18n": { useT: () => t },
+ "@/lib/api-base": apiStubs["@/lib/api-base"],
+ "@/lib/strip-ansi": { stripAnsi: (value: string) => value },
+ "@/lib/toast": { toast },
+ "@hugeicons/core-free-icons": { Tick02Icon: {} },
+ "@hugeicons/react": { HugeiconsIcon: () => null },
+ "../api/debug-logs": api,
+ "../components/settings-row": {
+ SettingsRow: (props: { label: string; children?: React.ReactNode }) =>
+ React.createElement("div", null, props.label, props.children),
+ },
+ "../components/settings-section": {
+ SettingsSection: (props: { title: string; children?: React.ReactNode }) =>
+ React.createElement("section", null, props.title, props.children),
+ },
+ "../lib/debug-log-buffer": debugLogBuffer,
+ "../lib/debug-log-error": debugLogError,
+ });
+
+ function render(): string {
+ buttons.length = 0;
+ return renderToStaticMarkup(React.createElement(DebuggingTab));
+ }
+
+ function button(testId: string): ButtonProps {
+ const found = buttons.find((props) => props["data-testid"] === testId);
+ assert.ok(found, `no button rendered with data-testid="${testId}"`);
+ return found;
+ }
+
+ return {
+ api,
+ buttons,
+ button,
+ downloads,
+ invokes,
+ refreshes,
+ render,
+ requests,
+ toasts,
+ tauriImports: () => tauriImports,
+ };
+}
+
+function jsonResponse(status: number, detail: string): Response {
+ return new Response(JSON.stringify({ detail }), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+test("the desktop export streams through the Tauri command", async () => {
+ const world = makeWorld({
+ isTauri: true,
+ invoke: async () => SAVED_PATH,
+ });
+
+ assert.equal(await world.api.exportAllLogs(), SAVED_PATH);
+ assert.equal(world.invokes.length, 1);
+ assert.equal(world.invokes[0].command, "download_logs_to_downloads");
+ const args = world.invokes[0].args as {
+ url: string;
+ filename: string;
+ uiToken: string | null;
+ };
+ assert.equal(args.url, `${API_BASE}${EXPORT_PATH}`);
+ assert.match(args.filename, ARCHIVE_NAME);
+ // The multi-account fallback. `desktop-login` refuses to mint unconditionally
+ // on a multi-account install, so without this the owner -- signed in, looking
+ // at the owner-only tab -- could never export and signing in again would not
+ // help. The command still prefers a minted session and pins host, port and
+ // path, so this reaches nothing the tab could not reach itself.
+ assert.equal(args.uiToken, UI_TOKEN);
+ // The whole point of the desktop branch: the response never crosses into JS.
+ assert.deepEqual(world.requests, []);
+});
+
+test("the browser export fetches the route and never reaches for Tauri", async () => {
+ const world = makeWorld({ isTauri: false });
+
+ // Null, not a path: only the browser knows where its downloads land.
+ assert.equal(await world.api.exportAllLogs(), null);
+ assert.deepEqual(world.requests, [EXPORT_PATH]);
+ assert.equal(world.downloads.length, 1);
+ assert.match(world.downloads[0].filename, ARCHIVE_NAME);
+ assert.equal(world.invokes.length, 0);
+ assert.equal(world.tauriImports(), 0);
+});
+
+test("openLogsFolder falls back to open_logs_dir when nothing is selected", async () => {
+ const world = makeWorld({ isTauri: true });
+
+ await world.api.openLogsFolder();
+ assert.deepEqual(world.invokes, [
+ { command: "open_logs_dir", args: undefined },
+ ]);
+});
+
+test("an export that works does not touch the session", async () => {
+ // refreshSession clears both stored tokens on ANY non-2xx, so refreshing
+ // before every export would let a transient 500 on /api/auth/refresh sign the
+ // user out of the whole app just for clicking Download all logs.
+ const world = makeWorld({
+ isTauri: true,
+ invoke: async () => SAVED_PATH,
+ });
+
+ await world.api.exportAllLogs();
+ assert.equal(world.refreshes.length, 0, "the export refreshed for no reason");
+});
+
+test("a rejected token is refreshed once and the export retried", async () => {
+ // Rust uses the token once and as-is: it cannot retry a 401 by refreshing the
+ // way authFetch does. Without this, a desktop left idle past the access-token
+ // lifetime fails while holding a perfectly good refresh token. A 401 is also
+ // the one case where refreshing costs nothing, the token having already been
+ // rejected.
+ let attempts = 0;
+ const world = makeWorld({
+ isTauri: true,
+ invoke: async () => {
+ attempts += 1;
+ if (attempts === 1) throw "Download failed with status 401.";
+ return SAVED_PATH;
+ },
+ });
+
+ assert.equal(await world.api.exportAllLogs(), SAVED_PATH);
+ assert.equal(world.refreshes.length, 1);
+ assert.equal(world.invokes.length, 2);
+ const retried = world.invokes[1].args as { uiToken?: string | null };
+ assert.equal(retried.uiToken, REFRESHED_TOKEN, "retried with the dead token");
+});
+
+test("a 401 that cannot be refreshed is reported, not retried", async () => {
+ let attempts = 0;
+ const world = makeWorld({
+ isTauri: true,
+ invoke: async () => {
+ attempts += 1;
+ throw "Download failed with status 401.";
+ },
+ refreshFails: true,
+ });
+
+ await assert.rejects(
+ () => world.api.exportAllLogs(),
+ (error: Error) => error.message.includes("401"),
+ );
+ assert.equal(attempts, 1, "retried with a session that could not be renewed");
+});
+
+test("a failure that is not a 401 never reaches for the refresh token", async () => {
+ const world = makeWorld({
+ isTauri: true,
+ invoke: async () => {
+ throw "Download failed with status 500.";
+ },
+ });
+
+ await assert.rejects(() => world.api.exportAllLogs());
+ assert.equal(world.refreshes.length, 0, "a 500 is not an authentication problem");
+ assert.equal(world.invokes.length, 1);
+});
+
+test("openLogsFolder uses the reported root when no source is selected", async () => {
+ // The custom-home case with nothing readable in it: realpath stays null and
+ // open_logs_dir would send the user to a hard-coded ~/.unsloth/studio.
+ const world = makeWorld({ isTauri: true });
+
+ await world.api.openLogsFolder(null, "/srv/studio-home");
+ assert.deepEqual(world.invokes, [
+ { command: "open_models_dir", args: { path: "/srv/studio-home" } },
+ ]);
+});
+
+test("a selected log still beats the reported root", async () => {
+ const world = makeWorld({ isTauri: true });
+
+ await world.api.openLogsFolder("/srv/other/logs/server/s.log", "/srv/studio-home");
+ assert.deepEqual(world.invokes, [
+ { command: "open_models_dir", args: { path: "/srv/other/logs/server" } },
+ ]);
+});
+
+test("openLogsFolder opens the CONFIGURED home, not the hard-coded one", async () => {
+ // `open_logs_dir` resolves ~/.unsloth/studio and nothing else, while the
+ // picker honours UNSLOTH_STUDIO_HOME and STUDIO_HOME. On a custom home the
+ // button would open an unrelated directory, or error on one that does not
+ // exist. The selected log's own realpath is what makes them agree.
+ const world = makeWorld({ isTauri: true });
+
+ await world.api.openLogsFolder("/srv/studio-home/logs/server/server-1.log");
+ assert.deepEqual(world.invokes, [
+ { command: "open_models_dir", args: { path: "/srv/studio-home/logs/server" } },
+ ]);
+});
+
+test("openLogsFolder handles a Windows realpath", async () => {
+ const world = makeWorld({ isTauri: true });
+
+ await world.api.openLogsFolder("C:\\studio\\logs\\server\\server-1.log");
+ assert.deepEqual(world.invokes, [
+ { command: "open_models_dir", args: { path: "C:\\studio\\logs\\server" } },
+ ]);
+});
+
+test("an archive saved at a filesystem root still reveals that root", async () => {
+ // Dropping the separator here changes the meaning rather than tidying the
+ // path: "" is not "/", and "C:" is the CURRENT directory on drive C: rather
+ // than "C:\", so Show in folder would open the wrong place or nowhere.
+ const unix = makeWorld({ isTauri: true });
+ await unix.api.revealSavedArchive("/unsloth-logs.zip");
+ assert.deepEqual(unix.invokes, [
+ { command: "open_models_dir", args: { path: "/" } },
+ ]);
+
+ const windows = makeWorld({ isTauri: true });
+ await windows.api.revealSavedArchive("C:\\unsloth-logs.zip");
+ assert.deepEqual(windows.invokes, [
+ { command: "open_models_dir", args: { path: "C:\\" } },
+ ]);
+
+ // A bare name has no directory at all, which is still nothing to open.
+ const bare = makeWorld({ isTauri: true });
+ await bare.api.revealSavedArchive("unsloth-logs.zip");
+ assert.deepEqual(bare.invokes, []);
+});
+
+test("a missing export route is reported as an outdated backend", async () => {
+ const world = makeWorld({
+ isTauri: false,
+ respond: () => jsonResponse(404, "Not Found"),
+ });
+
+ const error = await world.api.exportAllLogs().then(
+ () => null,
+ (reason: unknown) => reason,
+ );
+ assert.ok(error instanceof world.api.LogExportError);
+ assert.equal(error.failure, "outdated");
+});
+
+test("a rejected caller is told the session is the problem, not the backend", async () => {
+ const world = makeWorld({
+ isTauri: false,
+ respond: () => jsonResponse(403, "Forbidden"),
+ });
+
+ const error = await world.api.exportAllLogs().then(
+ () => null,
+ (reason: unknown) => reason,
+ );
+ assert.ok(error instanceof world.api.LogExportError);
+ assert.equal(error.failure, "forbidden");
+});
+
+test("the desktop stream failure carries the HTTP status back out of Rust", async () => {
+ const world = makeWorld({
+ isTauri: true,
+ // What `stream_url_to_path` rejects with; Rust hands back a string, not a status.
+ invoke: async () => {
+ throw "Download failed with status 404.";
+ },
+ });
+
+ const error = await world.api.exportAllLogs().then(
+ () => null,
+ (reason: unknown) => reason,
+ );
+ assert.ok(error instanceof world.api.LogExportError);
+ assert.equal(error.failure, "outdated");
+});
+
+test("the download button is offered everywhere, the folder button only on desktop", () => {
+ const web = makeWorld({ isTauri: false });
+ const webMarkup = web.render();
+ assert.ok(webMarkup.includes(t("settings.debugging.downloadAllLogs")));
+ assert.ok(!webMarkup.includes(t("settings.debugging.openLogsFolder")));
+ assert.equal(
+ web.buttons.filter(
+ (props) => props["data-testid"] === "debug-log-open-folder",
+ ).length,
+ 0,
+ );
+ // The masking of credentials in the archive is stated where it is downloaded.
+ assert.ok(webMarkup.includes(t("settings.debugging.exportMaskedNote")));
+
+ const desktop = makeWorld({ isTauri: true });
+ const desktopMarkup = desktop.render();
+ assert.ok(desktopMarkup.includes(t("settings.debugging.openLogsFolder")));
+ assert.equal(desktop.button("debug-log-open-folder")["aria-busy"], false);
+ assert.equal(desktop.button("debug-log-download-all")["aria-busy"], false);
+});
+
+test("a 404 from the tab surfaces the backend-too-old message", async () => {
+ const world = makeWorld({
+ isTauri: false,
+ respond: () => jsonResponse(404, "Not Found"),
+ });
+ world.render();
+
+ (world.button("debug-log-download-all").onClick as () => void)();
+ await flush();
+
+ assert.deepEqual(
+ world.toasts.map((call) => [call.kind, call.title]),
+ [["error", t("settings.debugging.exportTooOld")]],
+ );
+});
+
+test("a desktop export toasts the saved path and reveals that folder", async () => {
+ const world = makeWorld({
+ isTauri: true,
+ invoke: async (command) =>
+ command === "download_logs_to_downloads" ? SAVED_PATH : undefined,
+ });
+ world.render();
+
+ (world.button("debug-log-download-all").onClick as () => void)();
+ await flush();
+
+ assert.equal(world.toasts.length, 1);
+ assert.equal(world.toasts[0].kind, "success");
+ assert.ok(
+ world.toasts[0].title.includes(SAVED_PATH),
+ `toast "${world.toasts[0].title}" does not name the saved file`,
+ );
+
+ // The reveal action must open the folder the toast just named -- Downloads --
+ // not ~/.unsloth/studio, where the logs came from.
+ const action = world.toasts[0].options?.action as {
+ label: string;
+ onClick: () => void;
+ };
+ assert.equal(action.label, t("settings.debugging.showInFolder"));
+ action.onClick();
+ await flush();
+ assert.deepEqual(
+ world.invokes.map((call) => call.command),
+ ["download_logs_to_downloads", "open_models_dir"],
+ );
+ const revealed = world.invokes[1].args as { path: string };
+ assert.ok(
+ SAVED_PATH.startsWith(`${revealed.path}/`),
+ `revealed "${revealed.path}" does not contain the saved file`,
+ );
+ assert.notEqual(revealed.path, SAVED_PATH);
+});
+
+test("the open-logs-folder button still reaches the command", async () => {
+ const world = makeWorld({ isTauri: true, invoke: async () => undefined });
+ world.render();
+
+ (world.button("debug-log-open-folder").onClick as () => void)();
+ await flush();
+
+ assert.deepEqual(
+ world.invokes.map((call) => call.command),
+ ["open_logs_dir"],
+ );
+});
+
+test("a browser export reports the download without naming a folder", async () => {
+ const world = makeWorld({ isTauri: false });
+ world.render();
+
+ (world.button("debug-log-download-all").onClick as () => void)();
+ await flush();
+
+ assert.deepEqual(
+ world.toasts.map((call) => [call.kind, call.title]),
+ [["success", t("settings.debugging.downloadedToBrowser")]],
+ );
+});
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 8b8871131ff..7d96cf20e81 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -1919,6 +1919,7 @@ fn main() {
native_clipboard::read_native_clipboard_png,
native_file_dialogs::save_native_file,
native_file_dialogs::save_native_file_from_url,
+ native_file_dialogs::download_logs_to_downloads,
native_file_dialogs::pick_native_chat_import,
native_file_dialogs::read_native_chat_import_chunk,
native_file_dialogs::pick_native_training_config,
diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rs
index 562be94dd79..3844d92b5c4 100644
--- a/studio/src-tauri/src/native_file_dialogs.rs
+++ b/studio/src-tauri/src/native_file_dialogs.rs
@@ -418,7 +418,7 @@ pub async fn save_native_file_from_url(
let Some(path) = selected_path else {
return Ok(None);
};
- stream_url_to_path(&url, &path, DOWNLOAD_READ_TIMEOUT).await?;
+ stream_url_to_path(&url, &path, DOWNLOAD_READ_TIMEOUT, None).await?;
Ok(Some(saved_file_name(&path)))
}
@@ -426,14 +426,26 @@ pub async fn save_native_file_from_url(
/// clip that is still arriving resets it, so a large save is not cut short.
const DOWNLOAD_READ_TIMEOUT: Duration = Duration::from_secs(30);
-async fn stream_url_to_path(url: &str, path: &Path, read_timeout: Duration) -> Result<(), String> {
- let mut response =
- crate::loopback_http::streaming_client(Duration::from_secs(10), read_timeout)
- .map_err(|error| format!("Download failed: {error}"))?
- .get(url)
- .send()
- .await
- .map_err(|error| format!("Download failed: {error}"))?;
+/// `bearer` carries a UI-session token for routes that demand one. It is always minted by
+/// the command, never handed in over IPC, so the webview cannot choose what this client
+/// authenticates as -- see `download_logs_to_downloads`.
+async fn stream_url_to_path(
+ url: &str,
+ path: &Path,
+ read_timeout: Duration,
+ bearer: Option<&str>,
+) -> Result<(), String> {
+ let request = crate::loopback_http::streaming_client(Duration::from_secs(10), read_timeout)
+ .map_err(|error| format!("Download failed: {error}"))?
+ .get(url);
+ let request = match bearer {
+ Some(token) => request.bearer_auth(token),
+ None => request,
+ };
+ let mut response = request
+ .send()
+ .await
+ .map_err(|error| format!("Download failed: {error}"))?;
// Redirects are refused rather than followed, so a 3xx is a rejection here, not a hop.
if !response.status().is_success() {
return Err(format!(
@@ -461,6 +473,291 @@ async fn stream_url_to_path(url: &str, path: &Path, read_timeout: Duration) -> R
Ok(())
}
+/// The only route `download_logs_to_downloads` may fetch.
+///
+/// A suffix match rather than equality, so an install served under a base path still
+/// resolves. The point is that the path cannot be swapped for another endpoint: the
+/// bearer this command mints is a full UI session, so a caller-chosen path would make a
+/// download button into "read any local route as the signed-in user".
+const LOG_EXPORT_ROUTE: &str = "/api/settings/debug/logs/export";
+const LOG_ARCHIVE_FALLBACK_NAME: &str = "unsloth-logs.zip";
+/// A Downloads folder already holding this many copies has something else wrong with it;
+/// give up rather than stat forever.
+const LOG_ARCHIVE_MAX_COPIES: u32 = 999;
+
+/// Reduce a caller-suggested name to a bare basename.
+///
+/// The destination is chosen here, not by a file chooser, so nothing else stops a
+/// suggested `../../.bashrc` from landing outside it. `Path::file_name` alone is not
+/// enough: a backslash is an ordinary character on Unix, so `..\..\x` would survive it.
+fn log_archive_file_name(suggested: &str) -> String {
+ let base = suggested
+ .rsplit(['/', '\\'])
+ .next()
+ .unwrap_or_default()
+ // A Windows drive-relative name like `C:evil.zip` keeps its prefix through the
+ // separator split and still resolves off this directory.
+ .rsplit(':')
+ .next()
+ .unwrap_or_default();
+ if base.is_empty() || base == "." || base == ".." || base.contains('\0') {
+ return LOG_ARCHIVE_FALLBACK_NAME.to_string();
+ }
+ // The destination falls back to $HOME when the OS has no Downloads folder
+ // (a minimal container, a server image with no user-dirs.dirs), and this
+ // name comes from the webview. A leading dot there is `.bashrc`, and any
+ // other extension is an arbitrary drop. Neither is something a "download
+ // the logs" button should be able to write, and both are free to refuse:
+ // the only real caller sends `unsloth-logs-<stamp>.zip`.
+ if base.starts_with('.') || !base.ends_with(".zip") {
+ return LOG_ARCHIVE_FALLBACK_NAME.to_string();
+ }
+ base.to_string()
+}
+
+/// Where a one-click download belongs, with the fallback the rest of the app uses.
+fn log_archive_directory() -> Result<PathBuf, String> {
+ let directory = dirs::download_dir()
+ .or_else(dirs::home_dir)
+ .ok_or_else(|| "Could not determine home directory".to_string())?;
+ // XDG can name a Downloads folder that was never created.
+ fs::create_dir_all(&directory)
+ .map_err(|error| format!("Failed to prepare {}: {error}", directory.display()))?;
+ Ok(directory)
+}
+
+/// `name.zip`, then `name (2).zip`, the way a browser download uniquifies.
+///
+/// Exporting twice must not silently replace the archive the user is still attaching to
+/// an issue. Best effort by nature -- another process can take the name between the check
+/// and the rename -- but it removes the case that actually happens, which is the same
+/// user pressing the button again.
+fn unique_destination(directory: &Path, file_name: &str) -> Result<PathBuf, String> {
+ let candidate = directory.join(file_name);
+ if !candidate.exists() {
+ return Ok(candidate);
+ }
+ let name = Path::new(file_name);
+ let stem = name
+ .file_stem()
+ .and_then(|stem| stem.to_str())
+ .unwrap_or(file_name);
+ let extension = name.extension().and_then(|extension| extension.to_str());
+ for copy in 2..=LOG_ARCHIVE_MAX_COPIES {
+ let candidate = directory.join(match extension {
+ Some(extension) => format!("{stem} ({copy}).{extension}"),
+ None => format!("{stem} ({copy})"),
+ });
+ if !candidate.exists() {
+ return Ok(candidate);
+ }
+ }
+ Err(format!(
+ "Could not find a free name for {file_name} in {}.",
+ directory.display()
+ ))
+}
+
+const NOT_THE_LOG_EXPORT: &str = "Only the local log export endpoint can be downloaded.";
+
+/// Returned when desktop auth cannot mint a session AND the caller supplied no UI
+/// token of its own. A fixed sentence, matched structurally on the TypeScript side
+/// (`DESKTOP_LOGIN_REQUIRED` in features/settings/api/debug-logs.ts) so the tab can
+/// say "sign in" instead of showing a generic failure. Keep the two in step.
+const LOGIN_REQUIRED: &str = "Log export requires a signed-in Studio session.";
+
+/// Which bearer token the export is made with: a minted desktop session where one
+/// exists, otherwise the tab's own.
+///
+/// The fallback covers two cases that both leave a signed-in owner unable to export.
+/// `desktop-login` answers LoginRequired UNCONDITIONALLY on a multi-account install:
+/// the desktop secret proves the shell owns the backend, not which account is driving
+/// it (routes/auth.py). And minting can fail outright, because provisioning runs the
+/// backend CLI with UNSLOTH_STUDIO_HOME and STUDIO_HOME scrubbed, so an attached
+/// backend under a custom home writes its secret where this code does not read it.
+/// In both, the tab asking for the export is holding a session that reads that very
+/// endpoint perfectly well.
+///
+/// A minting error survives when there is nothing to fall back to: it says far more
+/// about what went wrong than the sentinel would.
+fn select_export_session(
+ minted: Result<crate::desktop_auth::DesktopAuthResponse, String>,
+ ui_token: Option<String>,
+) -> Result<String, String> {
+ let fallback = ui_token.filter(|token| !token.trim().is_empty());
+ match minted {
+ Ok(crate::desktop_auth::DesktopAuthResponse::Tokens { access_token, .. }) => {
+ Ok(access_token)
+ }
+ Ok(crate::desktop_auth::DesktopAuthResponse::LoginRequired { .. }) => {
+ fallback.ok_or_else(|| LOGIN_REQUIRED.to_string())
+ }
+ Err(error) => fallback.ok_or(error),
+ }
+}
+
+/// Refuse anything but the export route, before a token is minted for it.
+///
+/// `Url::parse` normalises `..` segments, so a path that walks out of the route fails
+/// here rather than reaching the backend.
+fn require_log_export_route(url: &str) -> Result<reqwest::Url, String> {
+ let parsed = reqwest::Url::parse(url).map_err(|_| NOT_THE_LOG_EXPORT.to_string())?;
+ if !parsed.path().ends_with(LOG_EXPORT_ROUTE) {
+ return Err(NOT_THE_LOG_EXPORT.to_string());
+ }
+ Ok(parsed)
+}
+
+/// Point the caller's URL at the backend this app is actually running.
+///
+/// The webview names the endpoint; it never names the port. Rebasing onto the live port
+/// pins the authenticated fetch to this install's backend, so it cannot be aimed at some
+/// other loopback listener that would then receive the token. It also means a webview
+/// whose API base is still the `127.0.0.1:0` placeholder resolves correctly here.
+fn pin_to_backend(mut url: reqwest::Url, port: u16) -> Result<String, String> {
+ url.set_host(Some("127.0.0.1"))
+ .map_err(|_| NOT_THE_LOG_EXPORT.to_string())?;
+ url.set_port(Some(port))
+ .map_err(|_| NOT_THE_LOG_EXPORT.to_string())?;
+ // The whole path, not just the host and port. The webview names an endpoint but
+ // gets no say in which one: the bearer minted for this request is a full UI
+ // session, and the backend mounts catch-all routes, so a caller-supplied prefix
+ // is a way to spend that token somewhere else. The desktop API base is only ever
+ // a host and a port, so there is no legitimate prefix to preserve.
+ url.set_path(LOG_EXPORT_ROUTE);
+ // The export takes no parameters, so anything here came from the caller.
+ url.set_query(None);
+ url.set_fragment(None);
+ Ok(url.to_string())
+}
+
+/// The port the backend is serving on, resolved the way desktop auth resolves it.
+///
+/// Read *after* minting a token, so any port discovery that minting performed is already
+/// reflected in the state this reads.
+fn live_backend_port(state: &State<'_, crate::process::BackendState>) -> Result<u16, String> {
+ let backend = state.lock().map_err(|error| error.to_string())?;
+ if let Some(port) = backend.owned_backend_port() {
+ return Ok(port);
+ }
+ // An owned backend whose port is not known yet is starting, not attachable: falling
+ // back to the cached field here would send the token to a stale listener.
+ if backend.has_owned_backend() {
+ return Err("Backend is not ready".to_string());
+ }
+ backend
+ .port
+ .ok_or_else(|| "Backend is not ready".to_string())
+}
+
+/// The rewrite itself, compiled on EVERY platform so that a test for it runs in
+/// ordinary CI rather than only on a Windows runner. Gating the body behind
+/// `cfg(windows)` left the UNC branch below covered on no platform at all.
+///
+/// The prefix compare is case-insensitive: `fs::canonicalize` returns the uppercase
+/// `UNC` spelling today, but a lowercase one would otherwise fall through to the
+/// second arm and come out as `unc\server\share`, which is worse than leaving it
+/// alone -- it looks like a relative path.
+// Off Windows the only caller is the test above, and an ordinary build would
+// otherwise warn that it is never used. Kept compiled rather than cfg'd away,
+// which is the entire point: that is what lets the UNC case be tested here.
+#[cfg_attr(not(windows), allow(dead_code))]
+fn strip_verbatim_prefix_inner(text: String) -> String {
+ const UNC: &str = r"\\?\UNC\";
+ // `get` rather than `text[..UNC.len()]`: a Downloads folder directly under a
+ // drive root with a non-ASCII first component canonicalises to `\\?\C:\下载\...`,
+ // where byte 8 falls inside a multibyte character and slicing would panic --
+ // after the archive had already been saved, so the download succeeds and the
+ // command still fails. `get` answers None there instead.
+ if text
+ .get(..UNC.len())
+ .is_some_and(|head| head.eq_ignore_ascii_case(UNC))
+ {
+ return format!(r"\\{}", &text[UNC.len()..]);
+ }
+ match text.strip_prefix(r"\\?\") {
+ Some(rest) => rest.to_string(),
+ None => text,
+ }
+}
+
+/// Windows canonicalisation returns the `\\?\` verbatim form, which is not the path a
+/// user recognises in a toast. Everywhere else this is the identity.
+#[cfg(windows)]
+fn strip_verbatim_prefix(text: String) -> String {
+ strip_verbatim_prefix_inner(text)
+}
+
+#[cfg(not(windows))]
+fn strip_verbatim_prefix(text: String) -> String {
+ text
+}
+
+/// The absolute, symlink-resolved path to show the user.
+fn display_path(path: &Path) -> String {
+ let resolved = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
+ strip_verbatim_prefix(resolved.display().to_string())
+}
+
+/// Save the backend's log archive straight into the user's Downloads folder.
+///
+/// Sharing a problem means collecting the server log and every runner log by hand, and on
+/// desktop the webview cannot reach the log folder at all. This is the one-click half of
+/// that: no chooser, a known destination, and the real path returned so the UI can say
+/// where the file went and offer to reveal it.
+///
+/// The bearer is minted here rather than accepted as a parameter. The webview already
+/// holds a session, so passing one in would gain it nothing while letting it aim an
+/// arbitrary `Authorization` header at an arbitrary loopback port. Minting internally, and
+/// pinning both the port and the route, keeps this command able to do exactly one thing.
+///
+/// `filename` is a single word on purpose: Tauri renames a snake_case parameter to
+/// camelCase over IPC, and this one is the name the Logs tab already passes.
+/// `ui_token` arrives as `uiToken` for the same reason.
+///
+/// Errors come back with `stream_url_to_path`'s wording, non-2xx included, so the caller
+/// can still tell a 404 (backend too old for the route) and a 403 (no UI session) apart
+/// from a generic failure.
+#[tauri::command]
+pub async fn download_logs_to_downloads(
+ window: WebviewWindow,
+ state: State<'_, crate::process::BackendState>,
+ diagnostics: State<'_, crate::diagnostics::DiagnosticsState>,
+ url: String,
+ filename: String,
+ ui_token: Option<String>,
+) -> Result<String, String> {
+ crate::native_intents::ensure_main_window(&window)?;
+ // Both guards run before anything is minted, so a URL this command will not fetch
+ // never causes a token to exist.
+ require_loopback_url(&url)?;
+ let target = require_log_export_route(&url)?;
+
+ // Minting is attempted either way, because it also resolves and caches the live
+ // port. The refresh token that comes with it is discarded unused; the backend has
+ // no access-token-only exchange to ask for instead. `select_export_session` says
+ // when the tab's own token stands in, and why. Falling back grants the webview
+ // nothing it did not already have: the token is the one it is already holding, and
+ // this command pins the host, the port and the path, so the only thing it can be
+ // spent on is this one route on this install's backend.
+ let minted = crate::desktop_auth::desktop_auth(state.clone(), diagnostics).await;
+ let session = select_export_session(minted, ui_token)?;
+ let pinned_url = pin_to_backend(target, live_backend_port(&state)?)?;
+
+ let directory = log_archive_directory()?;
+ let destination = unique_destination(&directory, &log_archive_file_name(&filename))?;
+ // Staged and renamed, so an interrupted download never leaves a truncated archive
+ // sitting under a name that looks complete.
+ stream_url_to_path(
+ &pinned_url,
+ &destination,
+ DOWNLOAD_READ_TIMEOUT,
+ Some(&session),
+ )
+ .await?;
+ Ok(display_path(&destination))
+}
+
fn read_range(
handle: &Arc<Mutex<File>>,
path: &Path,
@@ -711,7 +1008,7 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("clip.mp4");
test_runtime()
- .block_on(stream_url_to_path(&url, &dest, DOWNLOAD_READ_TIMEOUT))
+ .block_on(stream_url_to_path(&url, &dest, DOWNLOAD_READ_TIMEOUT, None))
.unwrap();
server.join().unwrap();
assert_eq!(fs::read(&dest).unwrap(), body);
@@ -730,7 +1027,7 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("clip.mp4");
let error = test_runtime()
- .block_on(stream_url_to_path(&url, &dest, DOWNLOAD_READ_TIMEOUT))
+ .block_on(stream_url_to_path(&url, &dest, DOWNLOAD_READ_TIMEOUT, None))
.unwrap_err();
server.join().unwrap();
assert!(error.contains("401"), "{error}");
@@ -790,6 +1087,7 @@ mod tests {
&format!("http://127.0.0.1:{port}/clip.mp4"),
&dest,
Duration::from_millis(250),
+ None,
))
.unwrap_err();
drop(release);
@@ -823,6 +1121,7 @@ mod tests {
&format!("http://127.0.0.1:{port}/clip.mp4"),
&dest,
DOWNLOAD_READ_TIMEOUT,
+ None,
))
.unwrap_err();
server.join().unwrap();
@@ -1033,6 +1332,378 @@ mod tests {
let _ = fs::remove_file(path);
}
+ #[test]
+ fn a_suggested_log_archive_name_cannot_escape_the_download_folder() {
+ // No chooser sits between the webview and the filesystem here, so this
+ // function is the whole containment check.
+ let directory = tempfile::tempdir().unwrap();
+ for suggested in [
+ "../../.bashrc",
+ "../unsloth-logs.zip",
+ "/etc/cron.d/unsloth",
+ "..\\..\\Startup\\unsloth.zip",
+ "C:evil.zip",
+ r"C:\Windows\System32\evil.zip",
+ "sub/dir/unsloth-logs.zip",
+ ".",
+ "..",
+ "",
+ "\0",
+ ] {
+ let name = log_archive_file_name(suggested);
+ assert!(
+ !name.contains('/') && !name.contains('\\') && !name.contains(':'),
+ "{suggested} produced {name}"
+ );
+ let resolved = directory.path().join(&name);
+ assert_eq!(
+ resolved.parent(),
+ Some(directory.path()),
+ "{suggested} escaped to {}",
+ resolved.display()
+ );
+ }
+
+ // A name that was already a basename is left exactly alone.
+ assert_eq!(
+ log_archive_file_name("unsloth-logs-20260910-101500.zip"),
+ "unsloth-logs-20260910-101500.zip"
+ );
+ assert_eq!(log_archive_file_name("../.."), LOG_ARCHIVE_FALLBACK_NAME);
+ // $HOME is the destination when the OS has no Downloads folder, and this
+ // name comes from the webview: a dotfile or a non-zip is refused there.
+ assert_eq!(log_archive_file_name(".bashrc"), LOG_ARCHIVE_FALLBACK_NAME);
+ assert_eq!(log_archive_file_name(".ssh"), LOG_ARCHIVE_FALLBACK_NAME);
+ assert_eq!(
+ log_archive_file_name("unsloth-logs.zip.exe"),
+ LOG_ARCHIVE_FALLBACK_NAME
+ );
+ assert_eq!(log_archive_file_name("notes.txt"), LOG_ARCHIVE_FALLBACK_NAME);
+ assert_eq!(
+ log_archive_file_name("unsloth-logs-20260910-101112.zip"),
+ "unsloth-logs-20260910-101112.zip"
+ );
+ }
+
+ #[test]
+ fn a_second_export_gets_its_own_name_instead_of_replacing_the_first() {
+ let directory = tempfile::tempdir().unwrap();
+ let first = unique_destination(directory.path(), "unsloth-logs.zip").unwrap();
+ assert_eq!(first, directory.path().join("unsloth-logs.zip"));
+
+ fs::write(&first, b"first").unwrap();
+ let second = unique_destination(directory.path(), "unsloth-logs.zip").unwrap();
+ assert_eq!(second, directory.path().join("unsloth-logs (2).zip"));
+
+ fs::write(&second, b"second").unwrap();
+ assert_eq!(
+ unique_destination(directory.path(), "unsloth-logs.zip").unwrap(),
+ directory.path().join("unsloth-logs (3).zip")
+ );
+ // The earlier archive is still the one the user was told about.
+ assert_eq!(fs::read(&first).unwrap(), b"first");
+
+ // A name with no extension still uniquifies rather than looping forever.
+ let plain = directory.path().join("logs");
+ fs::write(&plain, b"x").unwrap();
+ assert_eq!(
+ unique_destination(directory.path(), "logs").unwrap(),
+ directory.path().join("logs (2)")
+ );
+
+ // And the search is bounded.
+ for copy in 2..=LOG_ARCHIVE_MAX_COPIES {
+ fs::write(directory.path().join(format!("full ({copy}).zip")), b"x").unwrap();
+ }
+ fs::write(directory.path().join("full.zip"), b"x").unwrap();
+ assert!(unique_destination(directory.path(), "full.zip")
+ .unwrap_err()
+ .contains("free name"));
+ }
+
+ #[test]
+ fn the_log_export_download_is_pinned_to_the_live_backend_and_its_own_route() {
+ fn resolve(url: &str, port: u16) -> Result<String, String> {
+ pin_to_backend(require_log_export_route(url)?, port)
+ }
+
+ // Whatever port the webview names, the fetch goes to the running backend. The
+ // placeholder base a Tauri webview starts with is exactly this case.
+ assert_eq!(
+ resolve("http://127.0.0.1:0/api/settings/debug/logs/export", 8890).unwrap(),
+ "http://127.0.0.1:8890/api/settings/debug/logs/export"
+ );
+ // A caller-supplied prefix is discarded, not preserved: the token minted
+ // for this request is a full UI session and the backend has catch-all
+ // routes, so the path is rebuilt rather than trusted.
+ assert_eq!(
+ resolve(
+ "http://localhost:9/base/api/settings/debug/logs/export",
+ 8890
+ )
+ .unwrap(),
+ "http://127.0.0.1:8890/api/settings/debug/logs/export"
+ );
+
+ // Query and fragment are the caller's, and the export takes neither.
+ assert_eq!(
+ resolve(
+ "http://127.0.0.1:0/api/settings/debug/logs/export?x=1#frag",
+ 8890
+ )
+ .unwrap(),
+ "http://127.0.0.1:8890/api/settings/debug/logs/export"
+ );
+ // A prefix that smuggles another api mount is flattened to the real route.
+ assert_eq!(
+ resolve("http://127.0.0.1:0/api/v1/api/settings/debug/logs/export", 8890).unwrap(),
+ "http://127.0.0.1:8890/api/settings/debug/logs/export"
+ );
+
+ // The bearer is a full UI session, so no other route may be reached with it.
+ for url in [
+ "http://127.0.0.1:8888/api/settings",
+ "http://127.0.0.1:8888/api/settings/debug/logs",
+ "http://127.0.0.1:8888/api/settings/debug/logs/export/../../secrets",
+ "http://127.0.0.1:8888/api/settings/debug/logs/export%2fmore",
+ "http://127.0.0.1:8888/api/auth/api-keys",
+ "not a url",
+ ] {
+ assert!(resolve(url, 8890).is_err(), "should reject {url}");
+ }
+
+ // The loopback guard runs before any of this, and it is the same one the
+ // streaming save uses, so an off-host export never reaches the rebase.
+ for url in [
+ "http://evil.test/api/settings/debug/logs/export",
+ "https://127.0.0.1:8888/api/settings/debug/logs/export",
+ "http://127.0.0.1:[email protected]/api/settings/debug/logs/export",
+ "http://169.254.169.254/api/settings/debug/logs/export",
+ "file:///etc/passwd",
+ ] {
+ assert!(require_loopback_url(url).is_err(), "should reject {url}");
+ }
+ assert!(
+ require_loopback_url("http://127.0.0.1:8888/api/settings/debug/logs/export").is_ok()
+ );
+ }
+
+ /// The four ways the export picks a bearer token. The two fallback rows are the
+ /// point: a signed-in owner on a multi-account install, and one whose minting
+ /// fails because the backend was attached under a custom home, both export with
+ /// the session their tab is already using rather than hitting a dead end.
+ #[test]
+ fn the_tab_token_stands_in_whenever_minting_cannot_produce_a_session() {
+ use crate::desktop_auth::{DesktopAuthResponse, LoginRequired, MultiLoginMode};
+
+ let minted = || {
+ Ok(DesktopAuthResponse::Tokens {
+ access_token: "minted".to_string(),
+ refresh_token: "unused".to_string(),
+ })
+ };
+ let login_required = || {
+ Ok(DesktopAuthResponse::LoginRequired {
+ login_required: LoginRequired,
+ login_mode: MultiLoginMode::Multi,
+ })
+ };
+ let failed = || Err("Desktop auth provisioning failed: no such file".to_string());
+
+ // A minted session always wins, even with a UI token to hand.
+ assert_eq!(
+ select_export_session(minted(), Some("ui".to_string())).unwrap(),
+ "minted"
+ );
+ assert_eq!(select_export_session(minted(), None).unwrap(), "minted");
+
+ // Multi-account install: minting refuses on principle, the tab's token works.
+ assert_eq!(
+ select_export_session(login_required(), Some("ui".to_string())).unwrap(),
+ "ui"
+ );
+ // Attached backend under UNSLOTH_STUDIO_HOME: minting errors, same answer.
+ assert_eq!(
+ select_export_session(failed(), Some("ui".to_string())).unwrap(),
+ "ui"
+ );
+
+ // Blank is not a token, so it must not be mistaken for one.
+ assert_eq!(
+ select_export_session(login_required(), Some(" ".to_string())).unwrap_err(),
+ LOGIN_REQUIRED
+ );
+ // Nothing to fall back to: say "sign in" where that is the reason, and keep
+ // the real error where it is not.
+ assert_eq!(
+ select_export_session(login_required(), None).unwrap_err(),
+ LOGIN_REQUIRED
+ );
+ assert!(
+ select_export_session(failed(), None)
+ .unwrap_err()
+ .starts_with("Desktop auth provisioning failed")
+ );
+ }
+
+ /// The multi-account fallback, asserted where it is decidable without a live
+ /// backend: the tab must actually SEND a token for the command to fall back
+ /// to. `desktop-login` refuses to mint unconditionally when the install is
+ /// multi-account, so if the caller stops passing `uiToken` the export dies
+ /// there permanently, for an owner who is signed in and cannot fix it by
+ /// signing in again.
+ #[test]
+ fn the_tab_sends_a_ui_token_for_the_multi_account_fallback() {
+ let frontend = include_str!("../../frontend/src/features/settings/api/debug-logs.ts");
+ // How the token is spelled at the call site is the frontend's business:
+ // it has already gone from `uiToken: getAuthToken()` to a refreshing
+ // wrapper to a shorthand property, none of which changed the contract.
+ // So pin the part that is ours -- the payload of THIS command names
+ // `uiToken` -- and that the tab still reads a token to put in it.
+ let payload = frontend
+ .split_once("\"download_logs_to_downloads\"")
+ .map(|(_, rest)| rest.chars().take(200).collect::<String>());
+ assert!(
+ payload.as_deref().is_some_and(|p| p.contains("uiToken")),
+ "debug-logs.ts no longer sends uiToken ({payload:?}), so a \
+ multi-account desktop install can never export logs"
+ );
+ assert!(
+ frontend.contains("getAuthToken("),
+ "debug-logs.ts no longer reads a token to send"
+ );
+ }
+
+ /// The login-required sentinel is matched by its exact text on the TypeScript
+ /// side, so a reworded constant here would silently downgrade the toast from
+ /// "sign in" to a generic failure. This fails if the two drift apart.
+ #[test]
+ fn the_login_required_sentinel_matches_what_the_frontend_looks_for() {
+ let frontend = include_str!("../../frontend/src/features/settings/api/debug-logs.ts");
+ assert!(
+ frontend.contains(&format!("\"{LOGIN_REQUIRED}\"")),
+ "debug-logs.ts no longer matches LOGIN_REQUIRED ({LOGIN_REQUIRED:?})"
+ );
+ }
+
+ /// The verbatim rewrite, exercised on whatever platform CI happens to be.
+ ///
+ /// `strip_verbatim_prefix` itself is `cfg(windows)`, so on a Linux or macOS
+ /// runner it is the identity and proves nothing; its only caller resolves to
+ /// the identity too. That left the UNC branch -- the one a user hits when
+ /// Downloads is on a network share -- covered on no platform at all. This
+ /// drives the inner function, which is compiled everywhere.
+ #[test]
+ fn a_verbatim_windows_path_is_shown_the_way_a_user_writes_it() {
+ // Drive-letter form, the ordinary case.
+ assert_eq!(
+ strip_verbatim_prefix_inner(r"\\?\C:\Users\u\Downloads\a.zip".to_string()),
+ r"C:\Users\u\Downloads\a.zip"
+ );
+ // UNC form: `\\?\UNC\server\share` names `\\server\share`, and dropping
+ // only the `\\?\` would leave the nonsense `UNC\server\share`.
+ assert_eq!(
+ strip_verbatim_prefix_inner(r"\\?\UNC\server\share\a.zip".to_string()),
+ r"\\server\share\a.zip"
+ );
+ // Lowercase spelling. canonicalize returns uppercase today, so this is
+ // about not degrading if that ever changes.
+ assert_eq!(
+ strip_verbatim_prefix_inner(r"\\?\unc\server\share\a.zip".to_string()),
+ r"\\server\share\a.zip"
+ );
+ // A non-ASCII first component under a drive root: byte 8 lands inside the
+ // first multibyte character, so a plain `text[..8]` panics here rather
+ // than deciding the prefix does not match.
+ assert_eq!(
+ strip_verbatim_prefix_inner(r"\\?\C:\下载\a.zip".to_string()),
+ r"C:\下载\a.zip"
+ );
+ // The same shape, but long enough that a byte slice would reach past the
+ // character rather than stopping inside the first one.
+ assert_eq!(
+ strip_verbatim_prefix_inner(r"\\?\C:\ダウンロード\a.zip".to_string()),
+ r"C:\ダウンロード\a.zip"
+ );
+ // Anything without the prefix is handed back untouched, including a path
+ // shorter than the prefix itself, which must not panic on the slice.
+ assert_eq!(
+ strip_verbatim_prefix_inner(r"C:\Users\u\a.zip".to_string()),
+ r"C:\Users\u\a.zip"
+ );
+ assert_eq!(strip_verbatim_prefix_inner("/home/u/a.zip".to_string()), "/home/u/a.zip");
+ assert_eq!(strip_verbatim_prefix_inner(r"\\".to_string()), r"\\");
+ assert_eq!(strip_verbatim_prefix_inner(String::new()), "");
+ }
+
+ #[test]
+ fn the_log_export_sends_the_minted_session_and_lands_a_real_path() {
+ // The token is minted in the command, never handed in, so what matters here is
+ // that stream_url_to_path actually puts it on the wire.
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let server = std::thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ let mut request = [0_u8; 2048];
+ let read = std::io::Read::read(&mut stream, &mut request).unwrap();
+ let _ = stream.write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Type: application/zip\r\n\r\nPK",
+ );
+ String::from_utf8_lossy(&request[..read]).to_string()
+ });
+
+ let directory = tempfile::tempdir().unwrap();
+ let destination = directory.path().join("unsloth-logs.zip");
+ test_runtime()
+ .block_on(stream_url_to_path(
+ &format!("http://127.0.0.1:{port}/api/settings/debug/logs/export"),
+ &destination,
+ DOWNLOAD_READ_TIMEOUT,
+ Some("minted-session-token"),
+ ))
+ .unwrap();
+ let request = server.join().unwrap();
+ assert!(
+ request
+ .to_ascii_lowercase()
+ .contains("authorization: bearer minted-session-token"),
+ "{request}"
+ );
+ assert_eq!(fs::read(&destination).unwrap(), b"PK");
+
+ // What the toast shows: absolute, and it names the file that exists.
+ let shown = display_path(&destination);
+ assert!(Path::new(&shown).is_absolute(), "{shown}");
+ assert!(shown.ends_with("unsloth-logs.zip"), "{shown}");
+ assert_eq!(fs::read(&shown).unwrap(), b"PK");
+ }
+
+ #[test]
+ fn an_old_backend_and_a_refused_session_stay_distinguishable_in_the_error() {
+ // The Logs tab reads the status back out of this string to tell "backend too old"
+ // (404) and "not a UI session" (403) apart from a generic failure, so the wording
+ // is a contract, not just a message.
+ for status in ["404 Not Found", "403 Forbidden"] {
+ let (url, server) = serve_once(b"nope".to_vec(), status);
+ let directory = tempfile::tempdir().unwrap();
+ let destination = directory.path().join("unsloth-logs.zip");
+ let error = test_runtime()
+ .block_on(stream_url_to_path(
+ &url,
+ &destination,
+ DOWNLOAD_READ_TIMEOUT,
+ Some("minted-session-token"),
+ ))
+ .unwrap_err();
+ server.join().unwrap();
+ assert_eq!(
+ error,
+ format!("Download failed with status {}.", &status[..3])
+ );
+ assert!(!destination.exists(), "{status} must not create the file");
+ }
+ }
+
#[test]
fn strips_directories_from_suggested_default_name() {
assert_eq!(default_file_name("../../chat.jsonl"), "chat.jsonl");