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.

Unsloth Studio: make a newly created API key selectable when the clipboard is unavailable (#11489)

Leo Borcherdinga9f53480fb8c
diff --git a/studio/frontend/src/features/audio/audio-page.tsx b/studio/frontend/src/features/audio/audio-page.tsx
index 03965cb7b4a..603c8486055 100644
--- a/studio/frontend/src/features/audio/audio-page.tsx
+++ b/studio/frontend/src/features/audio/audio-page.tsx
@@ -101,6 +101,7 @@ import { useScrollFades } from "@/hooks/use-scroll-fades";
import { fetchSystemInfo } from "@/hooks/use-system";
import { isTauri } from "@/lib/api-base";
import { BlobUrlCache } from "@/lib/blob-url-cache";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { subscribeGalleryChanged } from "@/lib/gallery-flags";
import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";
import { toast } from "@/lib/toast";
@@ -2304,9 +2305,10 @@ export function AudioPage({
);
const handleCopyTranscript = useCallback(() => {
- void navigator.clipboard.writeText(transcript).then(
- () => toast.success("Transcript copied"),
- () => toast.error("Could not copy the transcript."),
+ void copyToClipboard(transcript).then((ok) =>
+ ok
+ ? toast.success("Transcript copied")
+ : toast.error("Could not copy the transcript."),
);
}, [transcript]);
@@ -2454,10 +2456,9 @@ export function AudioPage({
}, []);
const handleCopyPrompt = useCallback(async (text: string) => {
- try {
- await navigator.clipboard.writeText(text);
+ if (await copyToClipboard(text)) {
toast.success("Text copied");
- } catch {
+ } else {
toast.error("Could not copy the text.");
}
}, []);
diff --git a/studio/frontend/src/features/audio/transcript-gallery.tsx b/studio/frontend/src/features/audio/transcript-gallery.tsx
index 330db744942..ca3aa5bb3eb 100644
--- a/studio/frontend/src/features/audio/transcript-gallery.tsx
+++ b/studio/frontend/src/features/audio/transcript-gallery.tsx
@@ -25,6 +25,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { downloadTranscript } from "./transcript-download";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { archiveTranscript, deleteTranscript, listTranscripts } from "./api";
@@ -237,9 +238,10 @@ export function TranscriptGallery({
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
- void navigator.clipboard.writeText(record.text).then(
- () => toast.success("Transcript copied"),
- () => toast.error("Could not copy transcript."),
+ void copyToClipboard(record.text).then((ok) =>
+ ok
+ ? toast.success("Transcript copied")
+ : toast.error("Could not copy transcript."),
)
}
>
diff --git a/studio/frontend/src/features/chat/openai-codex-connect.tsx b/studio/frontend/src/features/chat/openai-codex-connect.tsx
index 4f11de3d404..73a9b76cccc 100644
--- a/studio/frontend/src/features/chat/openai-codex-connect.tsx
+++ b/studio/frontend/src/features/chat/openai-codex-connect.tsx
@@ -3,6 +3,7 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { openLink } from "@/lib/open-link";
import { useEffect, useRef, useState } from "react";
import {
@@ -189,7 +190,7 @@ export function OpenAICodexConnect({
type="button"
size="sm"
variant="outline"
- onClick={() => void navigator.clipboard.writeText(flow.user_code || "")}
+ onClick={() => void copyToClipboard(flow.user_code || "")}
>
Copy code
</Button>
diff --git a/studio/frontend/src/features/recipe-studio/components/executions/publish-execution-dialog.tsx b/studio/frontend/src/features/recipe-studio/components/executions/publish-execution-dialog.tsx
index e665edbcd7f..4ff29ca65fa 100644
--- a/studio/frontend/src/features/recipe-studio/components/executions/publish-execution-dialog.tsx
+++ b/studio/frontend/src/features/recipe-studio/components/executions/publish-execution-dialog.tsx
@@ -23,9 +23,9 @@ import {
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { toastError, toastSuccess } from "@/shared/toast";
import type { RecipeExecutionRecord } from "../../execution-types";
-import { copyTextToClipboard } from "../../executions/execution-helpers";
type PublishExecutionDialogProps = {
open: boolean;
@@ -119,7 +119,7 @@ export function PublishExecutionDialog({
if (!publishedUrl) {
return;
}
- const ok = await copyTextToClipboard(publishedUrl);
+ const ok = await copyToClipboard(publishedUrl);
if (ok) {
toastSuccess("Dataset link copied");
return;
diff --git a/studio/frontend/src/features/recipe-studio/executions/execution-helpers.ts b/studio/frontend/src/features/recipe-studio/executions/execution-helpers.ts
index efa7ef3a5b2..43f490c4e55 100644
--- a/studio/frontend/src/features/recipe-studio/executions/execution-helpers.ts
+++ b/studio/frontend/src/features/recipe-studio/executions/execution-helpers.ts
@@ -173,30 +173,3 @@ export function delay(ms: number): Promise<void> {
window.setTimeout(resolve, ms);
});
}
-
-export async function copyTextToClipboard(text: string): Promise<boolean> {
- try {
- if (navigator.clipboard?.writeText) {
- await navigator.clipboard.writeText(text);
- return true;
- }
- } catch {
- // fallthrough to legacy path
- }
-
- try {
- const textarea = document.createElement("textarea");
- textarea.value = text;
- textarea.setAttribute("readonly", "");
- textarea.style.position = "fixed";
- textarea.style.top = "0";
- textarea.style.left = "-9999px";
- document.body.appendChild(textarea);
- textarea.select();
- const ok = document.execCommand("copy");
- document.body.removeChild(textarea);
- return ok;
- } catch {
- return false;
- }
-}
diff --git a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts
index 4cb612f44c1..f68ade47245 100644
--- a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts
+++ b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-persistence.ts
@@ -2,12 +2,12 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useCallback, useEffect, useMemo, useState } from "react";
+import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { toastError, toastSuccess } from "@/shared/toast";
import { normalizeNonEmptyName } from "@/utils";
import { removeUnstructuredBlock } from "../api";
import {
buildSignature,
- copyTextToClipboard,
formatSavedLabel,
} from "../executions/execution-helpers";
import { useRecipeStudioStore } from "../stores/recipe-studio";
@@ -333,9 +333,7 @@ export function useRecipePersistence({
const safePayload = sanitizeSeedForShare(
stripApiKeys(payloadResult.payload),
);
- const ok = await copyTextToClipboard(
- JSON.stringify(safePayload, null, 2),
- );
+ const ok = await copyToClipboard(JSON.stringify(safePayload, null, 2));
if (!ok) {
throw new Error("Clipboard not available.");
}
diff --git a/studio/frontend/src/features/settings/components/key-reveal-card.tsx b/studio/frontend/src/features/settings/components/key-reveal-card.tsx
index a67bbe9c0a7..08a4fb8139f 100644
--- a/studio/frontend/src/features/settings/components/key-reveal-card.tsx
+++ b/studio/frontend/src/features/settings/components/key-reveal-card.tsx
@@ -8,7 +8,12 @@ import { Tick02Icon } from "@/lib/tick-icon";
import { cn } from "@/lib/utils";
import { Copy01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
+
+function selectToken(input: HTMLInputElement | null) {
+ input?.focus();
+ input?.select();
+}
export function KeyRevealCard({
rawKey,
@@ -19,11 +24,19 @@ export function KeyRevealCard({
}) {
const t = useT();
const [copied, setCopied] = useState(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Preselected so Ctrl+C works even where the copy button cannot.
+ useEffect(() => {
+ selectToken(inputRef.current);
+ }, []);
const handleCopy = async () => {
if (await copyToClipboard(rawKey)) {
setCopied(true);
setTimeout(() => setCopied(false), 1800);
+ } else {
+ selectToken(inputRef.current);
}
};
@@ -38,31 +51,44 @@ export function KeyRevealCard({
{t("settings.apiKeys.newTokenCreated")}
</span>
</div>
- <button
- type="button"
- onClick={handleCopy}
+ <div
className={cn(
- "flex w-full items-center justify-between gap-3 rounded-md border border-border bg-muted/40 px-3 py-2.5 font-mono text-sm transition-colors hover:bg-muted/60",
- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
+ "flex w-full items-center gap-3 rounded-md border border-border bg-muted/40 px-3 py-2.5 font-mono text-sm transition-colors",
+ "has-[input:focus-visible]:ring-1 has-[input:focus-visible]:ring-ring",
copied && "border-emerald-500/40 bg-emerald-500/10",
)}
- aria-label={
- copied
- ? t("settings.apiKeys.accessTokenCopied")
- : t("settings.apiKeys.copyAccessToken")
- }
>
- <code
- className="min-w-0 flex-1 break-all text-left text-foreground"
- data-reload-snapshot-sensitive
- >
- {rawKey}
- </code>
- <HugeiconsIcon
- icon={copied ? Tick02Icon : Copy01Icon}
- className={cn("size-4 shrink-0", copied && "text-emerald-600")}
+ <input
+ ref={inputRef}
+ type="text"
+ readOnly={true}
+ value={rawKey}
+ onFocus={(event) => event.currentTarget.select()}
+ aria-label={t("settings.apiKeys.newTokenCreated")}
+ className="min-w-0 flex-1 bg-transparent text-foreground outline-none"
+ data-reload-snapshot-sensitive={true}
/>
- </button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ onClick={handleCopy}
+ className={cn(
+ "-my-1 shrink-0",
+ copied && "text-emerald-600 hover:text-emerald-600",
+ )}
+ aria-label={
+ copied
+ ? t("settings.apiKeys.accessTokenCopied")
+ : t("settings.apiKeys.copyAccessToken")
+ }
+ >
+ <HugeiconsIcon
+ icon={copied ? Tick02Icon : Copy01Icon}
+ className="size-4"
+ />
+ </Button>
+ </div>
<div className="flex items-center justify-between gap-3 pt-0.5">
<p className="text-ui-11 text-muted-foreground">
{t("settings.apiKeys.copyNow")}
diff --git a/studio/frontend/src/lib/copy-to-clipboard.ts b/studio/frontend/src/lib/copy-to-clipboard.ts
index f0b04e76f83..e1369632f88 100644
--- a/studio/frontend/src/lib/copy-to-clipboard.ts
+++ b/studio/frontend/src/lib/copy-to-clipboard.ts
@@ -22,6 +22,17 @@ async function copyWithTauriClipboard(text: string): Promise<boolean> {
function copyWithExecCommand(text: string): boolean {
if (typeof document === "undefined" || !document.body) return false;
+ // A modal's focus trap pulls focus back off the textarea, so the copy would
+ // take an empty selection; the copy event writes the text regardless.
+ let written = false;
+ const onCopy = (event: ClipboardEvent) => {
+ if (!event.clipboardData) return;
+ event.clipboardData.setData("text/plain", text);
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ written = true;
+ };
+
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.readOnly = true;
@@ -35,13 +46,14 @@ function copyWithExecCommand(text: string): boolean {
textarea.focus({ preventScroll: true });
textarea.select();
+ document.addEventListener("copy", onCopy, true);
try {
- const ok = document.execCommand("copy");
- document.body.removeChild(textarea);
- return ok;
+ return document.execCommand("copy") && written;
} catch {
- document.body.removeChild(textarea);
return false;
+ } finally {
+ document.removeEventListener("copy", onCopy, true);
+ document.body.removeChild(textarea);
}
}
diff --git a/studio/frontend/tests/copy-to-clipboard.test.ts b/studio/frontend/tests/copy-to-clipboard.test.ts
index c265842f62e..09a2df77c3d 100644
--- a/studio/frontend/tests/copy-to-clipboard.test.ts
+++ b/studio/frontend/tests/copy-to-clipboard.test.ts
@@ -25,6 +25,10 @@ type Recorder = {
appended: number;
removed: number;
nativeWrites: string[];
+ clipboardData: string[];
+ /** How the copy event was taken over: capture phase, cancelled, not re-dispatched. */
+ copyHandling: string[];
+ copyListeners: number;
};
type EnvOptions = {
@@ -34,6 +38,8 @@ type EnvOptions = {
/** "absent" drops navigator.clipboard entirely, as an insecure context does. */
clipboard?: "ok" | "reject" | "absent";
execCommandResult?: boolean;
+ /** Whether execCommand("copy") dispatches a copy event, as every current browser does. */
+ copyEvent?: boolean;
};
let generation = 0;
@@ -56,6 +62,7 @@ async function load(options: EnvOptions) {
stub = "ok",
clipboard = "ok",
execCommandResult = true,
+ copyEvent = true,
} = options;
const recorder: Recorder = {
@@ -64,7 +71,12 @@ async function load(options: EnvOptions) {
appended: 0,
removed: 0,
nativeWrites: [],
+ clipboardData: [],
+ copyHandling: [],
+ copyListeners: 0,
};
+ // Listener -> capture flag; as in the DOM, removal must repeat the flag to match.
+ const listeners = new Map<(event: unknown) => void, boolean>();
const windowStub: Record<string, unknown> = {
location: { protocol: tauri ? "tauri:" : "https:" },
@@ -93,8 +105,41 @@ async function load(options: EnvOptions) {
select() {},
};
},
+ addEventListener(
+ type: string,
+ listener: (event: unknown) => void,
+ capture?: boolean,
+ ) {
+ if (type !== "copy") return;
+ listeners.set(listener, capture === true);
+ if (capture === true) recorder.copyHandling.push("capture");
+ recorder.copyListeners = listeners.size;
+ },
+ removeEventListener(
+ type: string,
+ listener: (event: unknown) => void,
+ capture?: boolean,
+ ) {
+ if (type === "copy" && listeners.get(listener) === (capture === true)) {
+ listeners.delete(listener);
+ }
+ recorder.copyListeners = listeners.size;
+ },
+ // Only the copy event carries text here; the stub has no selection to copy.
execCommand(command: string) {
recorder.execCommands.push(command);
+ if (copyEvent) {
+ const event = {
+ clipboardData: {
+ setData: (_type: string, data: string) =>
+ recorder.clipboardData.push(data),
+ },
+ preventDefault: () => recorder.copyHandling.push("preventDefault"),
+ stopImmediatePropagation: () =>
+ recorder.copyHandling.push("stopImmediatePropagation"),
+ };
+ for (const listener of listeners.keys()) listener(event);
+ }
return execCommandResult;
},
});
@@ -181,7 +226,30 @@ test("web build reaches execCommand in the same tick when clipboard is absent",
"the synchronous fallback must also run inside the gesture",
);
assert.equal(result, true);
+ assert.deepEqual(
+ recorder.clipboardData,
+ ["hello"],
+ "written by the copy event",
+ );
+ assert.deepEqual(recorder.copyHandling, [
+ "capture",
+ "preventDefault",
+ "stopImmediatePropagation",
+ ]);
assert.equal(recorder.removed, recorder.appended, "textarea must be cleaned up");
+ assert.equal(recorder.copyListeners, 0, "copy listener must be removed");
+});
+
+test("execCommand fallback reports failure when no copy event carried the text", async () => {
+ const { copyToClipboard, recorder } = await load({
+ tauri: false,
+ clipboard: "absent",
+ copyEvent: false,
+ });
+
+ assert.equal(await copyToClipboard("hello"), false);
+ assert.deepEqual(recorder.execCommands, ["copy"]);
+ assert.equal(recorder.copyListeners, 0);
});
test("Tauri build copies natively and never touches navigator.clipboard", async () => {