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: keep a text selection in Settings › Logs across polls so part of the log can be copied (#16099)

Leo Borcherding35385edbb652
diff --git a/studio/frontend/src/features/settings/lib/debug-log-buffer.ts b/studio/frontend/src/features/settings/lib/debug-log-buffer.ts
index 79b61469b23..1fdc487a20d 100644
--- a/studio/frontend/src/features/settings/lib/debug-log-buffer.ts
+++ b/studio/frontend/src/features/settings/lib/debug-log-buffer.ts
@@ -1,15 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-/** Kept free of React so node:test can import it. */
-
export type RefreshMode = "live" | "3s" | "manual";
export const DEFAULT_REFRESH_MODE: RefreshMode = "3s";
export const REFRESH_MODE_STORAGE_KEY = "unsloth_debug_log_refresh_mode";
-/** Distinct from AbortError, which unmounts and source switches use silently, so a hung request
- * is reported. Lives here because node:test resolves no extensionless src import. */
export class DebugLogTimeoutError extends Error {
constructor(timeoutMs: number) {
super(`Request timed out after ${Math.round(timeoutMs / 1000)}s.`);
@@ -21,17 +17,14 @@ export function isRequestTimeout(error: unknown): boolean {
return error instanceof DebugLogTimeoutError;
}
-/** Built by hand for the tie where the deadline won but the caller had already aborted. */
function abortError(): Error {
const error = new Error("Aborted.");
error.name = "AbortError";
return error;
}
-/** A never-answers backstop, not a latency budget; tunnels can be slow. */
export const REQUEST_TIMEOUT_MS = 20_000;
-/** The server caps a response; this caps accumulation over a long session. */
export const MAX_CLIENT_LINES = 2000;
export const MAX_CLIENT_CHARS = 400_000;
@@ -48,7 +41,6 @@ export interface LogBufferState {
export const EMPTY_BUFFER: LogBufferState = { lines: [], cursor: null };
-/** null for manual. "live" polls short requests rather than streaming, so it survives proxies. */
export function pollDelayMs(mode: RefreshMode): number | null {
switch (mode) {
case "live":
@@ -66,11 +58,7 @@ export function parseRefreshMode(value: unknown): RefreshMode {
: DEFAULT_REFRESH_MODE;
}
-/**
- * Every awaited request needs this: authFetch adds no timeout and awaits refreshSession() on a 401
- * without a signal, so the deadline is raced, not awaited. Signals are linked by hand because
- * `AbortSignal.any` needs Safari 17.4 and the floor is 16.4.
- */
+/** Race refreshSession (no abort signal); link signals for Safari 16.4 without AbortSignal.any. */
export async function withRequestTimeout<T>(
task: (signal: AbortSignal) => Promise<T>,
timeoutMs: number,
@@ -82,7 +70,7 @@ export async function withRequestTimeout<T>(
signal?.addEventListener("abort", relay);
let timer: ReturnType<typeof setTimeout> | undefined;
const running = task(local.signal);
- // An unobserved rejection is a process-level crash under node:test.
+ // Observe late rejections after the timeout wins.
running.catch(() => {});
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
@@ -103,8 +91,7 @@ export async function withRequestTimeout<T>(
}
}
-/** `selection` counts source changes: a manual refresh has no abort signal, and A -> B -> A
- * would match ids while A's old cursor rewinds the reset buffer. */
+/** The source-change counter rejects old A responses after A -> B -> A, including manual polls. */
export function isPageStale(page: {
requestSelection: number;
currentSelection: number;
@@ -112,7 +99,6 @@ export function isPageStale(page: {
pageSourceId: string | null;
}): boolean {
if (page.requestSelection !== page.currentSelection) return true;
- // The server answers an unset source with its default, so only compare when both name one.
return Boolean(
page.requestSourceId &&
page.pageSourceId &&
@@ -120,7 +106,6 @@ export function isPageStale(page: {
);
}
-/** Sticky until a reset: the skipped lines stay missing from the buffer. */
export function nextDroppedState(
previous: boolean,
page: { droppedBytes: number; reset: boolean },
@@ -144,7 +129,6 @@ export function trimBuffer(lines: string[]): string[] {
return trimmed;
}
-/** Returns the SAME object when nothing is new so the caller can skip a re-render. */
export function applyLogChunk(
previous: LogBufferState,
chunk: DebugLogChunk,
@@ -161,3 +145,27 @@ export function applyLogChunk(
cursor: chunk.cursor,
};
}
+
+export function selectionInside<N>(
+ selection: {
+ isCollapsed: boolean;
+ anchorNode: N | null;
+ focusNode: N | null;
+ } | null,
+ pane: { contains(node: N | null): boolean } | null,
+): boolean {
+ if (!selection || !pane || selection.isCollapsed) return false;
+ return pane.contains(selection.anchorNode) || pane.contains(selection.focusNode);
+}
+
+export function clearSelectionInside<N>(
+ selection: {
+ isCollapsed: boolean;
+ anchorNode: N | null;
+ focusNode: N | null;
+ removeAllRanges(): void;
+ } | null,
+ pane: { contains(node: N | null): boolean } | null,
+): void {
+ if (selectionInside(selection, pane)) selection?.removeAllRanges();
+}
diff --git a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
index ef9f9347247..5aac4981446 100644
--- a/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/debugging-tab.tsx
@@ -71,11 +71,13 @@ import {
REQUEST_TIMEOUT_MS,
type RefreshMode,
applyLogChunk,
+ clearSelectionInside,
isPageStale,
nextDroppedState,
parseRefreshMode,
isRequestTimeout,
pollDelayMs,
+ selectionInside,
withRequestTimeout,
} from "../lib/debug-log-buffer";
import { isAbort, isLogSourceGone } from "../lib/debug-log-error";
@@ -88,7 +90,6 @@ import { Tick02Icon } from "@/lib/tick-icon";
const MODES: RefreshMode[] = ["live", "3s", "manual"];
-// Slower than the poll: a directory walk rather than a tail read.
const SOURCE_RESCAN_MS = 10_000;
const FOLLOW_THRESHOLD_PX = 40;
@@ -180,22 +181,16 @@ export function DebuggingTab() {
const [logRoot, setLogRoot] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [dropped, setDropped] = useState(false);
- // In manual mode the continuation poll never comes unless the user asks.
const [morePending, setMorePending] = useState(false);
- // File logging is off but an old log is on disk; say so, or it looks live.
const [staleSession, setStaleSession] = useState(false);
- // Per-button state so the slow export does not lock out "Show in folder".
const [exporting, setExporting] = useState(false);
const [revealing, setRevealing] = useState(false);
const [filter, setFilter] = useState("");
const [wrap, setWrap] = useState(true);
- // Mirrors pinnedRef for the jump button; the ref stays the source of truth so scrolling
- // does not re-render the pane.
const [following, setFollowing] = useState(true);
const { copied, copy } = useCopyFeedback();
const { copied: pathCopied, copy: copyPath } = useCopyFeedback();
- // A ref too, so the poll loop does not restart per line.
const cursorRef = useRef<string | null>(null);
const selectionRef = useRef(0);
// The selection in flight, not a flag, so a slow read of the old source cannot swallow the new poll.
@@ -212,11 +207,9 @@ export function DebuggingTab() {
try {
window.localStorage.setItem(REFRESH_MODE_STORAGE_KEY, mode);
} catch {
- // A blocked localStorage must not stop the viewer working.
}
}, [mode]);
- // A response older than the last selecting one never overrides it.
const sourceFetchSeqRef = useRef(0);
const appliedSourceFetchRef = useRef(0);
@@ -224,7 +217,6 @@ export function DebuggingTab() {
async (options: { signal?: AbortSignal; reselect?: boolean } = {}) => {
const seq = ++sourceFetchSeqRef.current;
try {
- // Bounded: the poll loop and its recovery both await /sources.
const requestedFor = pendingLogRequestKey(
useSettingsDialogStore.getState(),
);
@@ -264,7 +256,6 @@ export function DebuggingTab() {
: (current ?? result.defaultSourceId),
);
} catch {
- // The log read reports the real reason; this just leaves the picker empty.
}
},
[],
@@ -288,13 +279,11 @@ export function DebuggingTab() {
async (error: unknown, signal?: AbortSignal) => {
if (isAbort(error)) return;
if (isRequestTimeout(error)) {
- // The backstop duration is internal; show the consequence.
setNotice(t("settings.debugging.timeout"));
return;
}
if (isLogSourceGone(error)) {
- // 404 means the id is no longer enumerated; reset so the loop does not poll a dead id.
- // Reselecting the default terminates, since "nothing at all" is a 200.
+ // Default reselection terminates: an empty source list returns 200, not another 404.
cursorRef.current = null;
await refreshSources({ signal, reselect: true });
return;
@@ -304,7 +293,6 @@ export function DebuggingTab() {
[refreshSources, t],
);
- // The llama runner writes a new file per load attempt, so the mount-time list goes stale.
const rescanSourcesIfStale = useCallback(
async (signal?: AbortSignal) => {
if (Date.now() - lastSourceScanRef.current < SOURCE_RESCAN_MS) return;
@@ -319,7 +307,6 @@ export function DebuggingTab() {
const selection = selectionRef.current;
if (inFlightRef.current === selection) return;
inFlightRef.current = selection;
- // Without the timeout a hung request pins inFlightRef and the pane freezes silently.
try {
const page = await withRequestTimeout(
(requestSignal) =>
@@ -331,7 +318,6 @@ export function DebuggingTab() {
REQUEST_TIMEOUT_MS,
signal,
);
- // A manual refresh has no abort signal and could land the old file's lines under the new pick.
if (
isPageStale({
requestSelection: selection,
@@ -369,11 +355,11 @@ export function DebuggingTab() {
);
useEffect(() => {
+ clearSelectionInside(document.getSelection(), paneRef.current);
selectionRef.current += 1;
cursorRef.current = null;
setBuffer(EMPTY_BUFFER);
setRealpath(null);
- // Every notice describes the file being left, so reset all of them; manual mode never retries.
setDropped(false);
setMorePending(false);
setStaleSession(false);
@@ -385,7 +371,6 @@ export function DebuggingTab() {
let timer: number | undefined;
let stopped = false;
- // Self-scheduling so a slow link builds no backlog.
const tick = async () => {
if (stopped) return;
if (
@@ -422,19 +407,65 @@ export function DebuggingTab() {
const text = useMemo(() => visibleLines.join("\n"), [visibleLines]);
+ // Keep presses in a ref: rendering before the drag's first selection collapses it in Chromium.
+ const [holding, setHolding] = useState(false);
+ const pointerDownRef = useRef(false);
+ const textRef = useRef(text);
+ textRef.current = text;
+ const [shownText, setShownText] = useState(text);
+ if (!holding && !pointerDownRef.current && shownText !== text)
+ setShownText(text);
+
+ useEffect(() => {
+ const inside = () =>
+ selectionInside(document.getSelection(), paneRef.current);
+ const update = () => {
+ const held = inside();
+ if (pointerDownRef.current && !held) return;
+ setHolding(held);
+ };
+ const release = () => {
+ if (!pointerDownRef.current) return;
+ pointerDownRef.current = false;
+ const held = inside();
+ setHolding(held);
+ if (!held) setShownText(textRef.current);
+ };
+ const onPointerMove = (event: PointerEvent) => {
+ if (event.buttons === 0) release();
+ };
+ document.addEventListener("selectionchange", update);
+ window.addEventListener("pointermove", onPointerMove);
+ window.addEventListener("pointerup", release);
+ window.addEventListener("pointercancel", release);
+ // A native context menu or text drag can swallow the pointerup.
+ window.addEventListener("contextmenu", release);
+ window.addEventListener("dragend", release);
+ window.addEventListener("drop", release);
+ return () => {
+ document.removeEventListener("selectionchange", update);
+ window.removeEventListener("pointermove", onPointerMove);
+ window.removeEventListener("pointerup", release);
+ window.removeEventListener("pointercancel", release);
+ window.removeEventListener("contextmenu", release);
+ window.removeEventListener("dragend", release);
+ window.removeEventListener("drop", release);
+ };
+ }, []);
+
const scrollToBottom = useCallback(() => {
const pane = paneRef.current;
if (!pane) return;
+ clearSelectionInside(document.getSelection(), pane);
pane.scrollTop = pane.scrollHeight;
pinnedRef.current = true;
setFollowing(true);
}, []);
- // wrap and a resize change the scroll height without changing the text, so they re-pin too
useEffect(() => {
const pane = paneRef.current;
if (pane && pinnedRef.current) pane.scrollTop = pane.scrollHeight;
- }, [text, wrap, paneHeight]);
+ }, [shownText, wrap, paneHeight]);
const resizePane = useCallback((next: number | null) => {
const height =
@@ -451,7 +482,6 @@ export function DebuggingTab() {
window.localStorage.setItem(PANE_HEIGHT_STORAGE_KEY, String(height));
}
} catch {
- // storage unavailable: the height still applies this visit
}
}, []);
@@ -530,14 +560,12 @@ export function DebuggingTab() {
setExporting(true);
try {
const savedPath = await exportAllLogs();
- // Only desktop returns a path; a browser's download location is unknown.
if (savedPath) {
toast.success(
t("settings.debugging.downloadedTo", { path: savedPath }),
{
action: {
label: t("settings.debugging.showInFolder"),
- // The archive's folder, not the logs' folder.
onClick: () => {
void revealSavedArchive(savedPath).catch((error: unknown) => {
toast.error(t("settings.debugging.openLogsFolderFailed"), {
@@ -675,6 +703,7 @@ export function DebuggingTab() {
variant="outline"
disabled={mode !== "manual"}
onClick={() => {
+ clearSelectionInside(document.getSelection(), paneRef.current);
void refreshSources();
void poll();
}}
@@ -729,7 +758,7 @@ export function DebuggingTab() {
"inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-xs font-medium",
staleSession
? "bg-amber-500/10 text-amber-600 dark:text-amber-400"
- : mode === "manual"
+ : mode === "manual" || holding
? "bg-muted text-muted-foreground"
: "bg-primary/10 text-primary",
)}
@@ -739,12 +768,13 @@ export function DebuggingTab() {
"size-1.5 rounded-full bg-current",
!staleSession &&
mode !== "manual" &&
+ !holding &&
"motion-safe:animate-pulse",
)}
/>
{staleSession
? t("settings.debugging.statusStale")
- : mode === "manual"
+ : mode === "manual" || holding
? t("settings.debugging.statusPaused")
: t("settings.debugging.statusLive")}
</span>
@@ -778,7 +808,6 @@ export function DebuggingTab() {
) : null}
<div className="relative">
- {/* Border on the frame, scrolling inside it: keeps the scrollbar off the rounded corners. */}
<div
ref={frameRef}
style={paneHeight === null ? undefined : { height: paneHeight }}
@@ -787,19 +816,21 @@ export function DebuggingTab() {
paneHeight === null && "h-[min(26rem,45vh)]",
)}
>
- {/* One text surface, not an element per line: this repaints on every
- poll and 1000 nodes per tick is what makes a log pane feel broken. */}
+ {/* Keep one text node; per-line nodes make frequent polls expensive. */}
<pre
ref={paneRef}
onScroll={onScroll}
+ onPointerDown={() => {
+ pointerDownRef.current = true;
+ }}
data-testid="debug-log-pane"
className={cn(
"h-full w-full overflow-auto [overflow-anchor:none] scroll-rounded rounded-md py-2 pr-11 pl-2.5 font-mono text-ui-11 leading-[1.55] text-foreground/90",
wrap ? "whitespace-pre-wrap break-words" : "whitespace-pre",
- !text && "text-muted-foreground",
+ !shownText && "text-muted-foreground",
)}
>
- {text ||
+ {shownText ||
(trimmedFilter && buffer.lines.length > 0
? t("settings.debugging.noMatches")
: t("settings.debugging.empty"))}
@@ -824,7 +855,7 @@ export function DebuggingTab() {
</TooltipTrigger>
<TooltipContent>{t("settings.debugging.wrapLines")}</TooltipContent>
</Tooltip>
- {!following && text ? (
+ {!following && shownText ? (
<Button
size="xs"
variant="dark"
@@ -888,8 +919,8 @@ export function DebuggingTab() {
<Button
size="sm"
variant="ghost"
- onClick={() => copy(text)}
- disabled={!text}
+ onClick={() => copy(shownText)}
+ disabled={!shownText}
>
<HugeiconsIcon
strokeWidth={1.75}
diff --git a/studio/frontend/tests/debug-log-buffer.test.ts b/studio/frontend/tests/debug-log-buffer.test.ts
index 541b0628b03..04fdfa9b9f6 100644
--- a/studio/frontend/tests/debug-log-buffer.test.ts
+++ b/studio/frontend/tests/debug-log-buffer.test.ts
@@ -9,10 +9,12 @@ import {
EMPTY_BUFFER,
MAX_CLIENT_LINES,
applyLogChunk,
+ clearSelectionInside,
isPageStale,
nextDroppedState,
parseRefreshMode,
pollDelayMs,
+ selectionInside,
trimBuffer,
isRequestTimeout,
withRequestTimeout,
@@ -115,7 +117,6 @@ test("appending past the cap still keeps the tail", () => {
assert.ok(!state.lines.includes("first"));
});
-// authFetch adds no timeout, so every awaited request needs the backstop.
function neverAnswers(signal: AbortSignal): Promise<never> {
return new Promise((_resolve, reject) => {
const fail = () => {
@@ -164,7 +165,6 @@ test("the source rescan cannot freeze the poll loop behind it", async () => {
try {
await withRequestTimeout(neverAnswers, 20);
} catch {
- // What refreshSources does: a failed list just leaves the picker be.
}
};
const poll = async () => {
@@ -275,7 +275,6 @@ test("the skipped-lines warning outlives the poll that raised it", () => {
});
test("the deadline fires even when the work ignores the abort", async () => {
- // authFetch awaits refreshSession() without a signal, so only racing the deadline unblocks it.
const deaf = () => new Promise<never>(() => {});
const started = Date.now();
await assert.rejects(
@@ -294,3 +293,45 @@ test("a caller abort still reads as one when the work ignores it too", async ()
(error: Error) => isAbort(error) && !isRequestTimeout(error),
);
});
+
+test("a selection holds the pane only when it is non-empty and touches the pane", () => {
+ const inside = { name: "pane text" };
+ const outside = { name: "sidebar" };
+ const pane = { contains: (node: unknown) => node === inside };
+ const select = (anchorNode: unknown, focusNode: unknown, isCollapsed = false) => ({
+ isCollapsed,
+ anchorNode,
+ focusNode,
+ });
+
+ assert.equal(selectionInside(select(inside, inside), pane), true);
+ assert.equal(selectionInside(select(outside, inside), pane), true);
+ assert.equal(selectionInside(select(inside, outside), pane), true);
+ assert.equal(selectionInside(select(inside, inside, true), pane), false);
+ assert.equal(selectionInside(select(outside, outside), pane), false);
+ assert.equal(selectionInside(null, pane), false);
+ assert.equal(selectionInside(select(inside, inside), null), false);
+});
+
+test("only a selection in the pane is cleared", () => {
+ const pane = { contains: (node: unknown) => node === "pane" };
+ const clearedFor = (anchorNode: string, focusNode: string) => {
+ let cleared = false;
+ clearSelectionInside(
+ {
+ isCollapsed: false,
+ anchorNode,
+ focusNode,
+ removeAllRanges: () => {
+ cleared = true;
+ },
+ },
+ pane,
+ );
+ return cleared;
+ };
+
+ assert.equal(clearedFor("pane", "pane"), true);
+ assert.equal(clearedFor("sidebar", "pane"), true);
+ assert.equal(clearedFor("sidebar", "sidebar"), false);
+});
diff --git a/studio/frontend/tests/debug-log-pane-layout.test.ts b/studio/frontend/tests/debug-log-pane-layout.test.ts
index 69c430be20a..7e784a29232 100644
--- a/studio/frontend/tests/debug-log-pane-layout.test.ts
+++ b/studio/frontend/tests/debug-log-pane-layout.test.ts
@@ -45,8 +45,29 @@ test("the pane resizes by drag and keyboard and remembers its height", () => {
"onKeyDown={onResizeKey}",
"onDoubleClick={() => resizePane(null)}",
'const PANE_HEIGHT_STORAGE_KEY = "unsloth_debug_log_pane_height";',
- "}, [text, wrap, paneHeight]);",
+ "}, [shownText, wrap, paneHeight]);",
]) {
assert.ok(tab.includes(needle), needle);
}
});
+
+test("the pane repaints from the held text, so a poll cannot drop a selection", () => {
+ assert.match(tab, /if \(!holding && !pointerDownRef\.current && shownText !== text\)\s*setShownText\(text\);/);
+ assert.match(pane, /\{shownText \|\|/);
+ assert.doesNotMatch(pane, /\{text \|\|/);
+ assert.match(tab, /document\.addEventListener\("selectionchange", update\)/);
+ assert.match(tab, /if \(pointerDownRef\.current && !held\) return;\s*setHolding\(held\);/);
+ assert.match(tab, /pointerDownRef\.current = false;\s*const held = inside\(\);\s*setHolding\(held\);/);
+ assert.doesNotMatch(pane, /onPointerDown=\{\(\) => \{[^}]*setHolding/);
+});
+
+test("asking for other log text ends the hold, and a context menu ends a press", () => {
+ assert.match(tab, /clearSelectionInside\(document\.getSelection\(\), paneRef\.current\);\s*selectionRef\.current \+= 1;/);
+ assert.match(tab, /clearSelectionInside\(document\.getSelection\(\), paneRef\.current\);\s*void refreshSources\(\);/);
+ assert.match(tab, /clearSelectionInside\(document\.getSelection\(\), pane\);\s*pane\.scrollTop = pane\.scrollHeight;/);
+ for (const type of ["contextmenu", "dragend", "drop"]) {
+ assert.ok(tab.includes(`window.addEventListener("${type}", release);`), type);
+ }
+ assert.match(tab, /if \(event\.buttons === 0\) release\(\);/);
+ assert.match(tab, /window\.addEventListener\("pointermove", onPointerMove\)/);
+});