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: put a just-created API token in the Agents command and API examples (#15890)

Michael Han3db27a2b5271
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
index 0f6c7c2f2ed..ebd89d033ed 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
@@ -116,6 +116,7 @@ import {
useApiMonitor,
} from "./use-api-monitor";
import { PlayIcon } from "lucide-react";
+import { useFreshApiKeyStore } from "@/features/settings/stores/fresh-api-key-store";
const API_INFERENCE_PREFIX_RE = /^\/api\/inference/;
const V1_PREFIX_RE = /^\/v1\//;
@@ -916,6 +917,7 @@ function QuickStart({
const choices = useApiExampleChoices(baseUrl, "curl");
const [useTunnel] = useApiTunnelPref();
const [kind, setKind] = useState<ApiExampleKind>("chat");
+ const freshKey = useFreshApiKeyStore((s) => s.key);
return (
<div className="flex flex-col items-center gap-4 px-6 py-12 text-center">
<span className="flex size-10 items-center justify-center icon-disc text-muted-foreground">
@@ -940,10 +942,12 @@ function QuickStart({
<div className="w-full max-w-2xl text-left">
<ApiExampleBox
choices={choices}
+ hasRealKey={freshKey !== null}
code={buildApiExample({
baseUrl,
model: model ?? "MODEL_ID",
sampling: {},
+ apiKey: freshKey ?? undefined,
language: choices.language,
os: choices.os,
})}
@@ -952,9 +956,17 @@ function QuickStart({
) : (
<div className="w-full max-w-3xl text-left">
{kind === "media" ? (
- <MediaApiExamples useTunnel={useTunnel} showHeading={false} />
+ <MediaApiExamples
+ apiKey={freshKey}
+ useTunnel={useTunnel}
+ showHeading={false}
+ />
) : kind === "audio" ? (
- <AudioApiExamples useTunnel={useTunnel} showHeading={false} />
+ <AudioApiExamples
+ apiKey={freshKey}
+ useTunnel={useTunnel}
+ showHeading={false}
+ />
) : (
<DecisionApiSection showHeading={false} />
)}
diff --git a/studio/frontend/src/features/api-monitor/components/api-example-box.tsx b/studio/frontend/src/features/api-monitor/components/api-example-box.tsx
index bf379ecf5dd..5f2e69a6c2b 100644
--- a/studio/frontend/src/features/api-monitor/components/api-example-box.tsx
+++ b/studio/frontend/src/features/api-monitor/components/api-example-box.tsx
@@ -52,17 +52,19 @@ export function ApiExampleBox({
choices,
code,
fitContent,
+ hasRealKey = false,
}: {
choices: ApiExampleChoices;
code: string;
fitContent?: boolean;
+ hasRealKey?: boolean;
}) {
return (
<ExampleCodeBox
code={code}
language={apiExampleShikiLanguage(choices.language, choices.os)}
label="Example request"
- redactFromReload={false}
+ redactFromReload={hasRealKey}
pills={
<ExampleToggle
label="Language"
diff --git a/studio/frontend/src/features/api-monitor/components/api-example-dialog.tsx b/studio/frontend/src/features/api-monitor/components/api-example-dialog.tsx
index 1f571c759a8..d1e4f80bae1 100644
--- a/studio/frontend/src/features/api-monitor/components/api-example-dialog.tsx
+++ b/studio/frontend/src/features/api-monitor/components/api-example-dialog.tsx
@@ -9,6 +9,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { authFetch } from "@/features/auth";
+import { useFreshApiKeyStore } from "@/features/settings/stores/fresh-api-key-store";
import { type ReactElement, useEffect, useState } from "react";
import {
type ApiSamplingDefaults,
@@ -31,6 +32,7 @@ export function ApiExampleDialog({
}): ReactElement {
const [sampling, setSampling] = useState<ApiSamplingDefaults | null>(null);
const choices = useApiExampleChoices(baseUrl, "python");
+ const freshKey = useFreshApiKeyStore((s) => s.key);
useEffect(() => {
if (!open) return;
@@ -67,10 +69,12 @@ export function ApiExampleDialog({
<ApiExampleBox
fitContent={true}
choices={choices}
+ hasRealKey={freshKey !== null}
code={buildApiExample({
baseUrl,
model,
sampling,
+ apiKey: freshKey ?? undefined,
language: choices.language,
os: choices.os,
})}
diff --git a/studio/frontend/src/features/settings/components/agent-command.ts b/studio/frontend/src/features/settings/components/agent-command.ts
index bb4474b4b0e..313b4f58f38 100644
--- a/studio/frontend/src/features/settings/components/agent-command.ts
+++ b/studio/frontend/src/features/settings/components/agent-command.ts
@@ -103,8 +103,10 @@ export function buildAgentShellCommands(
os: AgentCommandOs,
agent: string,
modelArgs: string,
+ // Fresh keys only: the CLI caches an explicit key per base, so a stale one overwrites a working one.
+ freshKey: string | null = null,
): AgentShellCommands {
- const primaryBase = buildAgentCommand(base, null, os, agent);
+ const primaryBase = buildAgentCommand(base, freshKey, os, agent);
return {
primary: appendCommand(primaryBase, modelArgs),
subagent: appendCommand(
diff --git a/studio/frontend/src/features/settings/stores/fresh-api-key-store.ts b/studio/frontend/src/features/settings/stores/fresh-api-key-store.ts
new file mode 100644
index 00000000000..3fb485540b9
--- /dev/null
+++ b/studio/frontend/src/features/settings/stores/fresh-api-key-store.ts
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Memory only: the raw key is shown once and must not outlive the page.
+
+import { create } from "zustand";
+
+interface FreshApiKeyState {
+ key: string | null;
+ setKey: (key: string) => void;
+ forgetIfRevoked: (keyPrefix: string) => void;
+}
+
+// auth/storage.py: key_prefix is the 8 characters after this marker.
+const RAW_KEY_MARKER = "sk-unsloth-";
+
+export const useFreshApiKeyStore = create<FreshApiKeyState>((set, get) => ({
+ key: null,
+ setKey: (key) => set({ key }),
+ forgetIfRevoked: (keyPrefix) => {
+ const key = get().key;
+ if (
+ key !== null &&
+ keyPrefix &&
+ key.startsWith(`${RAW_KEY_MARKER}${keyPrefix}`)
+ ) {
+ set({ key: null });
+ }
+ },
+}));
diff --git a/studio/frontend/src/features/settings/tabs/agents-tab.tsx b/studio/frontend/src/features/settings/tabs/agents-tab.tsx
index 339f74f0137..0a2a4e14dbe 100644
--- a/studio/frontend/src/features/settings/tabs/agents-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/agents-tab.tsx
@@ -89,6 +89,7 @@ import {
type ExampleOs,
useSettingsPanelPrefsStore,
} from "../stores/settings-panel-prefs-store";
+import { useFreshApiKeyStore } from "../stores/fresh-api-key-store";
import { LineBox } from "@/components/ui/line-box";
const DOCS_URL = UNSLOTH_START_DOCS_URL;
@@ -348,12 +349,15 @@ function CopyableCode({
copied,
onCopy,
breakAll = true,
+ sensitive = false,
}: {
value: string;
copyLabel: string;
copied: boolean;
onCopy: () => void;
breakAll?: boolean;
+ /** Holds a real API key: reload-snapshot.js clears it instead of saving it to sessionStorage. */
+ sensitive?: boolean;
}) {
const t = useT();
@@ -365,6 +369,7 @@ function CopyableCode({
"block min-w-0 whitespace-pre-wrap border border-border bg-background/70 py-2.5 pr-9 pl-4 font-mono text-ui-11 leading-relaxed text-foreground dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.05*var(--contrast-wash-gain,1)))]",
breakAll ? "break-all" : "break-words",
)}
+ data-reload-snapshot-sensitive={sensitive ? "" : undefined}
>
{value}
</LineBox>
@@ -390,9 +395,11 @@ function CopyableCode({
function SubagentSection({
agent,
command,
+ sensitive,
}: {
agent: AgentDetails;
command: string;
+ sensitive: boolean;
}) {
const t = useT();
const prompt =
@@ -429,6 +436,7 @@ function SubagentSection({
copyLabel={t("settings.agents.subagent.copySetupCommand")}
copied={commandCopy.copied}
onCopy={commandCopy.copy}
+ sensitive={sensitive}
/>
</div>
@@ -473,6 +481,7 @@ export function AgentsTab() {
// A Tauri origin is unreachable for the CLI, so use the backend URL; on loopback deviceType
// decides (it can report wsl).
const studioBase = isTauri ? (serverUrl ?? getApiBase()) : origin;
+ const freshApiKey = useFreshApiKeyStore((s) => s.key);
const inferredCommandOs: ExampleOs = (
isLoopbackBase(studioBase)
? deviceType === "windows"
@@ -641,12 +650,12 @@ export function AgentsTab() {
const modelArgs = attachOnly
? ""
: [selectedModelArgs, selectedModelFlags].filter(Boolean).join(" ");
- // No key: the CLI caches an explicit key per base, overwriting a working saved one.
const shellCommands = buildAgentShellCommands(
studioBase,
commandOs,
selectedAgent,
modelArgs,
+ freshApiKey,
);
const command = shellCommands.primary;
const {
@@ -1421,6 +1430,7 @@ export function AgentsTab() {
copyLabel={t("settings.agents.copyGeneratedCommand")}
copied={copied}
onCopy={handleCopy}
+ sensitive={freshApiKey !== null}
/>
{selectedAgent === "vscode" && (
<p className="text-ui-11 leading-relaxed text-muted-foreground">
@@ -1445,6 +1455,7 @@ export function AgentsTab() {
key={`${selectedAgent}:${commandModel}`}
command={shellCommands.subagent}
agent={selectedAgentDetails}
+ sensitive={freshApiKey !== null}
/>
<p className="text-ui-11 leading-relaxed text-muted-foreground">
diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
index 41a00fa7104..7345bb9a2ae 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -45,6 +45,7 @@ import { SettingsSection } from "../components/settings-section";
import { ApiExamplesPanel } from "../components/api-example-tabs";
import { useApiTunnelPref } from "../components/usage-examples";
import { usePublishAccessUrls } from "../hooks/use-publish-access-urls";
+import { useFreshApiKeyStore } from "../stores/fresh-api-key-store";
function expiryDays(key: ApiKey): number | null {
if (!key.expires_at) return null;
@@ -64,6 +65,12 @@ export function ApiKeysTab() {
const [revoking, setRevoking] = useState(false);
const [regenerate, setRegenerate] = useState(false);
const [revealed, setRevealed] = useState<string | null>(null);
+ // The examples read the store, not `revealed`: that dies with this tab and on Done.
+ const freshKey = useFreshApiKeyStore((s) => s.key);
+ const reveal = (raw: string) => {
+ setRevealed(raw);
+ useFreshApiKeyStore.getState().setKey(raw);
+ };
const [useTunnel, setUseTunnel] = useApiTunnelPref();
// Owner-only routes, as the Remote & LAN tab is.
usePublishAccessUrls(isOwner);
@@ -147,9 +154,10 @@ export function ApiKeysTab() {
revokeTarget.name,
expiryDays(revokeTarget),
);
- setRevealed(created.key);
+ reveal(created.key);
}
await revokeApiKey(revokeTarget.id);
+ useFreshApiKeyStore.getState().forgetIfRevoked(revokeTarget.key_prefix);
await load();
setRevokeTarget(null);
} catch (cause) {
@@ -218,7 +226,7 @@ export function ApiKeysTab() {
>
<CreateKeyForm
onCreated={(raw) => {
- setRevealed(raw);
+ reveal(raw);
void load();
}}
onError={setActionError}
@@ -276,7 +284,7 @@ export function ApiKeysTab() {
</section>
<ApiExamplesPanel
- apiKey={revealed}
+ apiKey={freshKey}
useTunnel={useTunnel}
onUseTunnelChange={setUseTunnel}
keylessScope={keyless.scope}
@@ -286,7 +294,7 @@ export function ApiKeysTab() {
{/* Installation-wide, so owner-only routes. */}
<SettingsSection title="Access & monitoring">
- {isOwner ? <McpAccessSection apiKey={revealed} /> : null}
+ {isOwner ? <McpAccessSection apiKey={freshKey} /> : null}
{isOwner ? <KeylessApiAccessLink /> : null}
<MonitorLink hideHeading={true} />
</SettingsSection>
diff --git a/studio/frontend/tests/agents-fresh-api-key.test.ts b/studio/frontend/tests/agents-fresh-api-key.test.ts
new file mode 100644
index 00000000000..f49e2a1a3bf
--- /dev/null
+++ b/studio/frontend/tests/agents-fresh-api-key.test.ts
@@ -0,0 +1,75 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+import { buildAgentShellCommands } from "../src/features/settings/components/agent-command.ts";
+import { useFreshApiKeyStore } from "../src/features/settings/stores/fresh-api-key-store.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+// `revealed` is local to the API tab, so it is lost on a tab switch or Done; examples read the store.
+test("Settings > API examples and MCP take the stored key, not the tab-local one", () => {
+ const tab = readSrc("features/settings/tabs/api-keys-tab.tsx");
+ assert.match(tab, /<ApiExamplesPanel\s+apiKey=\{freshKey\}/);
+ assert.match(tab, /<McpAccessSection apiKey=\{freshKey\} \/>/);
+});
+
+test("the API monitor page's examples carry the new key", () => {
+ const page = readSrc("features/api-monitor/api-monitor-page.tsx");
+ assert.match(page, /apiKey: freshKey \?\? undefined/);
+ assert.match(page, /<MediaApiExamples\s+apiKey=\{freshKey\}/);
+ assert.match(page, /<AudioApiExamples\s+apiKey=\{freshKey\}/);
+ const dialog = readSrc(
+ "features/api-monitor/components/api-example-dialog.tsx",
+ );
+ assert.match(dialog, /apiKey: freshKey \?\? undefined/);
+});
+
+const LAN_STUDIO = "http://10.4.0.110:8888";
+const KEY = "sk-unsloth-abcd1234efgh5678";
+
+test("a key just created reaches the Agents command for a LAN Studio", () => {
+ const commands = buildAgentShellCommands(
+ LAN_STUDIO,
+ "unix",
+ "opencode",
+ "--model XHToken/Spark-X2.6-4B-GGUF:Q8_0",
+ KEY,
+ );
+ assert.equal(
+ commands.primary,
+ `UNSLOTH_STUDIO_URL=http://10.4.0.110:8888 unsloth start opencode --api-key ${KEY} --model XHToken/Spark-X2.6-4B-GGUF:Q8_0`,
+ );
+ assert.match(
+ commands.subagent,
+ /--api-key sk-unsloth-abcd1234efgh5678 --as-subagent/,
+ );
+});
+
+test("without a fresh key the command stays keyless", () => {
+ const commands = buildAgentShellCommands(LAN_STUDIO, "unix", "opencode", "");
+ assert.doesNotMatch(commands.primary, /--api-key/);
+});
+
+test("loopback never carries the key: the CLI mints its own there", () => {
+ assert.equal(
+ buildAgentShellCommands("http://127.0.0.1:8888", "unix", "claude", "", KEY)
+ .primary,
+ "unsloth start claude",
+ );
+});
+
+test("revoking that key drops it, revoking another keeps it", () => {
+ const store = useFreshApiKeyStore.getState();
+ store.setKey(KEY);
+ store.forgetIfRevoked("zzzz9999");
+ assert.equal(useFreshApiKeyStore.getState().key, KEY);
+ store.forgetIfRevoked("abcd1234");
+ assert.equal(useFreshApiKeyStore.getState().key, null);
+});
+
+test("the Agents commands that can carry the key are kept out of reload snapshots", () => {
+ const tab = readSrc("features/settings/tabs/agents-tab.tsx");
+ assert.match(tab, /data-reload-snapshot-sensitive=\{sensitive \? "" : undefined\}/);
+ assert.equal(tab.match(/sensitive=\{freshApiKey !== null\}/g)?.length, 2);
+});
diff --git a/studio/frontend/tests/api-settings-tab.test.ts b/studio/frontend/tests/api-settings-tab.test.ts
index 26229857ad9..5983a3344e5 100644
--- a/studio/frontend/tests/api-settings-tab.test.ts
+++ b/studio/frontend/tests/api-settings-tab.test.ts
@@ -44,7 +44,7 @@ test("usage examples sit right under the keys, where a new key lands", () => {
test("MCP, keyless access and the monitor sit under one heading", () => {
assert.match(
TAB,
- /<SettingsSection title="Access & monitoring">\s*\{isOwner \? <McpAccessSection apiKey=\{revealed\} \/> : null\}\s*\{isOwner \? <KeylessApiAccessLink \/> : null\}\s*<MonitorLink hideHeading=\{true\} \/>\s*<\/SettingsSection>/,
+ /<SettingsSection title="Access & monitoring">\s*\{isOwner \? <McpAccessSection apiKey=\{freshKey\} \/> : null\}\s*\{isOwner \? <KeylessApiAccessLink \/> : null\}\s*<MonitorLink hideHeading=\{true\} \/>\s*<\/SettingsSection>/,
);
const keyless = readSrc("features/settings/components/keyless-api-access-link.tsx");
assert.match(keyless, /<SettingsRow\s+label="Keyless API access"/);
diff --git a/studio/frontend/tests/mcp-access-section.test.ts b/studio/frontend/tests/mcp-access-section.test.ts
index b74794beea1..7387405af09 100644
--- a/studio/frontend/tests/mcp-access-section.test.ts
+++ b/studio/frontend/tests/mcp-access-section.test.ts
@@ -33,7 +33,7 @@ const LOCALES = { ar, de, en, es, fr, he, hi, it, ja, ko, ptBR, ru, sv, zhCN };
test("only the owner sees it, in the access group, and settings search finds it", () => {
assert.match(
API_TAB,
- /\{isOwner \? <McpAccessSection apiKey=\{revealed\} \/> : null\}/,
+ /\{isOwner \? <McpAccessSection apiKey=\{freshKey\} \/> : null\}/,
);
assert.match(
API_TAB,