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 / Desktop: name chat exports after model, title and day, and reopen the last save folder (#12586)

Leo Borcherding7790e1b308e2
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.py
index 6442a315fb8..f773861ed9f 100644
--- a/studio/backend/core/inference/diffusion_engine_router.py
+++ b/studio/backend/core/inference/diffusion_engine_router.py
@@ -676,7 +676,11 @@ def loaded_state_of(engine: Any) -> Any:
return getattr(engine, "_state", None)
-def note_engine_pick(engine: Optional[str], loaded_by: Any = None, before: Any = _NO_SNAPSHOT) -> None:
+def note_engine_pick(
+ engine: Optional[str],
+ loaded_by: Any = None,
+ before: Any = _NO_SNAPSHOT,
+) -> None:
"""Record the load's engine pick for the status provenance. The load route calls it once ``loaded_by`` (the
engine) has accepted the load, inside ``begin_load_on``'s transition lock, so a pick refused by admission,
preflight or the arbiter never relabels the resident model and concurrent loads register in order. With an engine
diff --git a/studio/backend/core/inference/diffusion_segment.py b/studio/backend/core/inference/diffusion_segment.py
index 9e1e26b4395..60ce9429888 100644
--- a/studio/backend/core/inference/diffusion_segment.py
+++ b/studio/backend/core/inference/diffusion_segment.py
@@ -158,7 +158,10 @@ def _override_dir() -> Optional[str]:
has = lambda *names: any((path / name).is_file() for name in names) # noqa: E731
complete = (
has("config.json")
- and (has(SEGMENTER_WEIGHTS_FILE) or _shards_complete(path / (SEGMENTER_WEIGHTS_FILE + ".index.json")))
+ and (
+ has(SEGMENTER_WEIGHTS_FILE)
+ or _shards_complete(path / (SEGMENTER_WEIGHTS_FILE + ".index.json"))
+ )
# AutoTokenizer (CLIPTokenizer for sam3) loads tokenizer.json, else needs vocab.json and merges.txt together.
and (has("tokenizer.json") or (has("vocab.json") and has("merges.txt")))
)
@@ -369,7 +372,6 @@ def _other_owner_on(ordinal: Optional[int]) -> Optional[str]:
call (or aborts) instead."""
try:
from core.inference import gpu_arbiter
-
held = gpu_arbiter.residents()
physical = None if ordinal is None else gpu_arbiter.physical_gpu_ids([ordinal])
except Exception: # noqa: BLE001 -- no arbiter: nothing else is placed through it
@@ -537,13 +539,11 @@ def _free_device_cache(device: Optional[str]) -> None:
if device and device.startswith("cuda"):
with suppress(Exception):
import torch
-
with torch.cuda.device(device):
torch.cuda.empty_cache()
elif device == "mps":
with suppress(Exception):
import torch
-
torch.mps.empty_cache()
@@ -639,7 +639,6 @@ class MaskSegmenter:
logger.info("images.segment: unloaded from %s (%s)", device, reason)
return True
-
def _call_on_accelerator(self) -> bool:
"""A call is in flight on the GPU / MPS, or has not chosen its device yet."""
device = self._call_device
diff --git a/studio/backend/core/inference/gpu_arbiter.py b/studio/backend/core/inference/gpu_arbiter.py
index b5a5471738f..d938cfcfeb6 100644
--- a/studio/backend/core/inference/gpu_arbiter.py
+++ b/studio/backend/core/inference/gpu_arbiter.py
@@ -673,7 +673,7 @@ def acquire_for(
acting = account_id or current_account_id()
# The segmenter's VRAM goes to this owner: a mask call arriving before its register returns stays off the card.
handover = owner != DIFFUSION or register is not None or replacing
- with _lock, (_handover_fence() if handover else nullcontext()):
+ with _lock, _handover_fence() if handover else nullcontext():
if expected_current is not None and (_owner, _owner_epoch) != expected_current:
raise OwnerChangedError("The resident GPU model changed; retry the load.")
coreside = policy != "off" and owner in _KEPT_UNDER_ALWAYS
diff --git a/studio/backend/tests/test_deepseek_v41_defaults.py b/studio/backend/tests/test_deepseek_v41_defaults.py
index e3783d3684e..e3bbe244ce1 100644
--- a/studio/backend/tests/test_deepseek_v41_defaults.py
+++ b/studio/backend/tests/test_deepseek_v41_defaults.py
@@ -76,12 +76,10 @@ def test_reasoning_effort_ladder(model_id):
def test_requires_symmetric_kv():
from core.inference.llama_cpp import LlamaCppBackend
-
assert LlamaCppBackend._requires_symmetric_kv(None, "deepseek41") is True
def test_listed_as_default_gguf():
from core.inference.defaults import DEFAULT_MODELS_GGUF, DEFAULT_MODELS_STANDARD
-
assert "unsloth/DeepSeek-V4.1-Flash-1017-GGUF" in DEFAULT_MODELS_GGUF
assert "unsloth/DeepSeek-V4.1-Flash-1017-GGUF" in DEFAULT_MODELS_STANDARD
diff --git a/studio/backend/tests/test_diffusion_engine_load_contract.py b/studio/backend/tests/test_diffusion_engine_load_contract.py
index d1a49337f39..144091f05a7 100644
--- a/studio/backend/tests/test_diffusion_engine_load_contract.py
+++ b/studio/backend/tests/test_diffusion_engine_load_contract.py
@@ -103,7 +103,12 @@ def test_the_two_begin_load_signatures_declare_local_files_only_alike():
def _drive_the_images_load(
- monkeypatch, *, user_initiated: bool, engine_choice = None, begin_load_error = None, notes = None
+ monkeypatch,
+ *,
+ user_initiated: bool,
+ engine_choice = None,
+ begin_load_error = None,
+ notes = None,
):
"""Run ``POST /images/load``'s body with the NATIVE engine selected; return the mock engine.
diff --git a/studio/backend/tests/test_diffusion_segment.py b/studio/backend/tests/test_diffusion_segment.py
index 7a3f911c572..ba7090bba8c 100644
--- a/studio/backend/tests/test_diffusion_segment.py
+++ b/studio/backend/tests/test_diffusion_segment.py
@@ -309,7 +309,9 @@ def test_mask_planes_do_not_outlive_their_text(tiny_sam3, monkeypatch):
def __call__(self, **kwargs):
# Every earlier text's kept mask planes are already OR-ed into the union and gone.
- assert all(ref() is None for ref in planes), "an earlier concept's mask planes are still held"
+ assert all(
+ ref() is None for ref in planes
+ ), "an earlier concept's mask planes are still held"
return self._model(**kwargs)
def _load(path, device, dtype):
@@ -334,7 +336,9 @@ def test_mask_planes_do_not_outlive_their_text(tiny_sam3, monkeypatch):
combined = Image.open(io.BytesIO(alone[0].mask_png))
for other in alone[1:]:
combined = ImageChops.lighter(combined, Image.open(io.BytesIO(other.mask_png)))
- assert ImageChops.difference(combined, Image.open(io.BytesIO(result.mask_png))).getbbox() is None
+ assert (
+ ImageChops.difference(combined, Image.open(io.BytesIO(result.mask_png))).getbbox() is None
+ )
def test_raw_outputs_do_not_outlive_their_concept(tiny_sam3, monkeypatch):
@@ -490,14 +494,19 @@ def test_choose_device_never_shares_a_card_another_owner_holds(monkeypatch):
monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
monkeypatch.setattr(torch.cuda, "device", lambda ordinal: contextlib.nullcontext())
monkeypatch.setattr(torch.cuda, "is_bf16_supported", lambda *a, **k: True)
- monkeypatch.setattr(seg, "_cuda_free_mib", lambda ordinal: (60_000, 80_000)) # plenty of room either way
+ monkeypatch.setattr(
+ seg, "_cuda_free_mib", lambda ordinal: (60_000, 80_000)
+ ) # plenty of room either way
monkeypatch.setattr(seg, "_resident_cuda_ordinal", lambda: None)
monkeypatch.setattr(gpu_arbiter, "physical_gpu_ids", lambda visible: frozenset(visible))
if getattr(torch.backends, "mps", None) is not None:
monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)
cases = [
({}, "cuda:0"), # nobody
- ({gpu_arbiter.DIFFUSION: frozenset({0})}, "cuda:0"), # the image model: SAM 3 runs beside it by design
+ (
+ {gpu_arbiter.DIFFUSION: frozenset({0})},
+ "cuda:0",
+ ), # the image model: SAM 3 runs beside it by design
({gpu_arbiter.CHAT: frozenset({0})}, "cpu"),
({gpu_arbiter.VIDEO: frozenset({0}), gpu_arbiter.DIFFUSION: frozenset({0})}, "cpu"),
({gpu_arbiter.CHAT: None}, "cpu"), # unknown GPUs: every card
@@ -542,10 +551,14 @@ def test_a_failed_load_places_no_weights(tmp_path, monkeypatch):
raise OSError("no tokenizer files")
monkeypatch.setattr(transformers.AutoTokenizer, "from_pretrained", _broken_tokenizer)
- monkeypatch.setattr(transformers.Sam3Model, "from_pretrained", lambda *a, **k: placed.append(a) or object())
+ monkeypatch.setattr(
+ transformers.Sam3Model, "from_pretrained", lambda *a, **k: placed.append(a) or object()
+ )
with pytest.raises(OSError):
segmenter._load(str(tmp_path), "cuda:0", torch.bfloat16)
- assert placed == [] and not segmenter.loaded # the tokenizer fails before any weights reach the card
+ assert (
+ placed == [] and not segmenter.loaded
+ ) # the tokenizer fails before any weights reach the card
# Weights placed, then the load fails: they are dropped and the device cache handed back.
monkeypatch.setattr(transformers.AutoTokenizer, "from_pretrained", lambda *a, **k: object())
@@ -714,7 +727,9 @@ def test_partial_override_does_not_read_as_downloaded(tmp_path, monkeypatch):
monkeypatch.setattr(seg, "transformers_supports_sam3", lambda: True)
(tmp_path / "config.json").write_text("{}")
assert seg.model_dir() is None # config only: no weights, no tokenizer
- (tmp_path / "model.safetensors.index.json").write_text('{"weight_map": {"w": "model-1.safetensors"}}')
+ (tmp_path / "model.safetensors.index.json").write_text(
+ '{"weight_map": {"w": "model-1.safetensors"}}'
+ )
(tmp_path / "model-1.safetensors").write_bytes(b"")
assert seg.model_dir() is None # still no tokenizer
(tmp_path / "vocab.json").write_text("{}")
@@ -861,7 +876,10 @@ def test_a_release_timing_out_as_the_call_settles_still_unloads(monkeypatch):
monkeypatch.setattr(seg, "_cuda_free_mib", lambda ordinal: (None, None))
def _segment_on(image, concepts, threshold, path, device, dtype):
- segmenter._model, segmenter.device = object(), device # the CUDA copy stays resident after the call
+ segmenter._model, segmenter.device = (
+ object(),
+ device,
+ ) # the CUDA copy stays resident after the call
return types.SimpleNamespace()
real_after = segmenter._after_call
@@ -874,7 +892,9 @@ def test_a_release_timing_out_as_the_call_settles_still_unloads(monkeypatch):
monkeypatch.setattr(segmenter, "_segment_on", _segment_on)
monkeypatch.setattr(segmenter, "_after_call", _after_call)
- worker = threading.Thread(target = segmenter.segment, args = (Image.new("RGB", (8, 8)), "cat"), kwargs = {"path": "x"})
+ worker = threading.Thread(
+ target = segmenter.segment, args = (Image.new("RGB", (8, 8)), "cat"), kwargs = {"path": "x"}
+ )
worker.start()
assert settled.wait(10)
# Timed out on a call that will not see the flag: the handover waits out the tail and unloads, never letting the
@@ -1030,10 +1050,14 @@ def test_a_call_during_a_handovers_register_stays_off_the_card(tiny_sam3, monkey
monkeypatch.setattr(seg, "_segmenter", segmenter)
monkeypatch.setitem(sys.modules, "core.inference.diffusion_segment", seg)
monkeypatch.setattr(
- seg, "choose_device", lambda allow_gpu: ("cuda:0", torch.bfloat16) if allow_gpu else ("cpu", torch.float32)
+ seg,
+ "choose_device",
+ lambda allow_gpu: ("cuda:0", torch.bfloat16) if allow_gpu else ("cpu", torch.float32),
)
placed = []
- monkeypatch.setattr(segmenter, "_segment_on", lambda *a: placed.append(a[4]) or types.SimpleNamespace())
+ monkeypatch.setattr(
+ segmenter, "_segment_on", lambda *a: placed.append(a[4]) or types.SimpleNamespace()
+ )
monkeypatch.setattr(gpu_arbiter, "_residents", {})
monkeypatch.setattr(gpu_arbiter, "_owner", None)
monkeypatch.setattr(gpu_arbiter, "_release_idle_video_servers", lambda reason: None)
@@ -1045,7 +1069,9 @@ def test_a_call_during_a_handovers_register_stays_off_the_card(tiny_sam3, monkey
seen["fenced"] = gpu_arbiter.handover_in_progress()
with pytest.raises(seg.SegmenterBusyError):
segmenter.segment(image, "cat", path = tiny_sam3)
- segmenter.segment(image, "cat", allow_gpu = False, path = tiny_sam3) # the CPU is not being handed over
+ segmenter.segment(
+ image, "cat", allow_gpu = False, path = tiny_sam3
+ ) # the CPU is not being handed over
gpu_arbiter.acquire_for(gpu_arbiter.VIDEO, register = _register)
assert seen["fenced"] is True and placed == ["cpu"]
@@ -1054,7 +1080,9 @@ def test_a_call_during_a_handovers_register_stays_off_the_card(tiny_sam3, monkey
assert placed == ["cpu", "cuda:0"]
# A raising register still lifts the fence.
with pytest.raises(RuntimeError):
- gpu_arbiter.acquire_for(gpu_arbiter.VIDEO, register = lambda: (_ for _ in ()).throw(RuntimeError("load failed")))
+ gpu_arbiter.acquire_for(
+ gpu_arbiter.VIDEO, register = lambda: (_ for _ in ()).throw(RuntimeError("load failed"))
+ )
assert gpu_arbiter.handover_in_progress() is False
@@ -1096,7 +1124,12 @@ def test_training_start_refuses_while_a_mask_call_holds_the_gpu(monkeypatch):
class SegmenterReleaseTimeoutError(RuntimeError):
pass
- def release_segmenter(self, reason, wait = False, handover = False):
+ def release_segmenter(
+ self,
+ reason,
+ wait = False,
+ handover = False,
+ ):
if handover:
raise self.SegmenterReleaseTimeoutError("still running")
return False
@@ -1104,13 +1137,17 @@ def test_training_start_refuses_while_a_mask_call_holds_the_gpu(monkeypatch):
monkeypatch.setitem(sys.modules, "core.inference.diffusion_segment", _StillRunning())
with pytest.raises(gpu_arbiter.SegmenterStillRunningError, match = "try again"):
gpu_arbiter.release_mask_segmenter("training start")
- assert gpu_arbiter.SegmenterStillRunningError.blocks_training is True # the core trainer re-raises it
+ assert (
+ gpu_arbiter.SegmenterStillRunningError.blocks_training is True
+ ) # the core trainer re-raises it
unloaded = []
for off_torch in (True, False):
resident = SimpleNamespace(
runs_off_torch_device = off_torch, is_loaded = True, unload = lambda: unloaded.append(1)
)
- monkeypatch.setattr(diffusion_engine_router, "get_active_diffusion_engine", lambda r = resident: r)
+ monkeypatch.setattr(
+ diffusion_engine_router, "get_active_diffusion_engine", lambda r = resident: r
+ )
monkeypatch.setattr(gpu_arbiter, "release", lambda owner: None)
# A RuntimeError: the diffusion start route answers 409 instead of spawning beside SAM 3.
with pytest.raises(gpu_arbiter.SegmenterStillRunningError):
@@ -1165,7 +1202,11 @@ def test_a_render_releases_the_segmenter_first(monkeypatch):
# Before the run, on every render (a resident model renders with no arbiter acquire).
source = inspect.getsource(inference_routes._generate_diffusion_image_run)
release = source.index("_release_mask_segmenter_for_render")
- assert source.index("_enhance_generate_prompts(backend, request)") < release < source.index("for attempt in range(2)")
+ assert (
+ source.index("_enhance_generate_prompts(backend, request)")
+ < release
+ < source.index("for attempt in range(2)")
+ )
def test_release_segmenter_never_creates_one(monkeypatch):
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index cbd10272d55..2315f1b7ca9 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -278,8 +278,11 @@ export const BUDGET = {
// 160 B raw / 189 B transfer margin.
// The Loaded models card's eject confirmation (#14161, eager shell) adds 356 B raw / 158 B transfer over 28a222f20
// (6,842,874 B raw, 2,060,540 B transfer); limits = that build plus the same margin.
- transferBytes: 2_060_729,
- rawBytes: 6_843_034,
+ // Naming a chat export after its model, title and day (#12586) adds 615 B raw / 65 B transfer (6,842,183 ->
+ // 6,842,798 B raw, 2,060,321 -> 2,060,386 B transfer against 46e4f50bea, one machine and build, Node 24,
+ // 96 chunks): the name builder sits beside the chat exporters in the eager chat chunk. Raised by that growth.
+ transferBytes: 2_060_794,
+ rawBytes: 6_843_649,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
index f2135828e54..ed9e8f0e3a7 100644
--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
@@ -87,6 +87,7 @@ import { usePlusMenuPrefsStore } from "../stores/plus-menu-prefs-store";
import type { ThreadRecord, MessageRecord } from "../types";
import {
buildNamedConversationsMarkdown,
+ conversationExportBasename,
createConversationMarkdownBuilder,
createConversationMarkdownExporter,
} from "../utils/conversation-markdown-export";
@@ -304,6 +305,12 @@ function exportTs(): string {
return new Date().toISOString().slice(0, 19).replace(/:/g, "-");
}
+async function conversationBasename(threadId: string): Promise<string> {
+ // Best effort: the content is already loaded, so a failed name lookup must not fail the export.
+ const thread = await getStoredChatThread(threadId).catch(() => undefined);
+ return conversationExportBasename(thread, new Date());
+}
+
// attachment content is separate from message content and must be flattened for export
function messageToText(msg: { content: unknown; attachments?: unknown }): string {
const parts: string[] = [];
@@ -486,7 +493,7 @@ export async function exportConversationShareGPT(threadId: string): Promise<void
if (conversations.length === 0) { toast.info("No exportable content."); return; }
await downloadBlob(
ndjsonBody([JSON.stringify({ conversations })]),
- "conversation-" + exportTs() + ".jsonl",
+ `${await conversationBasename(threadId)}.jsonl`,
"application/x-ndjson",
);
}
@@ -515,7 +522,7 @@ async function exportConversationJsonl(
if (oaiMsgs.length === 0) { toast.info("No exportable content."); return; }
await downloadBlob(
ndjsonBody([conversationJsonlBody(oaiMsgs, layout)]),
- `conversation${layout === "messages" ? "-messages" : ""}-${exportTs()}.jsonl`,
+ `${await conversationBasename(threadId)}${layout === "messages" ? " messages" : ""}.jsonl`,
"application/x-ndjson",
);
}
@@ -534,7 +541,7 @@ export async function exportConversationCsv(threadId: string): Promise<void> {
if (rows.length <= 1) { toast.info("No exportable content."); return; }
await downloadBlob(
csvDocument(rows),
- "conversation-" + exportTs() + ".csv",
+ `${await conversationBasename(threadId)}.csv`,
CSV_MIME,
);
}
@@ -556,7 +563,7 @@ export const exportConversationMarkdown = createConversationMarkdownExporter({
loadMessages: loadDisplayedBranchMessages,
renderMessage: messageToMarkdown,
download: downloadBlob,
- exportTimestamp: exportTs,
+ exportBasename: conversationBasename,
notifyNoContent: () => toast.info("No exportable content."),
});
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
index dace477ffc0..5eefd8bdb5d 100644
--- a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
@@ -7,6 +7,8 @@ import {
type ConversationMarkdownMessage,
buildConversationMarkdown,
} from "./conversation-markdown.ts";
+import { parseExternalModelId } from "../external-providers.ts";
+import { modelDisplayName } from "../../hub/lib/model-identity.ts";
import { stripSearchImageTokens } from "../search-images/search-images.ts";
type StoredConversationMessage = {
@@ -25,7 +27,7 @@ type ConversationMarkdownExportDependencies<
filename: string,
mimeType: string,
) => Promise<void>;
- readonly exportTimestamp: () => string;
+ readonly exportBasename: (threadId: string) => Promise<string>;
readonly notifyNoContent: () => void;
};
@@ -59,6 +61,51 @@ export function createConversationMarkdownBuilder<
};
}
+// UTF-8 bytes, leaving room under the usual 255-byte name limit for " (YYYY-MM-DD).jsonl".
+const MAX_EXPORT_BASENAME_BYTES = 200;
+
+function filenamePart(text: string): string {
+ return (
+ text
+ .replace(/\s+/g, " ")
+ // Bidi controls too: `x\u202egpj.exe` would display as `xexe.jpg`.
+ // eslint-disable-next-line no-control-regex
+ .replace(/[\\/:*?"<>|\u0000-\u001f\u007f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "_")
+ .trim()
+ );
+}
+
+function localDateStamp(date: Date): string {
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+}
+
+/** `<model> - <title> (YYYY-MM-DD)`, dropping a missing part; model = its display name. */
+export function conversationExportBasename(
+ thread:
+ | { readonly title?: string | null; readonly modelId?: string | null }
+ | null
+ | undefined,
+ date: Date,
+): string {
+ const modelId = parseExternalModelId(thread?.modelId)?.modelId ?? thread?.modelId ?? "";
+ // Not split("/"): a Windows local path has no "/" and would put the whole path in the name.
+ const model = filenamePart(modelDisplayName(modelId));
+ const title = filenamePart(thread?.title ?? "");
+ const name = [model, title].filter(Boolean).join(" - ") || "conversation";
+ // Cut on a code point (no lone surrogate); Windows refuses a trailing dot or space.
+ const encoder = new TextEncoder();
+ let capped = "";
+ let bytes = 0;
+ for (const char of name) {
+ bytes += encoder.encode(char).length;
+ if (bytes > MAX_EXPORT_BASENAME_BYTES) break;
+ capped += char;
+ }
+ capped = capped.replace(/[. ]+$/, "");
+ return `${capped || "conversation"} (${localDateStamp(date)})`;
+}
+
/** A title safe to interpolate into a heading: a line break would end it. */
function headingText(title: string): string {
return title.replace(/\s+/g, " ").trim();
@@ -90,7 +137,7 @@ export function createConversationMarkdownExporter<
loadMessages,
renderMessage,
download,
- exportTimestamp,
+ exportBasename,
notifyNoContent,
}: ConversationMarkdownExportDependencies<Message>): (
threadId: string,
@@ -109,7 +156,7 @@ export function createConversationMarkdownExporter<
}
await download(
markdown,
- `conversation-${exportTimestamp()}.${CONVERSATION_MARKDOWN_EXTENSION}`,
+ `${await exportBasename(threadId)}.${CONVERSATION_MARKDOWN_EXTENSION}`,
CONVERSATION_MARKDOWN_MIME_TYPE,
);
};
diff --git a/studio/frontend/tests/chat-export-system-prompt.test.ts b/studio/frontend/tests/chat-export-system-prompt.test.ts
index 3ded24ab1f1..19271302732 100644
--- a/studio/frontend/tests/chat-export-system-prompt.test.ts
+++ b/studio/frontend/tests/chat-export-system-prompt.test.ts
@@ -21,6 +21,7 @@ import {
} from "../src/features/chat/utils/conversation-markdown.ts";
import {
buildNamedConversationsMarkdown,
+ conversationExportBasename,
createConversationMarkdownBuilder,
createConversationMarkdownExporter,
} from "../src/features/chat/utils/conversation-markdown-export.ts";
@@ -172,6 +173,7 @@ function loadExporters(
renderConversationBlocks,
buildConversationMarkdown,
buildNamedConversationsMarkdown,
+ conversationExportBasename,
createConversationMarkdownBuilder,
createConversationMarkdownExporter,
CONVERSATION_MARKDOWN_MIME_TYPE,
diff --git a/studio/frontend/tests/conversation-markdown-export.test.ts b/studio/frontend/tests/conversation-markdown-export.test.ts
index ce89eba7e34..6def6f53881 100644
--- a/studio/frontend/tests/conversation-markdown-export.test.ts
+++ b/studio/frontend/tests/conversation-markdown-export.test.ts
@@ -5,6 +5,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
buildNamedConversationsMarkdown,
+ conversationExportBasename,
createConversationMarkdownBuilder,
createConversationMarkdownExporter,
} from "../src/features/chat/utils/conversation-markdown-export.ts";
@@ -32,12 +33,12 @@ function exporterFor(
download: async (content, filename, mimeType) => {
downloads.push({ content, filename, mimeType });
},
- exportTimestamp: () => "2026-07-31T00-00-00",
+ exportBasename: async (threadId) => `named-${threadId}`,
notifyNoContent: () => notifications.push("empty"),
});
}
-test("downloads a timestamped Markdown conversation", async () => {
+test("downloads a Markdown conversation under the thread's name", async () => {
const downloads: Array<{
content: string;
filename: string;
@@ -53,7 +54,7 @@ test("downloads a timestamped Markdown conversation", async () => {
assert.deepEqual(downloads, [
{
content: "<!-- unsloth-chat-v1:[14] -->\n\n## User\n\nHello\n",
- filename: "conversation-2026-07-31T00-00-00.md",
+ filename: "named-thread-1.md",
mimeType: "text/markdown",
},
]);
@@ -162,3 +163,86 @@ test("renderer tokens never leave a thread, downloaded or copied", async () => {
assert.ok(!copied.includes("[[img:"));
assert.ok(copied.includes(stripped));
});
+
+const EXPORT_DAY = new Date(2026, 8, 1, 23, 30);
+
+test("an export is named after its model, title and local day", () => {
+ assert.equal(
+ conversationExportBasename(
+ { modelId: "unsloth/Gemma-4-26B-A4B", title: "Biology of Stag Beetles Explained" },
+ EXPORT_DAY,
+ ),
+ "Gemma-4-26B-A4B - Biology of Stag Beetles Explained (2026-09-01)",
+ );
+});
+
+test("an export drops whichever of model and title is missing", () => {
+ assert.equal(
+ conversationExportBasename({ title: "Untitled run" }, EXPORT_DAY),
+ "Untitled run (2026-09-01)",
+ );
+ assert.equal(
+ conversationExportBasename({ modelId: "qwen3", title: " " }, EXPORT_DAY),
+ "qwen3 (2026-09-01)",
+ );
+ assert.equal(
+ conversationExportBasename(null, EXPORT_DAY),
+ "conversation (2026-09-01)",
+ );
+});
+
+test("an export name never carries a path separator or a trailing dot", () => {
+ assert.equal(
+ conversationExportBasename(
+ { modelId: "org/model", title: 'a/b\\c: "d"?\nnext...' },
+ EXPORT_DAY,
+ ),
+ "model - a_b_c_ _d__ next (2026-09-01)",
+ );
+});
+
+test("an export name is cut by UTF-8 bytes on a code point and drops bidi controls", () => {
+ const name = conversationExportBasename(
+ { title: `${"a".repeat(197)}\u{1F600}tail \u202Egpj.exe` },
+ EXPORT_DAY,
+ );
+ assert.equal(name, `${"a".repeat(197)} (2026-09-01)`);
+ const cjk = conversationExportBasename({ title: "\u7532".repeat(120) }, EXPORT_DAY);
+ assert.equal(cjk, `${"\u7532".repeat(66)} (2026-09-01)`);
+ assert.ok(new TextEncoder().encode(`${cjk}.jsonl`).length <= 255);
+ assert.equal(
+ conversationExportBasename({ title: "x\u202Egpj.exe" }, EXPORT_DAY),
+ "x_gpj.exe (2026-09-01)",
+ );
+});
+
+test("an external provider chat is named after the model, not its internal id", () => {
+ assert.equal(
+ conversationExportBasename(
+ { modelId: "external::provider-1::openai%2Fgpt-4o", title: "Hi" },
+ EXPORT_DAY,
+ ),
+ "gpt-4o - Hi (2026-09-01)",
+ );
+});
+
+test("a local model is named after the model, not the folder it loads from", () => {
+ assert.equal(
+ conversationExportBasename(
+ { modelId: "C:\\Users\\alex\\models\\Qwen3-4B-Q4_K_M.gguf", title: "Hi" },
+ EXPORT_DAY,
+ ),
+ "Qwen3-4B-Q4_K_M - Hi (2026-09-01)",
+ );
+ assert.equal(
+ conversationExportBasename(
+ {
+ modelId:
+ "/home/alex/.cache/huggingface/hub/models--unsloth--Qwen3-4B-GGUF/snapshots/abc123/Qwen3-4B-Q4_K_M.gguf",
+ title: "Hi",
+ },
+ EXPORT_DAY,
+ ),
+ "Qwen3-4B-GGUF - Hi (2026-09-01)",
+ );
+});
diff --git a/studio/frontend/tests/markdown-export-branches.test.ts b/studio/frontend/tests/markdown-export-branches.test.ts
index 69bc0c65829..eb4b77bc4f0 100644
--- a/studio/frontend/tests/markdown-export-branches.test.ts
+++ b/studio/frontend/tests/markdown-export-branches.test.ts
@@ -130,6 +130,7 @@ function loadExporters(
csvDocument,
CSV_MIME,
exportTs: () => "ts",
+ conversationBasename: async () => "conversation",
downloadBlob: async (body: string) => {
downloads.push(body);
},
diff --git a/studio/frontend/tests/sharegpt-export-branches.test.ts b/studio/frontend/tests/sharegpt-export-branches.test.ts
index 204651970a4..155470d265d 100644
--- a/studio/frontend/tests/sharegpt-export-branches.test.ts
+++ b/studio/frontend/tests/sharegpt-export-branches.test.ts
@@ -93,6 +93,7 @@ function loadExporters(
messageToText: (message: StoredMessage) => message.content,
csvEscape: (value: string) => value,
exportTs: () => "ts",
+ conversationBasename: async () => "conversation",
downloadBlob: async (body: string) => {
downloads.push(body);
},
diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rs
index 86e01a24669..a84a08face2 100644
--- a/studio/src-tauri/src/native_file_dialogs.rs
+++ b/studio/src-tauri/src/native_file_dialogs.rs
@@ -21,6 +21,7 @@ const CHAT_IMPORT_EXTENSIONS: &[&str] = &["json", "jsonl", "ndjson", "csv", "md"
const CHAT_IMPORT_TYPE_ERROR: &str =
"Chat import must be a .json, .jsonl, .ndjson, .csv, or .md file.";
const TRAINING_CONFIG_EXTENSIONS: &[&str] = &["yaml", "yml"];
+const LAST_SAVE_DIR_FILE: &str = "last-save-dir.txt";
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -206,6 +207,25 @@ fn invoke_body_bytes(body: &tauri::ipc::InvokeBody) -> Option<Cow<'_, [u8]>> {
}
}
+/// GTK keeps no per-app last folder, so without this every Linux save starts from scratch.
+fn last_save_dir(config_dir: &Path) -> Option<PathBuf> {
+ let saved = fs::read_to_string(config_dir.join(LAST_SAVE_DIR_FILE)).ok()?;
+ let dir = PathBuf::from(saved.trim_end_matches(['\r', '\n']));
+ (dir.is_absolute() && dir.is_dir()).then_some(dir)
+}
+
+/// Best effort: failing to remember a folder must not fail a save that already landed.
+fn remember_save_dir(config_dir: &Path, saved_path: &Path) {
+ let Some(dir) = saved_path.parent().filter(|dir| dir.is_absolute()) else {
+ return;
+ };
+ let Some(dir) = dir.to_str() else {
+ return;
+ };
+ let _ = fs::create_dir_all(config_dir)
+ .and_then(|()| fs::write(config_dir.join(LAST_SAVE_DIR_FILE), dir));
+}
+
fn local_dialog_path(path: tauri_plugin_dialog::FilePath) -> Result<PathBuf, String> {
path.into_path()
.map_err(|_| "Only local filesystem paths are supported.".to_string())
@@ -442,9 +462,13 @@ pub async fn save_native_file(
request: tauri::ipc::Request<'_>,
) -> Result<Option<String>, String> {
crate::native_intents::ensure_main_window(&webview)?;
- Ok(save_request_with_dialog(&app, &request, None)
- .await?
- .map(|path| saved_file_name(&path)))
+ let config_dir = app.path().app_config_dir().ok();
+ let start = config_dir.as_deref().and_then(last_save_dir);
+ let saved = save_request_with_dialog(&app, &request, start.as_deref()).await?;
+ if let (Some(config_dir), Some(path)) = (&config_dir, &saved) {
+ remember_save_dir(config_dir, path);
+ }
+ Ok(saved.map(|path| saved_file_name(&path)))
}
pub(crate) fn request_file<'a>(
@@ -503,15 +527,20 @@ pub async fn begin_native_file_save(
let file_name = default_file_name(&file_name);
let (filter_name, extensions) = save_filter(&file_name);
let extension_refs = extensions.iter().map(String::as_str).collect::<Vec<_>>();
+ let config_dir = app.path().app_config_dir().ok();
let (tx, rx) = tokio::sync::oneshot::channel();
- app.dialog()
+ let mut dialog = app
+ .dialog()
.file()
.set_title("Save Unsloth export")
.set_file_name(file_name)
- .add_filter(filter_name, &extension_refs)
- .save_file(move |path| {
- let _ = tx.send(path);
- });
+ .add_filter(filter_name, &extension_refs);
+ if let Some(dir) = config_dir.as_deref().and_then(last_save_dir) {
+ dialog = dialog.set_directory(dir);
+ }
+ dialog.save_file(move |path| {
+ let _ = tx.send(path);
+ });
let selected_path = rx
.await
.map_err(|_| "Save dialog closed unexpectedly.".to_string())?
@@ -552,6 +581,7 @@ pub async fn append_native_file_save_chunk(
#[tauri::command]
pub async fn finish_native_file_save(
webview: tauri::Webview,
+ app: AppHandle,
registry: State<'_, NativeSaveRegistry>,
token: String,
) -> Result<String, String> {
@@ -559,9 +589,17 @@ pub async fn finish_native_file_save(
let save = registry
.take(&token)
.ok_or_else(|| "That native export is no longer available.".to_string())?;
- tokio::task::spawn_blocking(move || finish_native_save(save))
+ let destination = save
+ .lock()
+ .map(|save| save.destination.clone())
+ .map_err(|_| "Native export handle is unavailable.".to_string())?;
+ let name = tokio::task::spawn_blocking(move || finish_native_save(save))
.await
- .map_err(|error| format!("Failed to finish the native export: {error}"))?
+ .map_err(|error| format!("Failed to finish the native export: {error}"))??;
+ if let Ok(config_dir) = app.path().app_config_dir() {
+ remember_save_dir(&config_dir, &destination);
+ }
+ Ok(name)
}
#[tauri::command]
@@ -655,15 +693,20 @@ pub async fn save_native_file_from_url(
let file_name = default_file_name(&file_name);
let (filter_name, extensions) = save_filter(&file_name);
let extension_refs = extensions.iter().map(String::as_str).collect::<Vec<_>>();
+ let config_dir = app.path().app_config_dir().ok();
let (tx, rx) = tokio::sync::oneshot::channel();
- app.dialog()
+ let mut dialog = app
+ .dialog()
.file()
.set_title("Save Unsloth export")
.set_file_name(file_name)
- .add_filter(filter_name, &extension_refs)
- .save_file(move |path| {
- let _ = tx.send(path);
- });
+ .add_filter(filter_name, &extension_refs);
+ if let Some(dir) = config_dir.as_deref().and_then(last_save_dir) {
+ dialog = dialog.set_directory(dir);
+ }
+ dialog.save_file(move |path| {
+ let _ = tx.send(path);
+ });
let selected_path = rx
.await
.map_err(|_| "Save dialog closed unexpectedly.".to_string())?
@@ -673,6 +716,9 @@ pub async fn save_native_file_from_url(
return Ok(None);
};
stream_url_to_path(&url, &path, DOWNLOAD_READ_TIMEOUT, None).await?;
+ if let Some(config_dir) = &config_dir {
+ remember_save_dir(config_dir, &path);
+ }
Ok(Some(saved_file_name(&path)))
}
@@ -1305,6 +1351,23 @@ mod tests {
assert!(!extensions.iter().any(|extension| extension == "bad!"));
}
+ #[test]
+ fn the_last_save_folder_is_remembered_until_it_disappears() {
+ let config = tempfile::tempdir().unwrap();
+ let exports = tempfile::tempdir().unwrap();
+ assert_eq!(last_save_dir(config.path()), None);
+
+ remember_save_dir(config.path(), &exports.path().join("chat (2026-10-02).md"));
+ assert_eq!(
+ last_save_dir(config.path()).as_deref(),
+ Some(exports.path())
+ );
+
+ let gone = exports.path().to_path_buf();
+ drop(exports);
+ assert_eq!(last_save_dir(config.path()), None, "{}", gone.display());
+ }
+
#[test]
fn saved_chat_attachments_keep_their_own_extension() {
// Settings > Data saves attachments here; a name outside the filter can