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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: tighten the Settings > Logs comments (#8769)
Daniel Hanea34ac9d6e2e
diff --git a/studio/backend/utils/debug_log_sources.py b/studio/backend/utils/debug_log_sources.pyindex 9d0261d3be6..3c90a1e2189 100644--- a/studio/backend/utils/debug_log_sources.py+++ b/studio/backend/utils/debug_log_sources.py@@ -20,15 +20,11 @@ from typing import Optional# (subdirectory under a studio home, filename glob).## Python writers: run.py:_setup_server_disk_logging and the llama / diffusion-# runners in core/inference/llama_cpp.py.-#-# The desktop families are written by the Tauri shell-# (src-tauri/src/diagnostics/phase_log.rs) into the logs directory ITSELF, not a-# subdirectory. backend-* is the shell's capture of the backend's stdout and the-# only record that exists when the backend dies BEFORE-# _setup_server_disk_logging runs; without it a user whose app failed to start-# would be told nothing was logged. tauri.log sits at the home root and rotates-# to tauri.log.1.+# runners in core/inference/llama_cpp.py. The desktop families come from the+# Tauri shell (src-tauri/src/diagnostics/phase_log.rs) and land in the logs+# directory ITSELF, with tauri.log at the home root (rotates to tauri.log.1).+# backend-* is the shell's capture of backend stdout, and the only record that+# exists when the backend dies BEFORE _setup_server_disk_logging runs.FAMILIES: dict[str, tuple[str, str]] = {"server": ("logs/server", "server-*.log"),"llama-server": ("logs/llama-server", "llama-*.log"),@@ -41,8 +37,8 @@ FAMILIES: dict[str, tuple[str, str]] = {}# Per family, so a busy host cannot make the picker unusable. Several, not one:-# the llama runner writes a file per load ATTEMPT, so after a retry the-# interesting one is often the second to last.+# the llama runner writes a file per load ATTEMPT, so after a retry the useful+# one is often not the newest.MAX_SOURCES_PER_FAMILY = 10_DIGEST_CHARS = 16@@ -62,11 +58,10 @@ class LogSource:def candidate_roots() -> list[Path]:"""Every studio home a log file might be under, most specific first.- studio_root() infers a root from the installer venv; the llama and diffusion- runners resolve their own base (llama_cpp.py:_swa_cache_path) and do NOT do- that inference. On a venv install with no env var set the two disagree, and- scanning only one of them loses exactly the runtime logs a user chasing a- failed model load came here for.+ studio_root() infers a root from the installer venv; the runners resolve+ their own base (llama_cpp.py:_swa_cache_path) without that inference. On a+ venv install with no env var set the two disagree, so scanning only one+ loses the runtime logs a failed model load is chased through."""roots: list[Path] = []@@ -77,8 +72,8 @@ def candidate_roots() -> list[Path]:resolved = Path(os.path.realpath(path))except (OSError, ValueError):return- # Folded, so a home differing from the inferred root only in case is not- # scanned twice on a case-insensitive volume.+ # Folded, so a case-only difference is not scanned twice on a+ # case-insensitive volume.if not any(_identity(resolved) == _identity(known) for known in roots):roots.append(resolved)@@ -94,14 +89,12 @@ def candidate_roots() -> list[Path]:os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or "").strip()if env_home:- # Both spellings, because the writer and the reader disagree about the- # tilde: _swa_cache_path builds Path(home) raw, so a value passed- # literally (a systemd EnvironmentFile or a dotenv line never runs the- # shell's expansion) makes the runners write to a directory NAMED "~",- # while expanduser sends discovery to the real home. Scanning one of- # them loses the llama and diffusion logs this viewer exists to reach.- # Not the earlier env-versus-legacy case: these are two spellings of one- # value, so neither can be another installation's home.+ # Both spellings, because writer and reader disagree about the tilde:+ # _swa_cache_path builds Path(home) raw, so an unexpanded value (systemd+ # EnvironmentFile, dotenv) makes the runners write to a directory NAMED+ # "~" while expanduser looks in the real home. Safe unlike the+ # env-versus-legacy case above: one value, two spellings, so neither can+ # be another installation's home.for spelling in (Path(env_home).expanduser(), Path(env_home)):try:_add(spelling)@@ -119,19 +112,13 @@ def candidate_roots() -> list[Path]:def _identity(path) -> str:"""One comparable spelling of a path, for containment and for dedup.- Two jobs, both platform quirks:-- os.path.realpath is called separately for the directory and for each entry,- and on Windows ntpath.realpath decides PER CALL whether to keep the- \\\\?\\ extended-length prefix (it strips it only if the short form still- resolves). With a deep studio home on a host without long-path support the- directory can come back as C:\\... while the file comes back as- \\\\?\\C:\\..., which pathlib reads as two different DRIVES: containment then- fails and the whole family is silently dropped.-- normcase folds case on Windows and is the identity on POSIX, so a- case-insensitive volume stops yielding the same file twice under two- spellings while Linux keeps its case-sensitive comparison unchanged.+ Two Windows quirks. realpath is called separately for the directory and for+ each entry, and ntpath.realpath decides PER CALL whether to keep the \\\\?\\+ extended-length prefix, so the directory can come back as C:\\... and the+ file as \\\\?\\C:\\..., which pathlib reads as two different DRIVES:+ containment fails and the whole family is silently dropped. And normcase+ folds case (identity on POSIX), so a case-insensitive volume cannot yield+ one file twice under two spellings."""text = os.path.normcase(str(path))for prefix in ("\\\\?\\unc\\", "\\\\?\\UNC\\", "\\\\?\\"):@@ -167,20 +154,20 @@ def _family_files(family: str) -> list[Path]:except OSError:continue# Nothing prunes logs/llama-server and one file is written per load- # ATTEMPT, so a real install reaches five figures (this host: 11,794).- # realpath + stat on every one cost ~356ms, at a 1 Hz poll. Every+ # ATTEMPT, so a real install reaches five figures (this host: 11,794)+ # and realpath + stat on every one cost ~356ms, at a 1 Hz poll. Every# family's filename embeds its creation time (server-YYYYmmdd-HHMMSS,# llama-<epoch>, diffusion-<epoch>, desktop ms epoch), so name order- # tracks time order and this presort leaves a handful to interrogate.- # Survivors are still ordered by real mtime below, and the slice is wide- # enough to keep a file whose mtime moved after it was written.+ # tracks time order and this presort leaves a handful to stat. Survivors+ # are still ordered by real mtime below, and the slice is wide enough to+ # keep a file whose mtime moved after it was written.entries.sort(key = lambda entry: entry.name, reverse = True)entries = entries[: MAX_SOURCES_PER_FAMILY * 3]for entry in entries:try:real = Path(os.path.realpath(entry))- # The TARGET must stay inside: a symlink dropped into the log- # directory must not become a reader for ~/.ssh/id_rsa.+ # The TARGET must stay inside, so a symlink dropped into the log+ # directory cannot become a reader for ~/.ssh/id_rsa.if not _is_inside(real, real_dir):continueif not real.is_file():@@ -191,8 +178,8 @@ def _family_files(family: str) -> list[Path]:except (OSError, ValueError):continue# Keyed on the folded spelling so a case-insensitive volume cannot- # list the same file twice; the first spelling seen is kept, so the- # id digest stays over the real path.+ # list one file twice; the first spelling seen is kept, so the id+ # digest stays over the real path.found.setdefault(_identity(real), (real, stat.st_mtime))ordered = sorted(found.values(), key = lambda item: item[1], reverse = True)return [path for path, _ in ordered[:MAX_SOURCES_PER_FAMILY]]@@ -200,10 +187,10 @@ def _family_files(family: str) -> list[Path]:def _is_current(family: str, path: Path, newest: Optional[Path]) -> bool:if family == "server":- # uvicorn runs single process here, so our own pid is in the active+ # uvicorn is single process here, so our own pid is in the active# session's filename: an exact match, not a newest-file guess. Anchored- # on the suffix because run.py writes server-{stamp}-pid{pid}, and a- # substring test for "pid1234" also matches a retained ...-pid12345.log.+ # on the suffix because a substring test for "pid1234" would also match+ # a retained ...-pid12345.log.return path.name.endswith(f"-pid{os.getpid()}.log")return newest is not None and path == newest@@ -259,10 +246,9 @@ def default_source_id() -> Optional[str]:if source.family == "server" and source.is_current:return source.id# No live session: the newest file across every family, NOT any retained- # server log. Preferring a stale server log opened the tab on a previous- # run while the llama log holding the failure sat one entry down, which is- # the state after UNSLOTH_STUDIO_NO_FILE_LOG=1 or a failed log setup, the- # two cases where a user is most likely to be looking.+ # server log. Preferring a stale server log opened the tab on a previous run+ # while the llama log holding the failure sat one entry down, which is the+ # state after UNSLOTH_STUDIO_NO_FILE_LOG=1 or a failed log setup.return max(sources, key = lambda s: s.modified_at).id@@ -274,10 +260,9 @@ def source_is_frozen(source_id: Optional[str]) -> bool:"""Whether nothing will ever be appended to this source again.UNSLOTH_STUDIO_NO_FILE_LOG only skips _setup_server_disk_logging in run.py.- The llama and diffusion runners and the Tauri shell keep writing their own- files, so treating the setting as global told a user watching a live- llama-server log that it was an earlier session and would not update while- the failure they came for was still being appended to it.+ The runners and the Tauri shell keep writing their own files, so treating+ the setting as global labelled a live llama-server log an earlier session+ that would not update, while it was still being appended to."""if not file_logging_disabled():return Falsediff --git a/studio/backend/utils/log_redaction.py b/studio/backend/utils/log_redaction.pyindex 3819084b4e5..33da7140a52 100644--- a/studio/backend/utils/log_redaction.py+++ b/studio/backend/utils/log_redaction.py@@ -21,10 +21,10 @@ import reREDACTED = "<redacted>"# Terminal control sequences, stripped BEFORE anything is matched. A colorized-# writer puts an escape between the key and its value (structlog's ConsoleRenderer-# renders "\x1b[36mapi_key\x1b[0m=\x1b[35m<secret>\x1b[0m", and colors default on-# even off-terminal); the "m" ending "\x1b[36m" is a word character, so every-# anchored rule below stops matching and the credential goes out untouched.+# writer puts an escape between the key and its value (ConsoleRenderer emits+# "\x1b[36mapi_key\x1b[0m=\x1b[35m<secret>\x1b[0m", and colors default on even+# off-terminal); the "m" ending "\x1b[36m" is a word character, so every anchored+# rule below stops matching and the credential goes out untouched.## Order matters: OSC (\x1b]) comes before the single-character Fe class, which# covers 0x5C-0x5F and would otherwise swallow the "]" and leave the payload.@@ -45,10 +45,10 @@ _SECRET_KEYS = ("authorization|x-api-key|api[-_]?key|apikey|hf[-_]?token|access[-_]?token|""refresh[-_]?token|auth[-_]?token|bearer[-_]?token|client[-_]?secret|""aws_secret_access_key|aws_session_token|wandb[-_]?token|hub[-_]?token|"- # Studio's own S3 field (models/training.py:60) and its camelCase request- # alias. Neither is reachable through the bare "secret" alternative: the- # trailing \b cannot fire before "_access" or "Access", and an AWS secret- # key has no prefix of its own for a shape rule to catch.+ # Studio's own S3 field (models/training.py:60) and its camelCase alias.+ # Neither is reachable through the bare "secret" alternative (the trailing \b+ # cannot fire before "_access" or "Access"), and an AWS secret key has no+ # prefix of its own for a shape rule to catch."secret[-_]?access[-_]?key|""password|passwd|secret")@@ -96,11 +96,9 @@ _PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (# key = value / "key": "value" / --api-key value## The QUOTED branch wins whenever an opening quote is there, so a quoted-# credential is consumed to its CLOSING quote instead of stopping at the first-# space. Stopping at whitespace turned password="correct horse battery staple"-# into password="<redacted> horse battery staple", which reads as masked while-# leaking all but the first word. Passphrases with spaces are the realistic-# shape, and a partially masked one invites pasting the line into a bug report.+# credential is consumed to its CLOSING quote. Stopping at whitespace turned+# password="correct horse battery staple" into password="<redacted> horse+# battery staple", which reads as masked while leaking all but the first word.## "[^\"'\\\n]|\\." rather than a lazy ".*?" so an escaped quote does not end the# value early; \n is excluded so an unterminated quote cannot run the mask past@@ -125,10 +123,10 @@ _SCHEMES = ("bearer", "basic", "digest", "token", "apikey")# A scheme word only introduces a credential when an Authorization header put it# there. Bare "digest sha256:..." and "token hf_..." are ordinary log content,# and firing on the word alone blanked the digest a user came here to read.-# The credential stops at a quote or a structural delimiter rather than at the-# next space: \S+ swallowed the closing quote and every field behind it, so a-# compact header dict came back as {"Authorization":"Bearer <redacted> with the-# request id and status the user opened the pane to read gone with it.+# The credential stops at a quote or a structural delimiter, not at the next+# space: \S+ swallowed the closing quote and every field behind it, so a compact+# header dict came back as {"Authorization":"Bearer <redacted> with the request+# id and status gone with it._CREDENTIAL = r"[^\s\"',}\]]+"_AUTH_HEADER_RE = re.compile(r"(?i)((?:proxy-)?authorization[\"']?\s*[:=]\s*[\"']?"@@ -139,8 +137,8 @@ _AUTH_HEADER_RE = re.compile(_SCHEME_RE = re.compile(r"(?i)\b(Bearer)(\s+)(" + _CREDENTIAL + r")")# MULTILINE: this also runs over exception text, where the header is not on the# last line. The optional quote matters: headers are usually logged as a dict,-# and an anchored pair test on a value that opened with one never matched, so-# the session cookie gating these very endpoints went out in the clear.+# and the pair test never matched a value that opened with a quote, so the+# session cookie gating these very endpoints went out in the clear._COOKIE_RE = re.compile(r"(?i)\b(?P<key>(?:set-)?cookie)(?P<sep>[\"']?\s*[:=]\s*(?P<q>[\"'])?)(?P<val>\S.*)$",re.MULTILINE,@@ -154,9 +152,9 @@ _NUMERIC_IS_STILL_SECRET = re.compile(r"(?i)pass(word|wd)?$|secret$")def _looks_like_credential(value: str) -> bool:"""Token-shaped rather than an English word.- Guards the rules keyed on a weak name. "Bearer credentials were not- accepted" and "Cookie: disabled" are log content someone opened the viewer- to read, and blanking them hides the failure being diagnosed.+ Guards the rules keyed on a weak name: "Bearer credentials were not+ accepted" and "Cookie: disabled" are log content, and blanking them hides+ the failure being diagnosed."""if len(value) < 8:return False@@ -172,7 +170,6 @@ def _redact_kv(match: re.Match[str]) -> str:# Named groups: the quoted/unquoted branch adds a group, so positional# numbering is not stable.value = match.group("val")- # A numeric value is a count or an id, never a credential.if value.isdigit() and not _NUMERIC_IS_STILL_SECRET.search(match.group("key")):return match.group(0)# Quoting puts the scheme inside the value ('authorization': 'Basic abc').@@ -193,8 +190,8 @@ def _redact_shaped(match: re.Match[str]) -> str:# A cookie header is name=value pairs. _COOKIE_RE takes the rest of the line, so-# without this "Cookie: not sent because the origin is cross-site" is 20-odd-# characters and the length shortcut reads it as a token, masking the diagnosis.+# without this the length shortcut reads "Cookie: not sent because the origin is+# cross-site" as a token and masks the diagnosis._COOKIE_PAIR_RE = re.compile(r"^[A-Za-z0-9_.\-]+=\S")diff --git a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx b/studio/frontend/src/features/settings/tabs/debugging-tab.tsxindex da120d7f8e9..28f65d61470 100644--- a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx@@ -58,20 +58,18 @@ export function DebuggingTab() {const [realpath, setRealpath] = useState<string | null>(null);const [notice, setNotice] = useState<string | null>(null);const [dropped, setDropped] = useState(false);- // Reported by the reader, and until now read by nobody: a burst larger than- // one response continues on the next poll, which in manual mode never comes- // unless the user knows to ask for it.+ // A burst larger than one response continues on the next poll, which in+ // manual mode never comes unless the user knows to ask for it.const [morePending, setMorePending] = useState(false);// File logging is off and an older session's log is still on disk, so the- // pane shows real content that will never grow. Without saying so, a stale- // log is indistinguishable from a live one.+ // pane shows real content that will never grow. Unsaid, a stale log is+ // indistinguishable from a live one.const [staleSession, setStaleSession] = useState(false);const { copied, copy } = useCopyFeedback();// In a ref as well as state: the poll loop must not restart per line arrived.const cursorRef = useRef<string | null>(null);- // Counts source changes, so an in-flight request can tell its view was- // replaced.+ // Counts source changes, so an in-flight request can tell its view moved.const selectionRef = useRef(0);// The selection in flight, not a bare flag: a poll for the newly picked source// must not be swallowed by a slow read of the one the user just left, or the@@ -122,17 +120,17 @@ export function DebuggingTab() {async (error: unknown, signal?: AbortSignal) => {if (isAbort(error)) return;if (isRequestTimeout(error)) {- // Not the raw message: the backstop is an internal number and the user- // needs the consequence, not the duration.+ // Not the raw message: the backstop duration is an internal number, and+ // the user needs the consequence.setNotice(t("settings.debugging.timeout"));return;}if (isLogSourceGone(error)) {// The id we hold is no longer enumerated (file removed, or pushed out of- // the per-family window). The backend sends 404 precisely so the picker- // rebuilds; without this the loop re-polls a dead id forever.- // Reselecting the server's default terminates: it comes from the same- // walk, and "nothing at all" is a 200 with a status, not another 404.+ // the per-family window). The backend sends 404 so the picker rebuilds;+ // without this the loop re-polls a dead id forever. Reselecting the+ // server's default terminates: it comes from the same walk, and+ // "nothing at all" is a 200 with a status, not another 404.cursorRef.current = null;await refreshSources({ signal, reselect: true });return;@@ -144,8 +142,7 @@ export function DebuggingTab() {// The llama runner writes a NEW file per load attempt, so a list fetched at// mount goes stale exactly when it matters: fail a load with the tab open and- // that failure's log is not offered. It is three directory listings, hence the- // slower cadence than the tail poll.+ // that failure's log is not offered.const rescanSourcesIfStale = useCallback(async (signal?: AbortSignal) => {if (Date.now() - lastSourceScanRef.current < SOURCE_RESCAN_MS) return;@@ -162,7 +159,7 @@ export function DebuggingTab() {inFlightRef.current = selection;// Without the timeout a request that never settles pins inFlightRef// forever: every poll returns at the guard above and the pane freezes with- // no error, since the catch never runs. A dropped tunnel is enough.+ // no error, since the catch never runs. A dropped tunnel does it.try {const page = await withRequestTimeout((requestSignal) =>@@ -220,9 +217,9 @@ export function DebuggingTab() {setBuffer(EMPTY_BUFFER);setRealpath(null);// Every notice below describes the file being left, so all of them go with- // it. Clearing only `dropped` let a failed first read on the new source- // keep claiming the OLD one's state, and in manual mode nothing retries to- // correct it: the pane would sit there calling a live log a frozen session.+ // it. Clearing only `dropped` let a failed first read on the new source keep+ // claiming the OLD one's state, and in manual mode nothing retries: the pane+ // sat there calling a live log a frozen session.setDropped(false);setMorePending(false);setStaleSession(false);