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.

feat: allow disabling Studio API monitor logs (#7175)

Aditya Ingale61eeb9253d9c
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.py
index b637ba56d1a..641f3f626cf 100644
--- a/studio/backend/core/inference/api_monitor.py
+++ b/studio/backend/core/inference/api_monitor.py
@@ -124,6 +124,12 @@ class ApiMonitor:
self._lock = threading.Lock()
self._enabled = enabled
+ @property
+ def enabled(self) -> bool:
+ """Whether rows are being recorded. Read-only: the kill switch is a
+ startup env var, so nothing may flip it on a live monitor."""
+ return self._enabled
+
def start(
self,
*,
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 6dbc63d09d2..e927bc9dc3a 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2906,6 +2906,18 @@ def _monitor_openai_error_message(data: dict) -> Optional[str]:
return None
+def _is_openai_sse_done(raw_line: str) -> bool:
+ """Whether the line is the terminal `data: [DONE]` frame.
+
+ Deliberately independent of the monitor: framing the client sees must not
+ change just because recording is off.
+ """
+ # SSE spec allows `data:value` and `data: value`; accept both.
+ if not raw_line.startswith("data:"):
+ return False
+ return raw_line[5:].lstrip() == "[DONE]"
+
+
def _monitor_openai_sse_line(
monitor_id: Optional[str],
raw_line: str,
@@ -2913,7 +2925,6 @@ def _monitor_openai_sse_line(
) -> Optional[str]:
if not monitor_id:
return None
- # SSE spec allows `data:value` and `data: value`; accept both.
if not raw_line.startswith("data:"):
return None
data_str = raw_line[5:].lstrip()
@@ -6920,11 +6931,15 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):
operating_status = "ready"
else:
operating_status = "idle"
+ # With request logging off, ``snapshot()`` returns an empty list -- the same shape
+ # as a Studio that simply hasn't served a request yet. Signal the disabled state so
+ # the UI can explain the empty list instead of claiming there was no API traffic.
return {
"status": operating_status,
"active_model": active_model,
"context_length": _monitor_context_length(),
"active_requests": active_requests,
+ "logging_enabled": api_monitor.enabled,
"entries": api_monitor.snapshot(include_details = False, subject = current_subject),
}
@@ -8475,7 +8490,10 @@ async def _proxy_to_external_provider(
if monitor_event == "error":
stream_failed = True
yield f"{line}\n\n"
- if monitor_event == "done":
+ # Parsed from the line itself, not from monitor_event: with the
+ # monitor disabled the helper returns None for every line, and
+ # trusting it would append a second [DONE] after the provider's.
+ if _is_openai_sse_done(line):
sent_done = True
if not sent_done:
if not stream_failed:
diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.py
index 4602b5cf622..dd4ffbd7946 100644
--- a/studio/backend/tests/test_api_monitor.py
+++ b/studio/backend/tests/test_api_monitor.py
@@ -1,7 +1,28 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth.authentication import get_current_subject
from core.inference.api_monitor import ApiMonitor, _trim
+import routes.inference as inference_route
+
+
+def _get_monitor(monkeypatch, *, enabled: bool):
+ """Call GET /monitor against a monitor in a known state.
+
+ Swaps the whole singleton rather than poking ``_enabled`` on it: the route
+ reads ``snapshot()``, which does not consult the flag, so a shared monitor
+ carrying rows from an earlier test would leak into the assertions.
+ """
+ monkeypatch.setattr(inference_route, "api_monitor", ApiMonitor(enabled = enabled))
+ app = FastAPI()
+ app.include_router(inference_route.studio_router)
+ # Dict literal, not `overrides[key] = ...`: verify_import_hoist.py does not
+ # see Load names inside an assignment target and reports the import unused.
+ app.dependency_overrides = {get_current_subject: lambda: "test-user"}
+ return TestClient(app).get("/monitor")
def test_api_monitor_tracks_reply_usage_and_context():
@@ -412,3 +433,68 @@ def test_request_rows_report_kind_request():
monitor = ApiMonitor(max_entries = 2)
monitor.start(endpoint = "/v1/chat/completions", method = "POST", model = "m", prompt = "hi")
assert monitor.snapshot()[0]["kind"] == "request"
+
+
+# ── stream framing must not depend on the monitor ───────────────────
+
+
+def test_sse_done_detection_accepts_both_spacings():
+ done = inference_route._is_openai_sse_done
+ assert done("data: [DONE]") is True
+ assert done("data:[DONE]") is True
+ assert done('data: {"choices": []}') is False
+ assert done("event: ping") is False
+ assert done("") is False
+
+
+def test_sse_done_detection_is_independent_of_the_monitor():
+ """The external-provider proxy sets ``sent_done`` from the line itself.
+
+ It used to read the monitor helper's return, which is None for every line
+ once recording is off -- so the proxy appended a second [DONE] after the
+ provider's own, changing client-visible framing based on a logging flag.
+ """
+ line = "data: [DONE]"
+ assert inference_route._monitor_openai_sse_line(None, line) is None
+ assert inference_route._is_openai_sse_done(line) is True
+
+
+# ── /monitor route: the disabled state has to reach the UI ──────────
+
+
+def test_monitor_route_reports_enabled(monkeypatch):
+ response = _get_monitor(monkeypatch, enabled = True)
+
+ assert response.status_code == 200
+ assert response.json()["logging_enabled"] is True
+
+
+def test_monitor_route_reports_disabled(monkeypatch):
+ response = _get_monitor(monkeypatch, enabled = False)
+
+ # An empty list on its own is indistinguishable from "no traffic yet", so the
+ # console needs the flag to explain itself instead of claiming idleness.
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["logging_enabled"] is False
+ assert payload["entries"] == []
+
+
+def test_monitor_route_disabled_still_hides_recorded_rows(monkeypatch):
+ """A disabled monitor records nothing, so the route reports an empty list
+ even after traffic that would otherwise have shown up."""
+ monkeypatch.setattr(inference_route, "api_monitor", ApiMonitor(enabled = False))
+ inference_route.api_monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ subject = "test-user",
+ )
+ app = FastAPI()
+ app.include_router(inference_route.studio_router)
+ app.dependency_overrides = {get_current_subject: lambda: "test-user"}
+ payload = TestClient(app).get("/monitor").json()
+
+ assert payload["logging_enabled"] is False
+ assert payload["entries"] == []
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index d973aa9f2ab..967d0c9325e 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -330,6 +330,8 @@ export interface ApiMonitorResponse {
active_model?: string | null;
context_length?: number | null;
active_requests: number;
+ /** Absent on older backends -- treat only an explicit `false` as disabled. */
+ logging_enabled?: boolean;
entries: ApiMonitorEntry[];
}
diff --git a/studio/frontend/src/features/settings/components/api-monitor-console.tsx b/studio/frontend/src/features/settings/components/api-monitor-console.tsx
index 332cd4f2f9d..a9c89dbeffe 100644
--- a/studio/frontend/src/features/settings/components/api-monitor-console.tsx
+++ b/studio/frontend/src/features/settings/components/api-monitor-console.tsx
@@ -344,6 +344,8 @@ export function ApiMonitorConsole(): ReactElement {
const statusLabel = data?.status ?? "idle";
const hasActive = (data?.active_requests ?? 0) > 0;
const entries = useMemo(() => data?.entries ?? [], [data]);
+ // Older backends omit the field; only an explicit `false` means logging is off.
+ const loggingDisabled = data?.logging_enabled === false;
// Page 1 tracks the live list; paging back freezes the id order so history holds still.
const [page, setPage] = useState(0);
@@ -506,8 +508,10 @@ export function ApiMonitorConsole(): ReactElement {
<div className="flex items-center justify-between border-b border-border/60 px-4 py-2 text-xs text-muted-foreground">
<span>
- {(data?.active_requests ?? 0).toLocaleString()} active /{" "}
- {entries.length.toLocaleString()} recent
+ {(data?.active_requests ?? 0).toLocaleString()} active
+ {loggingDisabled ? null : (
+ <> / {entries.length.toLocaleString()} recent</>
+ )}
</span>
{data?.context_length ? (
<span>{data.context_length.toLocaleString()} context</span>
@@ -519,6 +523,15 @@ export function ApiMonitorConsole(): ReactElement {
<div className="rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
+ ) : loggingDisabled ? (
+ <div className="rounded-lg border border-border/70 p-4 text-sm text-muted-foreground">
+ The API monitor is disabled by{" "}
+ <code className="rounded bg-muted/60 px-1 py-0.5 text-xs">
+ UNSLOTH_STUDIO_DISABLE_API_MONITOR
+ </code>
+ . Requests and model loads still run normally, they are just not recorded
+ here. Unset the variable and restart Studio to re-enable.
+ </div>
) : entries.length === 0 ? (
<div className="rounded-lg border border-border/70 p-4 text-sm text-muted-foreground">
No API traffic yet