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: say why a generation or a model load failed, and offer the log (#8804)

Daniel Han3ae1c2973074
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 152d6b6ba99..13783a588d4 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1668,6 +1668,43 @@ def _log_failed_generation(request_shape: Optional[dict[str, Any]], exc: BaseExc
pass
+VIDEO_GENERATION_FAILED_MSG = "Video generation failed."
+
+_NATIVE_CRASH_NEEDLES = (
+ "sd-cli exited",
+ "process exited",
+ "ggml_abort",
+ "signal",
+ "connection lost",
+ "worker died",
+)
+
+
+def video_failure_detail(exc: BaseException, request_shape: Optional[dict[str, Any]] = None) -> str:
+ """A user-facing reason for a failed generation, built only from fixed text."""
+ try:
+ if _is_out_of_memory(exc):
+ if (
+ request_shape is not None
+ and request_shape.get("attention_backend") is None
+ and sdpa_math_only(_probe_target(request_shape))
+ ):
+ return f"{VIDEO_GENERATION_FAILED_MSG} {SDPA_MATH_ONLY_MESSAGE}"
+ return (
+ f"{VIDEO_GENERATION_FAILED_MSG} The device ran out of memory. Try a smaller "
+ "resolution, fewer frames, or fewer steps."
+ )
+ text = str(exc).lower()
+ if any(needle in text for needle in _NATIVE_CRASH_NEEDLES):
+ return (
+ f"{VIDEO_GENERATION_FAILED_MSG} The renderer stopped unexpectedly. See the "
+ "server log in Settings > Logs for its output."
+ )
+ except Exception: # noqa: BLE001 -- diagnostics never mask the real failure
+ pass
+ return VIDEO_GENERATION_FAILED_MSG
+
+
def _is_out_of_memory(exc: BaseException) -> bool:
"""Whether ``exc`` is an allocator failure, by name and text rather than by class: torch
raises ``torch.OutOfMemoryError`` on CUDA and a plain RuntimeError on some backends."""
@@ -1715,6 +1752,7 @@ class VideoBackend:
self._teardown_waiters = 0
# Generation progress, written by the step callback / phase transitions.
self._gen: dict[str, Any] = {"active": False}
+ self._last_request_shape: Optional[dict[str, Any]] = None
# True from begin_generate() until its worker records a terminal state, so a second call is refused while it
# runs.
self._generate_job_active = False
@@ -6655,6 +6693,7 @@ class VideoBackend:
"total": 0,
"eta_seconds": None,
}
+ self._last_request_shape = None
break
worker = account_thread(
# The token and the /v1/videos job id ride on the target rather than in kwargs: those kwargs are also a
@@ -6785,17 +6824,18 @@ class VideoBackend:
msg = str(exc)
if msg not in (VIDEO_NOT_LOADED_MSG, VIDEO_CANCELLED_MSG):
logger.error("video.generate_failed: %s", exc, exc_info = True)
- msg = "Video generation failed."
+ msg = video_failure_detail(exc, self._last_request_shape)
_record_outcome(msg)
self._finish_generate_job(job_token = job_token, cancel_event = cancel_event, error = msg)
return
except Exception as exc: # noqa: BLE001 -- worker thread: never propagate
logger.error("video.generate_failed: %s", exc, exc_info = True)
- _record_outcome("Video generation failed.")
+ detail = video_failure_detail(exc, self._last_request_shape)
+ _record_outcome(detail)
self._finish_generate_job(
job_token = job_token,
cancel_event = cancel_event,
- error = "Video generation failed.",
+ error = detail,
)
return
@@ -7143,6 +7183,7 @@ class VideoBackend:
"offload": state.offload_policy,
"attention_backend": state.attention_backend,
}
+ self._last_request_shape = request_shape
pipe = state.pipe
call_params = inspect.signature(pipe.__call__).parameters
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 2113471124e..6ae08f6c001 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -41595,7 +41595,7 @@ async def generate_diffusion_image(
raise HTTPException(status_code = 500, detail = _generate_failure_detail(msg))
except Exception as exc:
logger.error("diffusion.generate_failed: %s", exc, exc_info = True)
- raise HTTPException(status_code = 500, detail = "Image generation failed.")
+ raise HTTPException(status_code = 500, detail = _generate_failure_detail(str(exc)))
# Persist each image with its full recipe. BOTH engines batch with a distinct seed per image, returned in ``seeds``, so each is individually reproducible.
created_at = time.time()
@@ -42515,7 +42515,7 @@ async def _generate_openai_images(
detail = openai_error_body(str(exc), status = 400, param = "size"),
)
logger.error("openai_images.generate_failed: %s", exc)
- raise HTTPException(status_code = 500, detail = "Image generation failed.")
+ raise HTTPException(status_code = 500, detail = _generate_failure_detail(str(exc)))
# A local-directory load puts the host path in repo_id and the monitor row goes out over
# the tunnel, so the label gets the same path-free treatment as active_model.
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 534ff033925..db40dfa23d5 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -4128,6 +4128,7 @@ class DebugLogSourceModel(BaseModel):
class DebugLogSourcesResponse(BaseModel):
sources: list[DebugLogSourceModel]
default_source_id: Optional[str] = None
+ matched_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
@@ -4158,6 +4159,7 @@ class DebugLogResponse(BaseModel):
@_owner_settings_router.get("/debug/logs/sources", response_model = DebugLogSourcesResponse)
def get_debug_log_sources(
+ diagnostic_path: Optional[str] = None,
current_subject: str = Depends(get_current_subject),
_ui_session: None = Depends(_require_ui_session),
) -> DebugLogSourcesResponse:
@@ -4179,6 +4181,7 @@ def get_debug_log_sources(
return DebugLogSourcesResponse(
sources = [DebugLogSourceModel(**vars(source)) for source in sources],
default_source_id = debug_log_sources.default_source_id(),
+ matched_source_id = debug_log_sources.source_id_for_path(diagnostic_path, sources),
file_logging_disabled = debug_log_sources.file_logging_disabled(),
log_root = log_root,
)
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 79bc412e1dd..1391a08c02d 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -573,7 +573,7 @@ async def generate_video(
when it is not the resident one."""
from core.inference.gpu_arbiter import VIDEO
from core.inference.media_auto_switch import maybe_auto_switch_media_model
- from core.inference.video import get_video_backend
+ from core.inference.video import get_video_backend, video_failure_detail
from core.inference.video_families import (
VIDEO_GENERATION_BUSY_MSG,
VIDEO_MODEL_CHANGED_MSG,
@@ -692,7 +692,7 @@ async def generate_video(
):
raise HTTPException(status_code = 409, detail = msg)
logger.error("video.generate_failed: %s", exc, exc_info = True)
- raise HTTPException(status_code = 500, detail = "Video generation failed.")
+ raise HTTPException(status_code = 500, detail = video_failure_detail(exc))
break
_note_generation_account()
diff --git a/studio/backend/tests/test_debug_log_sources.py b/studio/backend/tests/test_debug_log_sources.py
index 2dd359c30c4..50d8ce0aedc 100644
--- a/studio/backend/tests/test_debug_log_sources.py
+++ b/studio/backend/tests/test_debug_log_sources.py
@@ -330,3 +330,59 @@ def test_a_live_server_session_still_wins(tmp_path, monkeypatch):
chosen = debug_log_sources.resolve_source_id(debug_log_sources.default_source_id())
assert chosen == current
+
+
+def test_a_writers_own_spelling_of_a_path_resolves_to_its_source():
+ """Only the backend can match the raw path llama_cpp.py printed to a listed source."""
+ path = _seed("llama-server", "llama-1765000101-port-8080.log")
+ expected = next(s for s in debug_log_sources.list_sources() if s.label == path.name).id
+ assert debug_log_sources.source_id_for_path(str(path)) == expected
+ # The realpath spelling too, which is what the listing itself reports.
+ assert debug_log_sources.source_id_for_path(os.path.realpath(path)) == expected
+
+
+def test_a_relative_spelling_resolves_to_the_same_source(monkeypatch):
+ """A relative UNSLOTH_STUDIO_HOME makes the runner print a relative path; it still matches."""
+ path = _seed("llama-server", "llama-1765000102-port-8080.log")
+ expected = next(s for s in debug_log_sources.list_sources() if s.label == path.name).id
+ monkeypatch.chdir(_home())
+ relative = os.path.join("logs", "llama-server", path.name)
+ assert not os.path.isabs(relative)
+ assert relative != str(path), "the two spellings must differ for this to mean anything"
+ assert debug_log_sources.source_id_for_path(relative) == expected
+
+
+def test_an_unexpanded_home_spelling_resolves_to_the_same_source(monkeypatch, tmp_path):
+ """An unexpanded home (systemd EnvironmentFile, dotenv) still matches its listed source."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", "~/studio")
+ directory = tmp_path / "~" / "studio" / "logs" / "llama-server"
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / "llama-1765000103-port-8080.log"
+ path.write_text("boom\n", encoding = "utf-8")
+
+ listed = [s for s in debug_log_sources.list_sources() if s.label == path.name]
+ assert listed, "the runner's own directory must be discoverable at all"
+ raw = os.path.join("~", "studio", "logs", "llama-server", path.name)
+ assert debug_log_sources.source_id_for_path(raw) == listed[0].id
+ assert raw != listed[0].realpath, "the spellings must differ for this to mean anything"
+
+
+def test_a_path_naming_nothing_listed_matches_nothing():
+ """An unmatched path falls back to family recency rather than inventing a match."""
+ _seed("llama-server", "llama-1765000104-port-8080.log")
+ for absent in ("", " ", None, "/nowhere/llama-9.log", "/etc/passwd"):
+ assert debug_log_sources.source_id_for_path(absent) is None, absent
+
+
+def test_a_path_is_matched_against_the_listing_it_is_given(monkeypatch):
+ """The sources route already listed every file; matching must not walk the logs again."""
+ path = _seed("llama-server", "llama-1765000104-port-8080.log")
+ sources = debug_log_sources.list_sources()
+ expected = next(s for s in sources if s.label == path.name).id
+
+ def _no_second_walk():
+ raise AssertionError("listed the logs a second time")
+
+ monkeypatch.setattr(debug_log_sources, "list_sources", _no_second_walk)
+ assert debug_log_sources.source_id_for_path(str(path), sources) == expected
diff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.py
index 3136add0abd..d054fcd2640 100644
--- a/studio/backend/tests/test_openai_images_generations_route.py
+++ b/studio/backend/tests/test_openai_images_generations_route.py
@@ -310,8 +310,12 @@ def test_pipeline_runtime_error_is_sanitized_500(monkeypatch):
monkeypatch.setattr(gallery_module, "save", _save)
resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})
assert resp.status_code == 500
- assert resp.json()["error"]["message"] == "Image generation failed."
+ assert resp.json()["error"]["message"] == (
+ "Image generation failed. The device ran out of memory. Try a smaller size, fewer "
+ "steps, or a smaller batch."
+ )
assert "CUDA" not in resp.text # raw exception text must not leak
+ assert "GiB" not in resp.text and "GPU 0" not in resp.text
def test_unload_race_returns_503(monkeypatch):
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index 86cdeb66525..dffe55069f7 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -629,7 +629,7 @@ def test_generate_cancelled_reports_failed_with_sentinel(client, monkeypatch):
def test_generate_pipeline_error_reports_sanitized_failure(client, monkeypatch):
- # A loaded model failing mid-pipeline (CUDA OOM) is a server failure: the terminal state carries a generic message, never the raw exception.
+ # A loaded model failing mid-pipeline (CUDA OOM) is a server failure.
backend = video_module.get_video_backend()
backend.loaded = True
@@ -638,8 +638,51 @@ def test_generate_pipeline_error_reports_sanitized_failure(client, monkeypatch):
monkeypatch.setattr(backend, "generate", _oom)
progress = _shared_setup_4(client)
- assert progress["error"] == "Video generation failed."
+ assert progress["error"].startswith("Video generation failed.")
+ assert "ran out of memory" in progress["error"]
+ # The engine's own text stays server-side.
assert "CUDA" not in progress["error"]
+ assert "40.00 GiB" not in progress["error"]
+
+
+def test_generate_unclassified_error_keeps_the_bare_fallback(client, monkeypatch):
+ # Nothing recognised means nothing invented: the message must not grow a guess.
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+
+ def _odd(**kwargs):
+ raise RuntimeError("something went sideways in /home/u/models/secret.safetensors")
+
+ monkeypatch.setattr(backend, "generate", _odd)
+ progress = _shared_setup_4(client)
+ assert progress["error"] == "Video generation failed."
+ assert "secret.safetensors" not in progress["error"]
+
+
+def test_generate_native_crash_points_at_the_log(client, monkeypatch):
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+
+ def _crash(**kwargs):
+ raise RuntimeError("worker process exited with signal 6")
+
+ monkeypatch.setattr(backend, "generate", _crash)
+ progress = _shared_setup_4(client)
+ assert "Settings > Logs" in progress["error"]
+
+
[email protected]("code", ["-6", "3221225477"])
+def test_generate_native_sd_cli_exit_points_at_the_log(client, monkeypatch, code):
+ backend = video_module.get_video_backend()
+ backend.loaded = True
+
+ def _crash(**kwargs):
+ raise RuntimeError(f"sd-cli exited {code}. Last output:\nGGML_ASSERT(n_dims == 3) failed")
+
+ monkeypatch.setattr(backend, "generate", _crash)
+ progress = _shared_setup_4(client)
+ assert "Settings > Logs" in progress["error"]
+ assert "GGML_ASSERT" not in progress["error"]
def test_generate_value_error_reports_reason(client, monkeypatch):
diff --git a/studio/backend/utils/debug_log_sources.py b/studio/backend/utils/debug_log_sources.py
index e6748cc635b..c7e64f67ddb 100644
--- a/studio/backend/utils/debug_log_sources.py
+++ b/studio/backend/utils/debug_log_sources.py
@@ -193,6 +193,30 @@ def resolve_source_id(source_id: str) -> Optional[Path]:
return None
+def source_id_for_path(
+ raw: Optional[str], sources: Optional[list[LogSource]] = None
+) -> Optional[str]:
+ """The opaque id of the source a WRITER's own spelling of a path names, if any."""
+ if not isinstance(raw, str) or not raw.strip():
+ return None
+ wanted = set()
+ for expand in (False, True):
+ try:
+ spelling = Path(raw.strip())
+ wanted.add(_identity(os.path.realpath(spelling.expanduser() if expand else spelling)))
+ except (OSError, ValueError, RuntimeError):
+ pass
+ if not wanted:
+ return None
+ for source in list_sources() if sources is None else sources:
+ try:
+ if _identity(os.path.realpath(source.realpath)) in wanted:
+ return source.id
+ except (OSError, ValueError):
+ continue
+ return None
+
+
def default_source_id() -> Optional[str]:
"""The active server session if we have one, else the newest log we found."""
sources = list_sources()
diff --git a/studio/frontend/src/features/auth/account-session.ts b/studio/frontend/src/features/auth/account-session.ts
index 59931d53985..0c2394ce5f9 100644
--- a/studio/frontend/src/features/auth/account-session.ts
+++ b/studio/frontend/src/features/auth/account-session.ts
@@ -50,12 +50,13 @@ function subscribeSession(listener: () => void): () => void {
for (const event of events) window.removeEventListener(event, listener);
};
}
+/** Ownership outside a component body, for a callback that cannot call a hook. */
+export function isAccountOwner(): boolean {
+ return sessionAccount(getAuthToken())?.isOwner ?? false;
+}
+
export function useIsAccountOwner(): boolean {
- return useSyncExternalStore(
- subscribeSession,
- () => sessionAccount(getAuthToken())?.isOwner ?? false,
- () => false,
- );
+ return useSyncExternalStore(subscribeSession, isAccountOwner, () => false);
}
export function useLoginMode() {
const mode = useSyncExternalStore(
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 030e20868a0..aa3db0e8fc4 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -33,6 +33,11 @@ import {
serverWideReloadRequired,
} from "../lib/server-wide-reload";
import { isSettingsRouteAbsent } from "@/features/settings/api/settings-route-absent";
+import {
+ failureLogPath,
+ loadFailureLogFamily,
+ viewLogsAction,
+} from "@/features/settings/lib/view-logs-action";
import { loadModelMemorySettings } from "@/features/settings/api/model-memory";
import { loadVramBudgetSettings } from "@/features/settings/api/vram-budget";
import { loadOpenAIAutoSwitchSettings } from "@/features/settings";
@@ -3353,12 +3358,25 @@ export function useChatModelRuntime() {
if (!abortCtrl.signal.aborted) {
const message =
err instanceof Error ? err.message : "Failed to load model";
+ const [summary, ...rest] = message.split("\n");
+ const detail = rest.join("\n").trim();
+ const runnerLogPath = failureLogPath(message);
+ const logsAction = runnerLogPath
+ ? viewLogsAction(
+ loadFailureLogFamily(isGguf, isDiffusion, runnerLogPath),
+ runnerLogPath,
+ )
+ : undefined;
if (loadToastDismissedRef.current) {
- toast.error(message);
+ toast.error(summary, {
+ description: detail || undefined,
+ action: logsAction,
+ });
} else {
- toast.error(message, {
+ toast.error(summary, {
id: toastId,
- description: undefined,
+ description: detail || undefined,
+ action: logsAction,
cancel: undefined,
classNames: undefined,
closeButton: true,
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index b1850fbad6d..04469756919 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -1,6 +1,7 @@
// 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 { generationFailureLogsAction } from "@/features/settings/lib/view-logs-action";
import { readImageModel, rememberImageModel, matchesRememberedModel, type RememberedImageModel } from "./image-model-recall";
import {
type ReactNode,
@@ -4216,7 +4217,8 @@ export function ImagesPage({
onClick: () => setOversizedRetryQueued(true),
},
});
- } else if (report) toast.error(msg);
+ } else if (report)
+ toast.error(msg, { action: generationFailureLogsAction(msg) });
} finally {
if (genPollTimer.current) clearInterval(genPollTimer.current);
genPollTimer.current = null;
diff --git a/studio/frontend/src/features/settings/api/debug-logs.ts b/studio/frontend/src/features/settings/api/debug-logs.ts
index 7902732fd88..a60140ec880 100644
--- a/studio/frontend/src/features/settings/api/debug-logs.ts
+++ b/studio/frontend/src/features/settings/api/debug-logs.ts
@@ -29,6 +29,8 @@ export interface DebugLogSource {
export interface DebugLogSources {
sources: DebugLogSource[];
defaultSourceId: string | null;
+ /** The source a diagnostic's own path names, canonicalised by the backend. */
+ matchedSourceId: string | null;
fileLoggingDisabled: boolean;
/** Where the logs live. Null on a backend older than this field. */
logRoot: string | null;
@@ -52,8 +54,12 @@ export interface DebugLogPage {
export async function loadDebugLogSources(
signal?: AbortSignal,
+ diagnosticPath?: string | null,
): Promise<DebugLogSources> {
- const response = await authFetch("/api/settings/debug/logs/sources", {
+ const query = diagnosticPath
+ ? `?diagnostic_path=${encodeURIComponent(diagnosticPath)}`
+ : "";
+ const response = await authFetch(`/api/settings/debug/logs/sources${query}`, {
signal,
});
if (!response.ok) {
@@ -73,6 +79,7 @@ export async function loadDebugLogSources(
isCurrent: Boolean(source.is_current),
})),
defaultSourceId: body.default_source_id ?? null,
+ matchedSourceId: body.matched_source_id ?? null,
fileLoggingDisabled: Boolean(body.file_logging_disabled),
logRoot: body.log_root ?? null,
};
@@ -156,7 +163,8 @@ const DESKTOP_STATUS_PATTERN = /^Download failed with status (\d{3})\./;
// 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 Unsloth session.";
+const DESKTOP_LOGIN_REQUIRED =
+ "Log export requires a signed-in Unsloth session.";
function desktopExportError(error: unknown): LogExportError {
const message =
diff --git a/studio/frontend/src/features/settings/lib/view-logs-action.ts b/studio/frontend/src/features/settings/lib/view-logs-action.ts
new file mode 100644
index 00000000000..00a5dd7dc61
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/view-logs-action.ts
@@ -0,0 +1,59 @@
+// 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 { isAccountOwner } from "@/features/auth/account-session";
+import { translate } from "@/i18n";
+import { useSettingsDialogStore } from "../stores/settings-dialog-store";
+
+export type FailureLogFamily = "llama-server" | "diffusion-server" | "server";
+
+export function loadFailureLogFamily(
+ isGguf: boolean | undefined,
+ isDiffusion: boolean | undefined,
+ runnerLogPath: string | null | undefined,
+): FailureLogFamily {
+ if (!runnerLogPath || !isGguf) return "server";
+ return isDiffusion === true ? "diffusion-server" : "llama-server";
+}
+
+/** Pull the log path out of a load diagnostic (`llama_cpp.py` appends `Full log: <path>`). */
+export function failureLogPath(message: string): string | null {
+ const at = message.lastIndexOf("Full log: ");
+ if (at === -1) return null;
+ const path = message
+ .slice(at + "Full log: ".length)
+ .split("\n")[0]
+ .trim();
+ return path || null;
+}
+
+export function viewLogsAction(
+ family: FailureLogFamily,
+ sourcePath?: string | null,
+):
+ | {
+ label: string;
+ onClick: () => void;
+ }
+ | undefined {
+ if (!isAccountOwner()) return undefined;
+ return {
+ label: translate("settings.debugging.viewLogs"),
+ onClick: () =>
+ useSettingsDialogStore.getState().openLogs(family, sourcePath ?? null),
+ };
+}
+
+// Messages the backend writes to the server log; client-input refusals carry their own text instead.
+const LOGGED_GENERATION_FAILURES = [
+ "Image generation failed.",
+ "Video generation failed.",
+ "Failed to save the generated image.",
+ "Failed to save the generated video.",
+];
+
+export function generationFailureLogsAction(message: string) {
+ return LOGGED_GENERATION_FAILURES.some((prefix) => message.startsWith(prefix))
+ ? viewLogsAction("server")
+ : undefined;
+}
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 99e2a50e579..eb8ad65a27e 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -57,6 +57,10 @@ interface SettingsDialogState {
// toast). DataTab uses it as its initial subpage, then clears it. See requestsFor
// for how long it lives unconsumed.
archivedRequested: ArchivedShelf | null;
+ logFamilyRequested: string | null;
+ logSourcePathRequested: string | null;
+ /** Bumped per View logs click, so a repeated identical request still reads as new. */
+ logRequestSeq: number;
// Set when something asks for one connection's settings (the picker's Connected group gear).
// ConnectionsTab hands it to the form, then clears it. Same lifetime as archivedRequested.
connectionRequested: string | null;
@@ -66,6 +70,8 @@ interface SettingsDialogState {
/** Open Connections with `providerId`'s edit form already up. */
openConnectionSettings: (providerId: string) => void;
consumeArchivedChatsRequest: () => void;
+ openLogs: (family?: string, sourcePath?: string | null) => void;
+ consumeLogFamilyRequest: () => void;
consumeConnectionRequest: () => void;
consumeScrollTarget: (target: SettingsScrollTarget) => void;
closeDialog: () => void;
@@ -141,11 +147,27 @@ function requestsFor(state: SettingsDialogState, tab: SettingsTab) {
? state.scrollTarget
: null,
archivedRequested: tab === "data" ? state.archivedRequested : null,
+ logFamilyRequested: tab === "debugging" ? state.logFamilyRequested : null,
+ logSourcePathRequested:
+ tab === "debugging" ? state.logSourcePathRequested : null,
connectionRequested:
tab === "connections" ? state.connectionRequested : null,
};
}
+export const NO_PENDING_LOG_REQUEST = "|";
+
+export function pendingLogRequestKey(state: {
+ logFamilyRequested: string | null;
+ logSourcePathRequested: string | null;
+ logRequestSeq?: number;
+}): string {
+ if (state.logFamilyRequested == null && state.logSourcePathRequested == null)
+ return NO_PENDING_LOG_REQUEST;
+ return `${state.logFamilyRequested ?? ""}|${state.logSourcePathRequested ?? ""}|${state.logRequestSeq ?? 0}`;
+}
+
+
export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
open: false,
activeTab: loadInitialTab(),
@@ -153,6 +175,9 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
opener: null,
openerFallback: null,
archivedRequested: null,
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
+ logRequestSeq: 0,
connectionRequested: null,
openDialog: (tab, options) =>
set((state) => {
@@ -164,6 +189,8 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
// A caller that names a target replaces whatever was still pending.
scrollTarget: options?.scrollTarget ?? pending.scrollTarget,
archivedRequested: pending.archivedRequested,
+ logFamilyRequested: pending.logFamilyRequested,
+ logSourcePathRequested: pending.logSourcePathRequested,
connectionRequested: pending.connectionRequested,
...focusForOpen(state, options?.focusFallback),
};
@@ -174,6 +201,8 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
activeTab: "data",
scrollTarget: null,
archivedRequested: "chats",
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
connectionRequested: null,
...focusForOpen(state),
})),
@@ -183,6 +212,8 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
activeTab: "data",
scrollTarget: null,
archivedRequested: shelf,
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
connectionRequested: null,
...focusForOpen(state),
})),
@@ -192,10 +223,26 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
activeTab: "connections",
scrollTarget: null,
archivedRequested: null,
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
connectionRequested: providerId,
...focusForOpen(state),
})),
consumeArchivedChatsRequest: () => set({ archivedRequested: null }),
+ openLogs: (family, sourcePath) =>
+ set((state) => ({
+ open: true,
+ activeTab: "debugging",
+ scrollTarget: null,
+ archivedRequested: null,
+ logFamilyRequested: family ?? null,
+ logSourcePathRequested: sourcePath ?? null,
+ logRequestSeq: state.logRequestSeq + 1,
+ connectionRequested: null,
+ ...focusForOpen(state),
+ })),
+ consumeLogFamilyRequest: () =>
+ set({ logFamilyRequested: null, logSourcePathRequested: null }),
consumeConnectionRequest: () => set({ connectionRequested: null }),
consumeScrollTarget: (target) =>
set((state) => ({
@@ -209,6 +256,8 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
open: false,
scrollTarget: null,
archivedRequested: null,
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
connectionRequested: null,
}),
setActiveTab: (tab) => {
diff --git a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
index eeb9f313879..0f9fda6b410 100644
--- a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
@@ -70,6 +70,11 @@ import {
withRequestTimeout,
} from "../lib/debug-log-buffer";
import { isAbort, isLogSourceGone } from "../lib/debug-log-error";
+import {
+ NO_PENDING_LOG_REQUEST,
+ pendingLogRequestKey,
+ useSettingsDialogStore,
+} from "../stores/settings-dialog-store";
const MODES: RefreshMode[] = ["live", "3s", "manual"];
@@ -183,22 +188,54 @@ export function DebuggingTab() {
}
}, [mode]);
+ // Selection order: a response older than the last one that selected never overrides it.
+ const sourceFetchSeqRef = useRef(0);
+ const appliedSourceFetchRef = useRef(0);
+
const refreshSources = useCallback(
async (options: { signal?: AbortSignal; reselect?: boolean } = {}) => {
+ const seq = ++sourceFetchSeqRef.current;
try {
// Bounded like the tail read: the poll loop and its failure recovery
// both await this, so an unanswered /sources would freeze both.
+ const requestedFor = pendingLogRequestKey(
+ useSettingsDialogStore.getState(),
+ );
+ const pendingPath =
+ useSettingsDialogStore.getState().logSourcePathRequested;
const result = await withRequestTimeout(
- (signal) => loadDebugLogSources(signal),
+ (signal) => loadDebugLogSources(signal, pendingPath),
REQUEST_TIMEOUT_MS,
options.signal,
);
+ if (seq < appliedSourceFetchRef.current) return;
setSources(result.sources);
setLogRoot(result.logRoot);
+ const dialog = useSettingsDialogStore.getState();
+ const requested = dialog.logFamilyRequested;
+ const byPath = result.matchedSourceId
+ ? result.sources.find(
+ (source) => source.id === result.matchedSourceId,
+ )
+ : undefined;
+ const fromFailure =
+ byPath ??
+ (requested
+ ? result.sources.find((source) => source.family === requested)
+ : undefined);
+ // Only the request this fetch was made for.
+ const stillTheSameRequest =
+ pendingLogRequestKey(dialog) === requestedFor;
+ if (fromFailure && stillTheSameRequest)
+ useSettingsDialogStore.getState().consumeLogFamilyRequest();
+ if (fromFailure && !stillTheSameRequest) return;
+ appliedSourceFetchRef.current = seq;
setSourceId((current) =>
- options.reselect
- ? result.defaultSourceId
- : (current ?? result.defaultSourceId),
+ fromFailure
+ ? fromFailure.id
+ : options.reselect
+ ? result.defaultSourceId
+ : (current ?? result.defaultSourceId),
);
} catch {
// The log read reports the real reason; this just leaves the picker empty.
@@ -213,6 +250,15 @@ export function DebuggingTab() {
return () => controller.abort();
}, [refreshSources]);
+ // A request that arrives while this panel is ALREADY mounted.
+ const pendingLogRequest = useSettingsDialogStore(pendingLogRequestKey);
+ useEffect(() => {
+ if (pendingLogRequest === NO_PENDING_LOG_REQUEST) return;
+ const controller = new AbortController();
+ void refreshSources({ signal: controller.signal });
+ return () => controller.abort();
+ }, [pendingLogRequest, refreshSources]);
+
const onPollFailed = useCallback(
async (error: unknown, signal?: AbortSignal) => {
if (isAbort(error)) return;
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index a0543928d07..5a5a9e1fe3b 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -1,6 +1,7 @@
// 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 { generationFailureLogsAction } from "@/features/settings/lib/view-logs-action";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
ArrowExpand01Icon,
@@ -2433,7 +2434,8 @@ function VideoGenerator({
} else if (p.phase === "failed") {
const msg = p.error || "Video generation failed";
// The user's own Cancel surfaces as the backend's cancelled sentinel; not an error.
- if (!msg.toLowerCase().includes("cancelled")) toast.error(msg);
+ if (!msg.toLowerCase().includes("cancelled"))
+ toast.error(msg, { action: generationFailureLogsAction(msg) });
}
return;
}
@@ -2503,7 +2505,8 @@ function VideoGenerator({
// The other terminal phase, kept only until the next job: without this a reload after a failed
// generation shows an idle page and loses the error.
const msg = g.error || "Video generation failed";
- if (!msg.toLowerCase().includes("cancelled")) toast.error(msg);
+ if (!msg.toLowerCase().includes("cancelled"))
+ toast.error(msg, { action: generationFailureLogsAction(msg) });
}
} catch {
// Resume is best-effort; a failed probe just leaves the idle view.
@@ -3438,7 +3441,8 @@ function VideoGenerator({
});
} catch (err) {
if (!isMounted.current) return;
- toast.error(err instanceof Error ? err.message : "Video generation failed");
+ const refusal = err instanceof Error ? err.message : "Video generation failed";
+ toast.error(refusal, { action: generationFailureLogsAction(refusal) });
setBusy(null);
setGenStep(null);
// The refusal can be "No video model is loaded": re-read rather than leave Generate enabled
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 6c9f75f04ab..0eb064fd346 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -716,6 +716,7 @@ export const ar = {
disabled: "التسجيل في ملف مُعطَّل (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "لم يُعثر على أي ملف سجل.",
unreadable: "تعذّرت قراءة ملف السجل.",
+ viewLogs: "عرض السجلات",
timeout: "انتهت مهلة طلب السجل. قد يتعذر الوصول إلى الخادم.",
droppedNotice: "تم تخطي بعض الأسطر: كُتب السجل بسرعة أكبر مما أمكن قراءته.",
morePending: "لا يزال يجري قراءة أسطر إضافية، وستظهر عند التحديث التالي.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index c079adcc15b..5c392a85420 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -720,6 +720,7 @@ export const de = {
disabled: "Die Protokollierung in eine Datei ist deaktiviert (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "Es wurde keine Protokolldatei gefunden.",
unreadable: "Die Protokolldatei konnte nicht gelesen werden.",
+ viewLogs: "Protokolle anzeigen",
timeout: "Die Protokollanfrage hat das Zeitlimit uberschritten. Der Server ist moglicherweise nicht erreichbar.",
droppedNotice: "Einige Zeilen wurden übersprungen: Das Protokoll wurde schneller geschrieben, als es gelesen werden konnte.",
morePending: "Weitere Zeilen werden noch gelesen; sie erscheinen bei der nachsten Aktualisierung.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index b3c2143dda5..1b1d4b11336 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -723,6 +723,7 @@ export const en = {
disabled: "File logging is turned off (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "No log file was found.",
unreadable: "The log file could not be read.",
+ viewLogs: "View logs",
timeout: "The log request timed out. The server may be unreachable.",
droppedNotice: "Some lines were skipped: the log was written faster than it could be read.",
morePending: "More lines are still being read; they arrive on the next refresh.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 8b34caf4db2..91a51f119dd 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -719,6 +719,7 @@ export const es = {
disabled: "El registro en archivo está desactivado (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "No se encontró ningún archivo de registro.",
unreadable: "No se pudo leer el archivo de registro.",
+ viewLogs: "Ver registros",
timeout: "La solicitud del registro agoto el tiempo de espera. Puede que el servidor no este accesible.",
droppedNotice: "Se omitieron algunas líneas: el registro se escribió más rápido de lo que se podía leer.",
morePending: "Aun se estan leyendo mas lineas; llegaran en la proxima actualizacion.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 221020062bb..4820d732201 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -720,6 +720,7 @@ export const fr = {
disabled: "La journalisation dans un fichier est désactivée (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "Aucun fichier journal n'a été trouvé.",
unreadable: "Le fichier journal n'a pas pu être lu.",
+ viewLogs: "Voir les journaux",
timeout: "La demande du journal a expire. Le serveur est peut-etre injoignable.",
droppedNotice: "Certaines lignes ont été ignorées : le journal a été écrit plus vite qu'il ne pouvait être lu.",
morePending: "D'autres lignes sont encore en cours de lecture ; elles arriveront au prochain rafraichissement.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 291d24dfe6e..5d092ce307d 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -719,6 +719,7 @@ export const hi = {
disabled: "फ़ाइल में लॉगिंग बंद है (UNSLOTH_STUDIO_NO_FILE_LOG=1)।",
missing: "कोई लॉग फ़ाइल नहीं मिली।",
unreadable: "लॉग फ़ाइल पढ़ी नहीं जा सकी।",
+ viewLogs: "लॉग देखें",
timeout: "लॉग अनुरोध का समय समाप्त हो गया। सर्वर तक पहुंच नहीं हो पा रही है।",
droppedNotice: "कुछ पंक्तियाँ छोड़ दी गईं: लॉग इतनी तेज़ी से लिखा गया कि उसे पढ़ा नहीं जा सका।",
morePending: "और पंक्तियां अभी पढ़ी जा रही हैं; वे अगले रिफ्रेश पर आएंगी।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 6982f56c352..daacd57f9aa 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -679,6 +679,7 @@ export const it = {
disabled: "La registrazione su file è disattivata (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "Nessun file di log trovato.",
unreadable: "Non è stato possibile leggere il file di log.",
+ viewLogs: "Vedi i log",
timeout: "La richiesta del log e scaduta. Il server potrebbe non essere raggiungibile.",
droppedNotice: "Alcune righe sono state saltate: il log è stato scritto più velocemente di quanto potesse essere letto.",
morePending: "Altre righe sono ancora in lettura; arriveranno al prossimo aggiornamento.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index aeb58f0b277..a1b9bce5f83 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -718,6 +718,7 @@ export const ja = {
disabled: "ファイルへのログ出力は無効です (UNSLOTH_STUDIO_NO_FILE_LOG=1)。",
missing: "ログファイルが見つかりませんでした。",
unreadable: "ログファイルを読み取れませんでした。",
+ viewLogs: "ログを表示",
timeout: "ログの取得がタイムアウトしました。サーバーに接続できない可能性があります。",
droppedNotice: "一部の行がスキップされました。ログの書き込みが読み取りに追いつきませんでした。",
morePending: "さらに行を読み込み中です。次回の更新時に表示されます。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index ea87879e5d1..380a722270f 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -716,6 +716,7 @@ export const ko = {
disabled: "파일 로깅이 꺼져 있습니다 (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "로그 파일을 찾을 수 없습니다.",
unreadable: "로그 파일을 읽을 수 없습니다.",
+ viewLogs: "로그 보기",
timeout: "로그 요청 시간이 초과되었습니다. 서버에 연결할 수 없을 수 있습니다.",
droppedNotice: "일부 줄이 누락되었습니다. 로그를 읽는 속도보다 기록되는 속도가 빨랐습니다.",
morePending: "아직 더 많은 줄을 읽고 있습니다. 다음 새로 고침에 표시됩니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 923985c06d9..2ca775e5a50 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -718,6 +718,7 @@ export const ptBR = {
disabled: "O log em arquivo está desativado (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "Nenhum arquivo de log foi encontrado.",
unreadable: "Não foi possível ler o arquivo de log.",
+ viewLogs: "Ver registros",
timeout: "A solicitacao do registro expirou. O servidor pode estar inacessivel.",
droppedNotice: "Algumas linhas foram ignoradas: o log foi gravado mais rápido do que era possível ler.",
morePending: "Mais linhas ainda estao sendo lidas; elas chegam na proxima atualizacao.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index a1fdf7728c6..1116cedb955 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -718,6 +718,7 @@ export const ru = {
disabled: "Запись журнала в файл отключена (UNSLOTH_STUDIO_NO_FILE_LOG=1).",
missing: "Файл журнала не найден.",
unreadable: "Не удалось прочитать файл журнала.",
+ viewLogs: "Открыть журналы",
timeout: "Истекло время ожидания запроса журнала. Возможно, сервер недоступен.",
droppedNotice: "Часть строк пропущена: журнал записывался быстрее, чем его удавалось читать.",
morePending: "Ещё строки продолжают читаться; они появятся при следующем обновлении.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 9eff0fce65d..a37851b9c7b 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -714,6 +714,7 @@ export const zhCN = {
disabled: "文件日志已关闭 (UNSLOTH_STUDIO_NO_FILE_LOG=1)。",
missing: "未找到日志文件。",
unreadable: "无法读取日志文件。",
+ viewLogs: "查看日志",
timeout: "日志请求超时。服务器可能无法访问。",
droppedNotice: "已跳过部分行:日志的写入速度超过了读取速度。",
morePending: "仍在读取更多行,它们将在下次刷新时显示。",
diff --git a/studio/frontend/src/index.css b/studio/frontend/src/index.css
index 840423e7a2a..78f76a561b8 100644
--- a/studio/frontend/src/index.css
+++ b/studio/frontend/src/index.css
@@ -4511,6 +4511,14 @@ html[data-chat-font] .aui-root {
min-width: 0;
}
+/* A load failure carries a real diagnostic: a summary line, the runner's output, and the
+ path of the log it came from. Default `white-space: normal` collapsed every newline to
+ a space, so the structure the backend built was destroyed on the way to the reader. */
+[data-sonner-toast][data-styled='true'] [data-title],
+[data-sonner-toast][data-styled='true'] [data-description] {
+ white-space: pre-wrap;
+}
+
[data-sonner-toast][data-styled='true']:has([data-button]) {
display: grid !important;
grid-template-columns: minmax(0, 1fr);
diff --git a/studio/frontend/tests/debug-log-export.test.ts b/studio/frontend/tests/debug-log-export.test.ts
index 7ca2f0629fc..266a4a7ef9b 100644
--- a/studio/frontend/tests/debug-log-export.test.ts
+++ b/studio/frontend/tests/debug-log-export.test.ts
@@ -26,6 +26,18 @@ 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";
+type DialogState = {
+ logFamilyRequested: string | null;
+ logSourcePathRequested: string | null;
+ consumeLogFamilyRequest: () => void;
+};
+
+const IDLE_DIALOG_STATE: DialogState = {
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
+ consumeLogFamilyRequest: () => {},
+};
+
const API_URL = new URL(
"../src/features/settings/api/debug-logs.ts",
import.meta.url,
@@ -208,6 +220,15 @@ function makeWorld(options: {
},
"../lib/debug-log-buffer": debugLogBuffer,
"../lib/debug-log-error": debugLogError,
+ "../stores/settings-dialog-store": {
+ useSettingsDialogStore: Object.assign(
+ (selector?: (state: DialogState) => unknown) =>
+ selector ? selector(IDLE_DIALOG_STATE) : IDLE_DIALOG_STATE,
+ { getState: () => IDLE_DIALOG_STATE },
+ ),
+ pendingLogRequestKey: () => "|",
+ NO_PENDING_LOG_REQUEST: "|",
+ },
});
function render(): string {
@@ -366,7 +387,11 @@ test("a failure that is not a 401 never reaches for the refresh token", async ()
});
await assert.rejects(() => world.api.exportAllLogs());
- assert.equal(world.refreshes.length, 0, "a 500 is not an authentication problem");
+ assert.equal(
+ world.refreshes.length,
+ 0,
+ "a 500 is not an authentication problem",
+ );
assert.equal(world.invokes.length, 1);
});
diff --git a/studio/frontend/tests/video-generate-refusal-resync.test.ts b/studio/frontend/tests/video-generate-refusal-resync.test.ts
index 191e66e0a55..0789d8f3568 100644
--- a/studio/frontend/tests/video-generate-refusal-resync.test.ts
+++ b/studio/frontend/tests/video-generate-refusal-resync.test.ts
@@ -23,8 +23,10 @@ const RESYNC = VIDEO.slice(
test("a refused generation re-reads the model status", () => {
const generateCatch = VIDEO.slice(
- VIDEO.indexOf('toast.error(err instanceof Error ? err.message : "Video generation failed")'),
- ).slice(0, 400);
+ VIDEO.indexOf(
+ 'const refusal = err instanceof Error ? err.message : "Video generation failed";',
+ ),
+ ).slice(0, 600);
assert.match(generateCatch, /void resyncAfterGenerateRefusal\(\);/);
});
diff --git a/studio/frontend/tests/view-logs-action.test.ts b/studio/frontend/tests/view-logs-action.test.ts
new file mode 100644
index 00000000000..3356140341c
--- /dev/null
+++ b/studio/frontend/tests/view-logs-action.test.ts
@@ -0,0 +1,333 @@
+// 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 "View logs" route a failure offers, and the request that carries it. */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+import {
+ pendingLogRequestKey,
+ useSettingsDialogStore,
+} from "../src/features/settings/stores/settings-dialog-store.ts";
+import { en } from "../src/i18n/locales/en.ts";
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+const RUNNER_LOG =
+ "/home/u/.unsloth/studio/logs/llama-server-20260921-141500.log";
+const ACTION_URL = new URL(
+ "../src/features/settings/lib/view-logs-action.ts",
+ import.meta.url,
+);
+
+const store = useSettingsDialogStore;
+
+function pendingLogRequestKeyOf(): string {
+ return pendingLogRequestKey(store.getState());
+}
+
+function reset() {
+ store.setState({
+ open: false,
+ activeTab: "general",
+ scrollTarget: null,
+ archivedRequested: null,
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
+ connectionRequested: null,
+ });
+}
+
+test("the action opens Logs on the family that failed", () => {
+ reset();
+ const translated: string[] = [];
+ const { viewLogsAction } = loadWithStubs<
+ typeof import("../src/features/settings/lib/view-logs-action.ts")
+ >(ACTION_URL, {
+ "@/i18n": {
+ translate: (key: string) => {
+ translated.push(key);
+ return `t(${key})`;
+ },
+ },
+ "../stores/settings-dialog-store": { useSettingsDialogStore: store },
+ "@/features/auth/account-session": { isAccountOwner: () => true },
+ });
+
+ const action = viewLogsAction("llama-server");
+ // The owner gets one; the non-owner case has its own test below.
+ assert.ok(action, "an owner must be offered the action");
+ assert.equal(action.label, "t(settings.debugging.viewLogs)");
+ assert.deepEqual(translated, ["settings.debugging.viewLogs"]);
+ // The key has to exist in the shipped catalogue, or the label renders as the raw key.
+ const shipped = "settings.debugging.viewLogs"
+ .split(".")
+ .reduce<unknown>(
+ (node, part) => (node as Record<string, unknown> | undefined)?.[part],
+ en as unknown,
+ );
+ assert.equal(
+ typeof shipped,
+ "string",
+ "no English message for the View logs label",
+ );
+
+ assert.equal(store.getState().logFamilyRequested, null);
+ action.onClick();
+ const after = store.getState();
+ assert.equal(after.open, true);
+ assert.equal(after.activeTab, "debugging");
+ assert.equal(after.logFamilyRequested, "llama-server");
+});
+
+test("only a GGUF load is explained by a runner log; everything else is in the server log", () => {
+ const { loadFailureLogFamily } = loadWithStubs<
+ typeof import("../src/features/settings/lib/view-logs-action.ts")
+ >(ACTION_URL, {
+ "@/i18n": { translate: (k: string) => k },
+ "../stores/settings-dialog-store": { useSettingsDialogStore: store },
+ "@/features/auth/account-session": { isAccountOwner: () => true },
+ });
+
+ assert.equal(loadFailureLogFamily(true, false, RUNNER_LOG), "llama-server");
+ assert.equal(
+ loadFailureLogFamily(true, true, RUNNER_LOG),
+ "diffusion-server",
+ );
+ // A Transformers or MLX load has no runner at all.
+ for (const notGguf of [false, undefined] as const) {
+ for (const diffusion of [true, false, undefined] as const) {
+ assert.equal(
+ loadFailureLogFamily(notGguf, diffusion, RUNNER_LOG),
+ "server",
+ `isGguf=${notGguf} isDiffusion=${diffusion}`,
+ );
+ }
+ }
+});
+
+test("a load whose diagnostic names no runner log has none to open", () => {
+ const { loadFailureLogFamily } = loadWithStubs<
+ typeof import("../src/features/settings/lib/view-logs-action.ts")
+ >(ACTION_URL, {
+ "@/i18n": { translate: (k: string) => k },
+ "../stores/settings-dialog-store": { useSettingsDialogStore: store },
+ "@/features/auth/account-session": { isAccountOwner: () => true },
+ });
+ for (const gguf of [true, false, undefined] as const) {
+ for (const diffusion of [true, false, undefined] as const) {
+ for (const noPath of [null, undefined, ""] as const) {
+ assert.equal(
+ loadFailureLogFamily(gguf, diffusion, noPath),
+ "server",
+ `isGguf=${gguf} isDiffusion=${diffusion} path=${String(noPath)}`,
+ );
+ }
+ }
+ }
+ assert.equal(loadFailureLogFamily(true, false, RUNNER_LOG), "llama-server");
+ assert.equal(
+ loadFailureLogFamily(true, true, RUNNER_LOG),
+ "diffusion-server",
+ );
+});
+
+test("the family and the path are read from the same diagnostic", () => {
+ const src = readFileSync(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.ok(
+ src.includes("const runnerLogPath = failureLogPath(message);"),
+ "the hook no longer derives the runner log path from the diagnostic",
+ );
+ assert.ok(
+ src.includes("loadFailureLogFamily(isGguf, isDiffusion, runnerLogPath),"),
+ "the family no longer comes from the diagnostic's own path",
+ );
+ assert.match(
+ src,
+ /viewLogsAction\(\s*loadFailureLogFamily\(isGguf, isDiffusion, runnerLogPath\),\s*runnerLogPath,\s*\)/,
+ "the family and the path handed to the action are no longer the same value",
+ );
+ assert.match(
+ src,
+ /const logsAction = runnerLogPath\s*\?\s*viewLogsAction\(/,
+ "a load whose diagnostic names no log must not offer one",
+ );
+});
+
+test("the exact log the diagnostic named is carried, and wins over family recency", () => {
+ reset();
+ const { viewLogsAction, failureLogPath } = loadWithStubs<
+ typeof import("../src/features/settings/lib/view-logs-action.ts")
+ >(ACTION_URL, {
+ "@/i18n": { translate: (k: string) => k },
+ "../stores/settings-dialog-store": { useSettingsDialogStore: store },
+ "@/features/auth/account-session": { isAccountOwner: () => true },
+ });
+
+ // The wording llama_cpp.py appends, and treats as a diagnostics marker.
+ const diagnostic =
+ "llama-server failed to start\n\nllama-server output:\n ggml_abort\n\n" +
+ "Full log: /home/u/.unsloth/studio/logs/llama-server/llama-1765000000-port-8080.log";
+ const path = failureLogPath(diagnostic);
+ assert.equal(
+ path,
+ "/home/u/.unsloth/studio/logs/llama-server/llama-1765000000-port-8080.log",
+ );
+ assert.equal(failureLogPath("Failed to load model"), null);
+ assert.equal(failureLogPath("Full log: "), null);
+
+ const pathAction = viewLogsAction("llama-server", path);
+ assert.ok(pathAction);
+ pathAction.onClick();
+ assert.equal(store.getState().logSourcePathRequested, path);
+ // Cleared with the family, so a later visit cannot land on a stale file.
+ store.getState().consumeLogFamilyRequest();
+ assert.equal(store.getState().logSourcePathRequested, null);
+});
+
+test("the Logs panel clears the request once it has consumed it", () => {
+ reset();
+ store.getState().openLogs("server");
+ assert.equal(store.getState().logFamilyRequested, "server");
+ store.getState().consumeLogFamilyRequest();
+ assert.equal(store.getState().logFamilyRequested, null);
+ // Still on the tab: consuming the request must not close or navigate the dialog.
+ assert.equal(store.getState().activeTab, "debugging");
+ assert.equal(store.getState().open, true);
+});
+
+test("closing the dialog drops the request, like every other pending one", () => {
+ reset();
+ store.getState().openLogs("server");
+ store.getState().closeDialog();
+ const after = store.getState();
+ assert.equal(after.open, false);
+ assert.equal(after.logFamilyRequested, null);
+ assert.equal(after.archivedRequested, null);
+ assert.equal(after.connectionRequested, null);
+});
+
+test("an account that cannot open Logs is offered no action at all", () => {
+ reset();
+ const { viewLogsAction } = loadWithStubs<
+ typeof import("../src/features/settings/lib/view-logs-action.ts")
+ >(ACTION_URL, {
+ "@/i18n": { translate: (k: string) => k },
+ "../stores/settings-dialog-store": { useSettingsDialogStore: store },
+ "@/features/auth/account-session": { isAccountOwner: () => false },
+ });
+ for (const family of [
+ "llama-server",
+ "diffusion-server",
+ "server",
+ ] as const) {
+ assert.equal(viewLogsAction(family), undefined, family);
+ assert.equal(viewLogsAction(family, "/some/log.log"), undefined, family);
+ }
+ // And nothing was requested as a side effect of asking.
+ assert.equal(store.getState().logFamilyRequested, null);
+ assert.equal(store.getState().open, false);
+});
+
+test("an older in-flight refresh does not consume a newer request", async () => {
+ const { pendingLogRequestKey, NO_PENDING_LOG_REQUEST } = await import(
+ "../src/features/settings/stores/settings-dialog-store.ts"
+ );
+ reset();
+
+ // What the older fetch captured: nothing pending.
+ const capturedByOlderFetch = pendingLogRequestKey(store.getState());
+ assert.equal(capturedByOlderFetch, NO_PENDING_LOG_REQUEST);
+
+ // The click lands while that fetch is still out.
+ store.getState().openLogs("llama-server", "/logs/llama-failed.log");
+ const nowPending = pendingLogRequestKey(store.getState());
+ assert.notEqual(
+ nowPending,
+ capturedByOlderFetch,
+ "the older fetch would be unable to tell it was answering someone else's request",
+ );
+
+ const capturedByNewerFetch = pendingLogRequestKey(store.getState());
+ assert.equal(capturedByNewerFetch, nowPending);
+ store.getState().consumeLogFamilyRequest();
+ assert.equal(pendingLogRequestKey(store.getState()), NO_PENDING_LOG_REQUEST);
+
+ const tabSrc = await readFile(
+ new URL("../src/features/settings/tabs/debugging-tab.tsx", import.meta.url),
+ "utf8",
+ );
+ // A stale response must bail before touching ANY state, the source list included.
+ assert.match(
+ tabSrc,
+ /if \(seq < appliedSourceFetchRef\.current\) return;\s*setSources\(result\.sources\);/,
+ );
+
+ const tab = await readFile(
+ new URL("../src/features/settings/tabs/debugging-tab.tsx", import.meta.url),
+ "utf8",
+ );
+ for (const needle of [
+ "const requestedFor = pendingLogRequestKey(",
+ "pendingLogRequestKey(dialog) === requestedFor",
+ "if (fromFailure && stillTheSameRequest)",
+ "if (fromFailure && !stillTheSameRequest) return;",
+ // An older response (e.g. a 404 reselect) never overrides a newer selection.
+ "const seq = ++sourceFetchSeqRef.current;",
+ "appliedSourceFetchRef.current = seq;",
+ ]) {
+ assert.ok(
+ tab.includes(needle),
+ `the panel no longer guards consumption on the request it fetched for: ${needle}`,
+ );
+ }
+});
+
+test("only a generation failure the server logged offers its log", () => {
+ reset();
+ const { generationFailureLogsAction } = loadWithStubs<
+ typeof import("../src/features/settings/lib/view-logs-action.ts")
+ >(ACTION_URL, {
+ "@/i18n": { translate: (key: string) => key },
+ "../stores/settings-dialog-store": { useSettingsDialogStore: store },
+ "@/features/auth/account-session": { isAccountOwner: () => true },
+ });
+ for (const logged of [
+ "Image generation failed. The device ran out of memory.",
+ "Video generation failed. The renderer stopped unexpectedly.",
+ "Failed to save the generated image.",
+ "Failed to save the generated video.",
+ ]) {
+ const action = generationFailureLogsAction(logged);
+ assert.ok(action, logged);
+ action.onClick();
+ assert.equal(store.getState().logFamilyRequested, "server");
+ reset();
+ }
+ // Client-input refusals are answered with their own text and never logged.
+ assert.equal(
+ generationFailureLogsAction("negative_prompt is not supported by this family."),
+ undefined,
+ );
+ assert.equal(generationFailureLogsAction("Video generation could not start."), undefined);
+});
+
+test("a repeated identical View logs click is still a new request", () => {
+ reset();
+ store.setState({ logRequestSeq: 0 });
+ store.getState().openLogs("llama-server", "/logs/llama-failed.log");
+ const first = pendingLogRequestKeyOf();
+ store.getState().openLogs("llama-server", "/logs/llama-failed.log");
+ const second = pendingLogRequestKeyOf();
+ assert.notEqual(first, second, "the mounted tab would not refetch for the second click");
+ store.getState().consumeLogFamilyRequest();
+ assert.equal(pendingLogRequestKeyOf(), "|");
+});