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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix Studio desktop reliability (#7255)
Wasim Yousef Said5f92658ac35f
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex a7e9469cfcd..e6c89b9cd7a 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -51,9 +51,12 @@ async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {const { getCurrentWindow, LogicalSize } = await import("@tauri-apps/api/window");+ const { invoke } = await import("@tauri-apps/api/core");if (!isCurrent()) return;const win = getCurrentWindow();+ await invoke("reset_app_window_layout_initialized");+ if (!isCurrent()) return;await win.setResizable(false);if (!isCurrent()) return;await win.setSize(new LogicalSize(SETUP_WINDOW_WIDTH, SETUP_WINDOW_HEIGHT));@@ -98,18 +101,20 @@ async function applyAppWindowLayout(if (!isCurrent()) return;const win = getCurrentWindow();- // Decide first-launch vs restore from the on-disk state file BEFORE touching the- // window. Probing the window after restoreStateCurrent is unreliable: on GTK,- // set_size on a hidden window is deferred until show(), so innerSize() reads a- // stale value and a baseline fallback would overwrite the queued restore. On- // macOS the same probe works, hence the inconsistency between prior iterations.- const hasSavedState = await invoke<boolean>("has_saved_window_state");+ // Setup-window activity may create plugin state before the full app is ever+ // shown, so use a dedicated full-app marker to decide whether restoration is+ // appropriate. Keep checking plugin state so a missing/corrupt state file+ // falls back to a monitor-safe centered layout.+ const [hasInitializedAppLayout, hasSavedState] = await Promise.all([+ invoke<boolean>("has_initialized_app_window_layout"),+ invoke<boolean>("has_saved_window_state"),+ ]);if (!isCurrent()) return;await win.setResizable(true);if (!isCurrent()) return;- if (hasSavedState) {+ if (hasInitializedAppLayout && hasSavedState) {// Subsequent launch: plugin restores size/position/maximized, with built-in// off-screen protection for positions saved on a now-disconnected display.await restoreStateCurrent(@@ -144,6 +149,9 @@ async function applyAppWindowLayout(});if (!isCurrent()) return;await enforceMinimumWindowSize(win, LogicalSize, isCurrent);++ if (!isCurrent()) return;+ await invoke("mark_app_window_layout_initialized");}async function showWindowFallback(): Promise<void> {diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex 293971904fe..8dd7bcdd9aa 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -141,6 +141,7 @@ import {import type { TrainingRunSummary } from "@/features/training";import { useExportRuntimeStore } from "@/features/export";import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";import { ShutdownDialog } from "@/components/shutdown-dialog";import { translate, useT, type TranslationKey } from "@/i18n";@@ -971,11 +972,13 @@ export function AppSidebar() {const ids = item.type === "single"? [item.id]: (await listStoredChatThreads({ pairId: item.id })).map((t) => t.id);- await Promise.all(- ids.map((id) => exportConversationByFormat(id, format)),- );- } catch {- toast.error("Export failed.");+ for (const id of ids) {+ await exportConversationByFormat(id, format);+ }+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Export failed.");+ }}}}>diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 32fbd61e09c..bece2930b3e 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -102,6 +102,7 @@ import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";import { isTauri } from "@/lib/api-base";import { copyToClipboard } from "@/lib/copy-to-clipboard";import { MicIcon } from "@/lib/mic-icon";+import { downloadFile, isDownloadCancelled } from "@/lib/native-files";import { toast } from "@/lib/toast";import { Tick02Icon } from "@/lib/tick-icon";import { cn } from "@/lib/utils";@@ -2911,9 +2912,9 @@ const ComposerToolsMenu: FC<{ side?: "top" | "bottom" }> = ({<DropdownMenuItemonSelect={() => {if (!activeThreadId) return;- exportConversationRawJsonl(activeThreadId).catch(() =>- toast.error("Export failed."),- );+ exportConversationRawJsonl(activeThreadId).catch((error) => {+ if (!isDownloadCancelled(error)) toast.error("Export failed.");+ });}}>Raw JSONL@@ -2921,9 +2922,9 @@ const ComposerToolsMenu: FC<{ side?: "top" | "bottom" }> = ({<DropdownMenuItemonSelect={() => {if (!activeThreadId) return;- exportConversationCsv(activeThreadId).catch(() =>- toast.error("Export failed."),- );+ exportConversationCsv(activeThreadId).catch((error) => {+ if (!isDownloadCancelled(error)) toast.error("Export failed.");+ });}}>CSV@@ -2931,9 +2932,9 @@ const ComposerToolsMenu: FC<{ side?: "top" | "bottom" }> = ({<DropdownMenuItemonSelect={() => {if (!activeThreadId) return;- exportConversationShareGPT(activeThreadId).catch(() =>- toast.error("Export failed."),- );+ exportConversationShareGPT(activeThreadId).catch((error) => {+ if (!isDownloadCancelled(error)) toast.error("Export failed.");+ });}}>ShareGPT JSONL@@ -3896,6 +3897,21 @@ const EditAssistantMessageButton: FC = () => {);};+async function exportMessageMarkdown(content: string): Promise<void> {+ try {+ await downloadFile(+ content,+ `message-${Date.now()}.md`,+ "text/markdown",+ );+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Could not save Markdown export.", {+ description: error instanceof Error ? error.message : String(error),+ });+ }+ }+}const AssistantActionBar: FC = () => {const { forkMessage, forkDisabled } = useForkMessageAction();const [detailsOpen, setDetailsOpen] = useState(false);@@ -3964,7 +3980,10 @@ const AssistantActionBar: FC = () => {<GitBranchIcon strokeWidth={1.75} className="size-icon" />Fork in new chat</ActionBarMorePrimitive.Item>- <ActionBarPrimitive.ExportMarkdown asChild={true}>+ <ActionBarPrimitive.ExportMarkdown+ asChild={true}+ onExport={exportMessageMarkdown}+ ><ActionBarMorePrimitive.Item className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-[12px] px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"><HugeiconsIconicon={Download01Icon}diff --git a/studio/frontend/src/components/tauri/window-titlebar.tsx b/studio/frontend/src/components/tauri/window-titlebar.tsxindex d86af54f797..8d11bbd2290 100644--- a/studio/frontend/src/components/tauri/window-titlebar.tsx+++ b/studio/frontend/src/components/tauri/window-titlebar.tsx@@ -115,7 +115,7 @@ export function WindowTitlebar({? "var(--studio-sidebar-expanded-width,17.5rem)": "var(--studio-sidebar-collapsed-width,3rem)": "0px";- const contentBorderLeft = `calc(${sidebarWidth} + 12px)`;+ const contentBorderLeft = pinned ? `calc(${sidebarWidth} + 12px)` : "0px";const refreshMaximized = useCallback(async () => {if (!enabled) {@@ -232,10 +232,10 @@ export function WindowTitlebar({)}aria-label="Window titlebar">- {showSidebarSurface && (+ {showSidebarSurface && pinned && (<divaria-hidden="true"- className="pointer-events-none absolute top-full h-3 w-px -translate-x-px bg-sidebar"+ className="pointer-events-none absolute top-full size-3 -translate-x-px bg-sidebar"style={{ left: sidebarWidth }}/>)}@@ -246,7 +246,7 @@ export function WindowTitlebar({style={{ left: contentBorderLeft, right: 0 }}/>)}- {showSidebarSurface && (+ {showSidebarSurface && pinned && (<divaria-hidden="true"className="pointer-events-none absolute top-full size-3 -translate-x-px rounded-tl-[12px] border-l border-t border-sidebar-border bg-background"@@ -257,7 +257,7 @@ export function WindowTitlebar({<divclassName={cn("pointer-events-auto absolute left-0 top-0 flex h-full min-w-0 items-center",- pinned ? "gap-2 px-3" : "justify-center",+ pinned ? "gap-2 pl-3" : "justify-center",)}style={{ width: sidebarWidth }}onMouseDown={handleDragMouseDown}diff --git a/studio/frontend/src/components/ui/input-group.tsx b/studio/frontend/src/components/ui/input-group.tsxindex 55984452f01..7ec7a2e3d42 100644--- a/studio/frontend/src/components/ui/input-group.tsx+++ b/studio/frontend/src/components/ui/input-group.tsx@@ -122,7 +122,7 @@ function InputGroupInput({<Inputdata-slot="input-group-control"className={cn(- "rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 aria-invalid:ring-0 dark:bg-transparent flex-1",+ "rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 aria-invalid:ring-0 dark:bg-transparent dark:focus-visible:bg-transparent flex-1",className,)}{...props}diff --git a/studio/frontend/src/features/chat/projects-page.tsx b/studio/frontend/src/features/chat/projects-page.tsxindex 5e0b37895b4..ee94a9537fc 100644--- a/studio/frontend/src/features/chat/projects-page.tsx+++ b/studio/frontend/src/features/chat/projects-page.tsx@@ -30,6 +30,8 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select";+import { isTauri } from "@/lib/api-base";+import { isDownloadCancelled, pickNativeChatImport } from "@/lib/native-files";import { toast } from "@/lib/toast";import {createChatProject,@@ -118,6 +120,40 @@ export function ProjectsPage() {}}++ async function selectGlobalImportFile() {+ if (!isTauri) {+ globalImportRef.current?.click();+ return;+ }+ try {+ const selected = await pickNativeChatImport();+ if (!selected) return;+ setImportTargetId(projects[0]?.id ?? null);+ setImportFile(new File([selected.content], selected.name));+ } catch (error) {+ toast.error("Import failed.", {+ description: error instanceof Error ? error.message : String(error),+ });+ }+ }++ async function selectProjectImportFile(projectId: string) {+ if (!isTauri) {+ projectImportRefs.current.get(projectId)?.click();+ return;+ }+ try {+ const selected = await pickNativeChatImport();+ if (!selected) return;+ await handleImport(new File([selected.content], selected.name), projectId);+ } catch (error) {+ toast.error("Import failed.", {+ description: error instanceof Error ? error.message : String(error),+ });+ }+ }+async function commitImport() {if (!importFile) return;const file = importFile;@@ -183,8 +219,10 @@ export function ProjectsPage() {const threads = await listStoredChatThreads({ projectId: project.id, includeArchived: false });const ids = [...new Set(threads.map((t) => t.id))];await exportProjectConversations(ids, fmt, project.name);- } catch {- toast.error("Export failed.");+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Export failed.");+ }}}@@ -215,8 +253,10 @@ export function ProjectsPage() {} else {await exportBulkConversationsSeparate(ids, fmt, basename);}- } catch {- toast.error("Export failed.");+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Export failed.");+ }}}@@ -294,7 +334,7 @@ export function ProjectsPage() {</Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-56">- <DropdownMenuItem onSelect={() => globalImportRef.current?.click()}>+ <DropdownMenuItem onSelect={() => void selectGlobalImportFile()}><HugeiconsIcon icon={Upload01Icon} strokeWidth={1.75} className="size-icon" />Import chats…</DropdownMenuItem>@@ -470,7 +510,7 @@ export function ProjectsPage() {<DropdownMenuItemonSelect={(e) => {e.stopPropagation();- projectImportRefs.current.get(project.id)?.click();+ void selectProjectImportFile(project.id);}}><HugeiconsIcon icon={Upload01Icon} strokeWidth={1.75} className="size-icon" />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.tsxindex 68f24a7b089..09c4944a141 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@@ -10,6 +10,8 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import { downloadFile, isDownloadCancelled } from "@/lib/native-files";+import { cn } from "@/lib/utils";import { Search01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";@@ -70,77 +72,73 @@ function sanitizeFilename(name: string): string {return name.replace(/[\\/:*?"<>|]/g, "_").slice(0, 80) || "export";}-function downloadBlob(content: string | Blob, filename: string, mimeType: string): void {- const blob = content instanceof Blob ? content : new Blob([content], { type: mimeType });- const url = URL.createObjectURL(blob);- const a = document.createElement("a");- a.href = url;- a.download = filename;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(url);+async function downloadBlob(+ content: string | Blob | Uint8Array,+ filename: string,+ mimeType: string,+): Promise<void> {+ return downloadFile(content, filename, mimeType);}function csvEscape(val: string): string {return `"${val.replace(/"/g, '""')}"`;}-function exportPromptJsonl(entry: PromptEntry): void {- downloadBlob(+function exportPromptJsonl(entry: PromptEntry): Promise<void> {+ return downloadBlob(JSON.stringify({ name: entry.name, text: entry.text }),`${sanitizeFilename(entry.name)}.jsonl`,"application/x-ndjson",);}-function exportPromptCsv(entry: PromptEntry): void {- downloadBlob(+function exportPromptCsv(entry: PromptEntry): Promise<void> {+ return downloadBlob(`name,text\n${csvEscape(entry.name)},${csvEscape(entry.text)}`,`${sanitizeFilename(entry.name)}.csv`,"text/csv",);}-function exportAllPromptsJsonl(entries: PromptEntry[]): void {+function exportAllPromptsJsonl(entries: PromptEntry[]): Promise<void> {const lines = entries.map((e) => JSON.stringify({ name: e.name, text: e.text })).join("\n");- downloadBlob(lines, "prompts.jsonl", "application/x-ndjson");+ return downloadBlob(lines, "prompts.jsonl", "application/x-ndjson");}-function exportAllPromptsCsv(entries: PromptEntry[]): void {+function exportAllPromptsCsv(entries: PromptEntry[]): Promise<void> {const rows = entries.map((e) => `${csvEscape(e.name)},${csvEscape(e.text)}`).join("\n");- downloadBlob(`name,text\n${rows}`, "prompts.csv", "text/csv");+ return downloadBlob(`name,text\n${rows}`, "prompts.csv", "text/csv");}-function exportListJsonl(entry: PromptListEntry): void {- downloadBlob(+function exportListJsonl(entry: PromptListEntry): Promise<void> {+ return downloadBlob(JSON.stringify({ name: entry.name, items: entry.items }),`${sanitizeFilename(entry.name)}.jsonl`,"application/x-ndjson",);}-function exportAllListsJsonl(entries: PromptListEntry[]): void {+function exportAllListsJsonl(entries: PromptListEntry[]): Promise<void> {const lines = entries.map((e) => JSON.stringify({ name: e.name, items: e.items })).join("\n");- downloadBlob(lines, "prompt-lists.jsonl", "application/x-ndjson");+ return downloadBlob(lines, "prompt-lists.jsonl", "application/x-ndjson");}-function exportListCsv(entry: PromptListEntry): void {+function exportListCsv(entry: PromptListEntry): Promise<void> {const rows = entry.items.map((text, i) => `${csvEscape(entry.name)},${i + 1},${csvEscape(text)}`).join("\n");- downloadBlob(+ return downloadBlob(`list_name,order,prompt_text\n${rows}`,`${sanitizeFilename(entry.name)}.csv`,"text/csv",);}-function exportAllListsCsv(entries: PromptListEntry[]): void {+function exportAllListsCsv(entries: PromptListEntry[]): Promise<void> {const rows = entries.flatMap((e) => e.items.map((text, i) => `${csvEscape(e.name)},${i + 1},${csvEscape(text)}`)).join("\n");- downloadBlob(`list_name,order,prompt_text\n${rows}`, "prompt-lists.csv", "text/csv");+ return downloadBlob(`list_name,order,prompt_text\n${rows}`, "prompt-lists.csv", "text/csv");}function contentBlocksToText(content: unknown): string {@@ -363,7 +361,7 @@ export async function exportConversationShareGPT(threadId: string): Promise<void}if (conversations.length === 0) { toast.info("No exportable content."); return; }- downloadBlob(+ await downloadBlob(JSON.stringify({ conversations }),"conversation-" + exportTs() + ".jsonl","application/x-ndjson",@@ -378,7 +376,7 @@ export async function exportConversationRawJsonl(threadId: string): Promise<voidconst oaiMsgs: OAIMessage[] = messages.flatMap((msg) => messageToOpenAI(msg));if (oaiMsgs.length === 0) { toast.info("No exportable content."); return; }- downloadBlob(+ await downloadBlob(JSON.stringify({ messages: oaiMsgs }),"conversation-" + exportTs() + ".jsonl","application/x-ndjson",@@ -397,7 +395,11 @@ export async function exportConversationCsv(threadId: string): Promise<void> {}if (rows.length <= 1) { toast.info("No exportable content."); return; }- downloadBlob(rows.join("\n"), "conversation-" + exportTs() + ".csv", "text/csv");+ await downloadBlob(+ rows.join("\n"),+ "conversation-" + exportTs() + ".csv",+ "text/csv",+ );}export type ConvExportFormat = "jsonl-raw" | "csv" | "sharegpt";@@ -479,7 +481,11 @@ export async function exportBulkConversationsMerged(? header + "\n" + parts.join("\n"): parts.join("\n");- downloadBlob(body, `${basename}.${exportExt(format)}`, exportMime(format));+ await downloadBlob(+ body,+ `${basename}.${exportExt(format)}`,+ exportMime(format),+ );}export async function exportBulkConversationsSeparate(@@ -504,11 +510,7 @@ export async function exportBulkConversationsSeparate(if (Object.keys(files).length === 0) { toast.info("No exportable content."); return; }const zipped = zipSync(files);- downloadBlob(- new Blob([zipped], { type: "application/zip" }),- `${basename}.zip`,- "application/zip",- );+ await downloadBlob(zipped, `${basename}.zip`, "application/zip");}// Scope-level bulk export shared by the sidebar Recents menu and@@ -536,8 +538,10 @@ export async function bulkExportConversationsByScope(} else {await exportBulkConversationsSeparate(ids, format, basename);}- } catch {- toast.error("Export failed.");+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Export failed.");+ }}}@@ -749,7 +753,7 @@ export async function exportFineTuneJsonl(return 0;}const suffix = format === "openai" ? "" : `-${format}`;- downloadBlob(+ await downloadBlob(lines.join("\n"),`chat-finetune${suffix}-${exportTs()}.jsonl`,"application/x-ndjson",@@ -992,21 +996,21 @@ export async function importConversationsFromFile(// ShareGPT training exports: prompt → one record (human turn + empty gpt slot);// list → one multi-turn record, each item a human turn.-function exportPromptTrainingJsonl(entry: PromptEntry): void {+function exportPromptTrainingJsonl(entry: PromptEntry): Promise<void> {const record = {conversations: [{ from: "human", value: entry.text },{ from: "gpt", value: "" },],};- downloadBlob(+ return downloadBlob(JSON.stringify(record),`${sanitizeFilename(entry.name)}-training.jsonl`,"application/x-ndjson",);}-function exportPromptsTrainingJsonl(entries: PromptEntry[]): void {+function exportPromptsTrainingJsonl(entries: PromptEntry[]): Promise<void> {const lines = entries.map((e) =>JSON.stringify({@@ -1017,22 +1021,22 @@ function exportPromptsTrainingJsonl(entries: PromptEntry[]): void {}),).join("\n");- downloadBlob(lines, "prompts-training.jsonl", "application/x-ndjson");+ return downloadBlob(lines, "prompts-training.jsonl", "application/x-ndjson");}-function exportListTrainingJsonl(entry: PromptListEntry): void {+function exportListTrainingJsonl(entry: PromptListEntry): Promise<void> {const conversations = entry.items.flatMap((text) => [{ from: "human", value: text },{ from: "gpt", value: "" },]);- downloadBlob(+ return downloadBlob(JSON.stringify({ conversations }),`${sanitizeFilename(entry.name)}-training.jsonl`,"application/x-ndjson",);}-function exportListsTrainingJsonl(entries: PromptListEntry[]): void {+function exportListsTrainingJsonl(entries: PromptListEntry[]): Promise<void> {const lines = entries.map((e) => {const conversations = e.items.flatMap((text) => [@@ -1042,7 +1046,7 @@ function exportListsTrainingJsonl(entries: PromptListEntry[]): void {return JSON.stringify({ conversations });}).join("\n");- downloadBlob(lines, "prompt-lists-training.jsonl", "application/x-ndjson");+ return downloadBlob(lines, "prompt-lists-training.jsonl", "application/x-ndjson");}// RFC 4180 CSV parser: handles quoted fields with embedded newlines/commas.@@ -1268,38 +1272,44 @@ function ExportModal({if (!csvAvailable) setFormat("jsonl");}, [csvAvailable]);- const handleExport = useCallback(() => {- if (ctx.kind === "prompt") {- if (scope === "training") exportPromptTrainingJsonl(ctx.entry);- else if (format === "csv") exportPromptCsv(ctx.entry);- else exportPromptJsonl(ctx.entry);- } else if (ctx.kind === "list") {- if (scope === "training") exportListTrainingJsonl(ctx.entry);- else if (format === "csv") exportListCsv(ctx.entry);- else exportListJsonl(ctx.entry);- } else {- const { tab, prompts, lists } = ctx;- if (scope === "training") {- if (tab === "prompts") {- if (prompts.length === 0) { toast.info("No prompts to export"); return; }- exportPromptsTrainingJsonl(prompts);- } else {- if (lists.length === 0) { toast.info("No prompt lists to export"); return; }- exportListsTrainingJsonl(lists);- }+ const handleExport = useCallback(async () => {+ try {+ if (ctx.kind === "prompt") {+ if (scope === "training") await exportPromptTrainingJsonl(ctx.entry);+ else if (format === "csv") await exportPromptCsv(ctx.entry);+ else await exportPromptJsonl(ctx.entry);+ } else if (ctx.kind === "list") {+ if (scope === "training") await exportListTrainingJsonl(ctx.entry);+ else if (format === "csv") await exportListCsv(ctx.entry);+ else await exportListJsonl(ctx.entry);} else {- if (tab === "prompts") {+ const { tab, prompts, lists } = ctx;+ if (scope === "training") {+ if (tab === "prompts") {+ if (prompts.length === 0) { toast.info("No prompts to export"); return; }+ await exportPromptsTrainingJsonl(prompts);+ } else {+ if (lists.length === 0) { toast.info("No prompt lists to export"); return; }+ await exportListsTrainingJsonl(lists);+ }+ } else if (tab === "prompts") {if (prompts.length === 0) { toast.info("No prompts to export"); return; }- if (format === "csv") exportAllPromptsCsv(prompts);- else exportAllPromptsJsonl(prompts);+ if (format === "csv") await exportAllPromptsCsv(prompts);+ else await exportAllPromptsJsonl(prompts);} else {if (lists.length === 0) { toast.info("No prompt lists to export"); return; }- if (format === "csv") exportAllListsCsv(lists);- else exportAllListsJsonl(lists);+ if (format === "csv") await exportAllListsCsv(lists);+ else await exportAllListsJsonl(lists);}}+ onClose();+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Could not save export.", {+ description: error instanceof Error ? error.message : String(error),+ });+ }}- onClose();}, [ctx, scope, format, onClose]);const singleLabel =diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 70dac70a238..a72d21aa6b3 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -36,6 +36,7 @@ import {} from "@/features/settings/stores/voice-settings-store";import { AUDIO_ACCEPT, MAX_AUDIO_SIZE, fileToBase64 } from "@/lib/audio-utils";import { isTauri } from "@/lib/api-base";+import { isDownloadCancelled } from "@/lib/native-files";import { isMultimodalResponse } from "./types/api";import { getImageInputUnavailableReason } from "./utils/image-input-support";import { useAui } from "@assistant-ui/react";@@ -1586,9 +1587,13 @@ export function SharedComposer({toast.error("No conversation to export yet.");return;}- Promise.all(exportThreadIds.map((id) => fn(id))).catch(() =>- toast.error("Export failed."),- );+ (async () => {+ for (const id of exportThreadIds) {+ await fn(id);+ }+ })().catch((error) => {+ if (!isDownloadCancelled(error)) toast.error("Export failed.");+ });}}>{label}diff --git a/studio/frontend/src/features/chat/thread-sidebar.tsx b/studio/frontend/src/features/chat/thread-sidebar.tsxindex 9e65fc57495..f85c74eb867 100644--- a/studio/frontend/src/features/chat/thread-sidebar.tsx+++ b/studio/frontend/src/features/chat/thread-sidebar.tsx@@ -42,6 +42,7 @@ import {PencilEdit02Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";+import { isDownloadCancelled } from "@/lib/native-files";import { toast } from "sonner";import { useChatRuntimeStore } from "./stores/chat-runtime-store";import type { ChatView } from "./types";@@ -133,9 +134,13 @@ export function ThreadSidebar({) {try {const ids = await getThreadIdsForItem(item);- await Promise.all(ids.map((id) => fn(id)));- } catch {- toast.error("Export failed.");+ for (const id of ids) {+ await fn(id);+ }+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Export failed.");+ }}}@@ -162,8 +167,10 @@ export function ThreadSidebar({} else {await exportBulkConversationsSeparate(ids, fmt, basename);}- } catch {- toast.error("Export failed.");+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Export failed.");+ }}}diff --git a/studio/frontend/src/features/chat/utils/export-chat-history.ts b/studio/frontend/src/features/chat/utils/export-chat-history.tsindex b4bc64d0537..6f641a9fa99 100644--- a/studio/frontend/src/features/chat/utils/export-chat-history.ts+++ b/studio/frontend/src/features/chat/utils/export-chat-history.ts@@ -1,9 +1,10 @@// 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 { downloadFile } from "@/lib/native-files";+import { filterArchivedChatExport } from "./archived-chat-export";import { buildStoredChatExport } from "./chat-history-storage";-import { triggerJsonDownload } from "./download-json";export const buildChatExport = buildStoredChatExport;@@ -14,7 +15,11 @@ function dateStamp(): string {export async function downloadChatExport(): Promise<void> {const data = await buildChatExport();- triggerJsonDownload(data, `unsloth-chats-${dateStamp()}.json`);+ await downloadFile(+ JSON.stringify(data, null, 2),+ `unsloth-chats-${dateStamp()}.json`,+ "application/json",+ );}// Full backup restricted to archived chats. Returns the archived thread count.@@ -29,6 +34,10 @@ export async function downloadArchivedChatExport(): Promise<number> {if (archivedCount === 0) {return 0;}- triggerJsonDownload(data, `unsloth-archived-chats-${dateStamp()}.json`);+ await downloadFile(+ JSON.stringify(data, null, 2),+ `unsloth-archived-chats-${dateStamp()}.json`,+ "application/json",+ );return archivedCount;}diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsxindex dc9e707ea04..e2b524f46ed 100644--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx@@ -39,6 +39,9 @@ import {useChatSidebarItems,} from "@/features/chat";import { useT } from "@/i18n";++import { isTauri } from "@/lib/api-base";+import { isDownloadCancelled, pickNativeChatImport } from "@/lib/native-files";import {ChevronDownStandardIcon,ChevronRightStandardIcon,@@ -147,6 +150,12 @@ export function DataTab() {setExporting(true);try {await downloadChatExport();+ } catch (error) {+ if (!isDownloadCancelled(error)) {+ toast.error("Could not export chats", {+ description: error instanceof Error ? error.message : String(error),+ });+ }} finally {setExporting(false);}@@ -164,9 +173,11 @@ export function DataTab() {: t("settings.data.exportedArchivedChatCount", { count: exported }),);} catch (error) {- toast.error(t("settings.data.failedToExportArchivedChats"), {- description: error instanceof Error ? error.message : undefined,- });+ if (!isDownloadCancelled(error)) {+ toast.error(t("settings.data.failedToExportArchivedChats"), {+ description: error instanceof Error ? error.message : undefined,+ });+ }} finally {setArchivedExporting(false);}@@ -191,6 +202,24 @@ export function DataTab() {}};+ const handleImportClick = async () => {+ if (!isTauri) {+ importInputRef.current?.click();+ return;+ }+ try {+ const selected = await pickNativeChatImport();+ if (!selected) {+ return;+ }+ await handleImport(new File([selected.content], selected.name));+ } catch (error) {+ toast.error(t("settings.chat.importFailed"), {+ description: error instanceof Error ? error.message : String(error),+ });+ }+ };+const handleArchiveAll = async () => {setArchiving(true);try {@@ -219,9 +248,11 @@ export function DataTab() {try {await exportFineTuneJsonl(fineTuneFormat);} catch (error) {- toast.error(t("settings.data.fineTuneExportFailed"), {- description: error instanceof Error ? error.message : undefined,- });+ if (!isDownloadCancelled(error)) {+ toast.error(t("settings.data.fineTuneExportFailed"), {+ description: error instanceof Error ? error.message : undefined,+ });+ }} finally {setFineTuneExporting(false);}@@ -632,7 +663,7 @@ export function DataTab() {<Buttonvariant="outline"size="sm"- onClick={() => importInputRef.current?.click()}+ onClick={() => void handleImportClick()}><HugeiconsIcon icon={Upload01Icon} className="size-3.5 mr-1.5" />{t("settings.chat.importChatsAction")}diff --git a/studio/frontend/src/lib/native-files.ts b/studio/frontend/src/lib/native-files.tsnew file mode 100644index 00000000000..48a6bd4ab77--- /dev/null+++ b/studio/frontend/src/lib/native-files.ts@@ -0,0 +1,86 @@+// 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 { isTauri } from "@/lib/api-base";++const NATIVE_FILE_NAME_HEADER = "x-unsloth-default-name";+export class DownloadCancelledError extends Error {+ constructor() {+ super("Save cancelled.");+ this.name = "DownloadCancelledError";+ }+}++export function isDownloadCancelled(error: unknown): boolean {+ return error instanceof DownloadCancelledError;+}++function encodeNativeFilename(filename: string): string {+ const bytes = new TextEncoder().encode(filename);+ let binary = "";+ for (const byte of bytes) {+ binary += String.fromCharCode(byte);+ }+ return btoa(binary);+}++export interface NativeChatImport {+ name: string;+ content: string;+}++function browserDownload(blob: Blob, filename: string): void {+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = filename;+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ URL.revokeObjectURL(url);+}++/** Save through a native chooser in Tauri and retain normal downloads on web. */+export async function downloadFile(+ content: string | Blob | Uint8Array,+ filename: string,+ mimeType = "application/octet-stream",+): Promise<void> {+ if (isTauri) {+ const { invoke } = await import("@tauri-apps/api/core");+ const bytes =+ typeof content === "string"+ ? new TextEncoder().encode(content)+ : content instanceof Blob+ ? new Uint8Array(await content.arrayBuffer())+ : content;+ const savedPath = await invoke<string | null>("save_native_file", bytes, {+ headers: {+ [NATIVE_FILE_NAME_HEADER]: encodeNativeFilename(filename),+ },+ });+ if (savedPath === null) {+ throw new DownloadCancelledError();+ }+ return;+ }++ const browserContent =+ content instanceof Uint8Array ? Uint8Array.from(content).buffer : content;+ const blob =+ browserContent instanceof Blob+ ? browserContent+ : new Blob([browserContent], { type: mimeType });++ browserDownload(blob, filename);+ return;+}++/** Open the bounded native chat-import picker. Cancellation returns null. */+export async function pickNativeChatImport(): Promise<NativeChatImport | null> {+ if (!isTauri) {+ return null;+ }+ const { invoke } = await import("@tauri-apps/api/core");+ return invoke<NativeChatImport | null>("pick_native_chat_import");+}diff --git a/studio/src-tauri/Cargo.lock b/studio/src-tauri/Cargo.lockindex 183cfc1cc83..604bb015258 100644--- a/studio/src-tauri/Cargo.lock+++ b/studio/src-tauri/Cargo.lock@@ -5592,6 +5592,7 @@ dependencies = ["tauri-plugin-single-instance","tauri-plugin-updater","tauri-plugin-window-state",+ "tempfile","tokio","windows 0.62.2","windows-sys 0.61.2",diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.tomlindex 438558fe77f..826509ce9a8 100644--- a/studio/src-tauri/Cargo.toml+++ b/studio/src-tauri/Cargo.toml@@ -29,6 +29,7 @@ tauri-plugin-clipboard-manager = "2"tauri-plugin-dialog = "2"rand = "0.10.0"tauri-plugin-notification = "2.3.3"+tempfile = "3"tauri-plugin-window-state = "2"[target.'cfg(unix)'.dependencies]diff --git a/studio/src-tauri/Entitlements.plist b/studio/src-tauri/Entitlements.plistindex 10e6df34270..71b1d2c0f4c 100644--- a/studio/src-tauri/Entitlements.plist+++ b/studio/src-tauri/Entitlements.plist@@ -8,6 +8,9 @@<!-- Network access for backend health checks and HuggingFace API --><key>com.apple.security.network.client</key><true/>+ <!-- Permit microphone capture for local dictation -->+ <key>com.apple.security.device.audio-input</key>+ <true/><!-- Allow loading Python/venv libraries not signed by us --><key>com.apple.security.cs.disable-library-validation</key><true/>diff --git a/studio/src-tauri/Info.plist b/studio/src-tauri/Info.plistnew file mode 100644index 00000000000..e7a280647be--- /dev/null+++ b/studio/src-tauri/Info.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>NSMicrophoneUsageDescription</key>+ <string>Unsloth Studio uses the microphone you select for local voice dictation.</string>+</dict>+</plist>diff --git a/studio/src-tauri/src/app_layout.rs b/studio/src-tauri/src/app_layout.rsnew file mode 100644index 00000000000..9b9277b48dc--- /dev/null+++ b/studio/src-tauri/src/app_layout.rs@@ -0,0 +1,274 @@+use std::fs;+use std::path::{Path, PathBuf};+use tauri::{Manager, WebviewWindow};++use tauri_plugin_window_state::AppHandleExt;++const APP_LAYOUT_MARKER_FILE: &str = "app-layout-initialized-v1";+const INITIALIZED_MARKER: &[u8] = b"initialized\n";+const RESET_MARKER: &[u8] = b"reset\n";++const SETUP_WINDOW_WIDTH: f64 = 760.0;+const SETUP_WINDOW_HEIGHT: f64 = 560.0;+const MIN_REASONABLE_WINDOW_WIDTH: u64 = 320;+const MIN_REASONABLE_WINDOW_HEIGHT: u64 = 240;++const SETUP_SIZE_TOLERANCE_PX: f64 = 2.0;++#[derive(serde::Deserialize)]+struct PersistedWindowState {+ width: u32,+ height: u32,+ #[serde(rename = "x")]+ _x: i32,+ #[serde(rename = "y")]+ _y: i32,+ #[serde(rename = "prev_x")]+ _prev_x: i32,+ #[serde(rename = "prev_y")]+ _prev_y: i32,+ #[serde(rename = "maximized")]+ _maximized: bool,+ #[serde(rename = "visible")]+ _visible: bool,+ #[serde(rename = "decorated")]+ _decorated: bool,+ #[serde(rename = "fullscreen")]+ _fullscreen: bool,+}++fn marker_path(config_dir: &Path) -> PathBuf {+ config_dir.join(APP_LAYOUT_MARKER_FILE)+}++fn marker_matches(config_dir: &Path, expected: &[u8]) -> bool {+ fs::read(marker_path(config_dir))+ .map(|contents| contents == expected)+ .unwrap_or(false)+}++fn is_initialized(config_dir: &Path) -> bool {+ marker_matches(config_dir, INITIALIZED_MARKER)+}++fn is_reset_pending(config_dir: &Path) -> bool {+ marker_matches(config_dir, RESET_MARKER)+}++fn write_marker(config_dir: &Path, contents: &[u8]) -> Result<(), String> {+ fs::create_dir_all(config_dir).map_err(|error| {+ format!(+ "Failed to create app configuration directory {}: {error}",+ config_dir.display()+ )+ })?;+ let path = marker_path(config_dir);+ fs::write(&path, contents).map_err(|error| {+ format!(+ "Failed to write app layout marker {}: {error}",+ path.display()+ )+ })+}++fn reset_initialized(config_dir: &Path) -> Result<(), String> {+ write_marker(config_dir, RESET_MARKER)+}++fn is_setup_window_size(width: u64, height: u64) -> bool {+ // Window-state persists physical dimensions but not their source scale.+ let width_scale = width as f64 / SETUP_WINDOW_WIDTH;+ let height_scale = height as f64 / SETUP_WINDOW_HEIGHT;+ let scale_tolerance = SETUP_SIZE_TOLERANCE_PX / SETUP_WINDOW_WIDTH+ + SETUP_SIZE_TOLERANCE_PX / SETUP_WINDOW_HEIGHT;+ (width_scale - height_scale).abs() <= scale_tolerance+}++fn saved_main_window_size(config_dir: &Path, state_file_name: &str) -> Option<(u64, u64)> {+ let contents = fs::read(config_dir.join(state_file_name)).ok()?;+ let states = serde_json::from_slice::<std::collections::HashMap<String, PersistedWindowState>>(+ &contents,+ )+ .ok()?;+ let main = states.get("main")?;+ let width = u64::from(main.width);+ let height = u64::from(main.height);+ if width < MIN_REASONABLE_WINDOW_WIDTH || height < MIN_REASONABLE_WINDOW_HEIGHT {+ return None;+ }+ Some((width, height))+}++fn should_restore_saved_layout(config_dir: &Path, state_file_name: &str) -> bool {+ if is_reset_pending(config_dir) {+ return false;+ }+ let Some((width, height)) = saved_main_window_size(config_dir, state_file_name) else {+ return false;+ };+ is_initialized(config_dir) || !is_setup_window_size(width, height)+}++fn mark_initialized(config_dir: &Path) -> Result<(), String> {+ write_marker(config_dir, INITIALIZED_MARKER)+}++fn app_config_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {+ app.path()+ .app_config_dir()+ .map_err(|error| format!("Could not determine app configuration directory: {error}"))+}++/// Returns whether a full-app layout has previously completed. Legacy state is+/// migrated unless it matches the fixed setup-window size at any display scale.+#[tauri::command]+pub fn has_initialized_app_window_layout(+ window: WebviewWindow,+ app: tauri::AppHandle,+) -> Result<bool, String> {+ crate::native_intents::ensure_main_window(&window)?;+ let config_dir = app_config_dir(&app)?;+ Ok(should_restore_saved_layout(&config_dir, &app.filename()))+}++/// Persist only after the caller has successfully sized/centered or restored,+/// shown, constrained, and minimum-sized the full application window.+#[tauri::command]+pub fn mark_app_window_layout_initialized(+ window: WebviewWindow,+ app: tauri::AppHandle,+) -> Result<(), String> {+ crate::native_intents::ensure_main_window(&window)?;+ mark_initialized(&app_config_dir(&app)?)+}++/// Force the next full-app transition to use a monitor-safe layout. Setup can+/// overwrite the plugin's saved full-app dimensions before the process exits.+#[tauri::command]+pub fn reset_app_window_layout_initialized(+ window: WebviewWindow,+ app: tauri::AppHandle,+) -> Result<(), String> {+ crate::native_intents::ensure_main_window(&window)?;+ reset_initialized(&app_config_dir(&app)?)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::{SystemTime, UNIX_EPOCH};++ fn temp_dir(name: &str) -> PathBuf {+ let nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ std::env::temp_dir().join(format!(+ "unsloth-app-layout-{name}-{}-{nanos}",+ std::process::id()+ ))+ }++ fn window_state(width: u32, height: u32, maximized: bool) -> String {+ serde_json::json!({+ "main": {+ "width": width,+ "height": height,+ "x": 0,+ "y": 0,+ "prev_x": 0,+ "prev_y": 0,+ "maximized": maximized,+ "visible": true,+ "decorated": true,+ "fullscreen": false+ }+ })+ .to_string()+ }++ #[test]+ fn marker_is_absent_until_full_layout_is_marked() {+ let dir = temp_dir("transition");+ assert!(!is_initialized(&dir));+ mark_initialized(&dir).unwrap();+ assert!(is_initialized(&dir));+ assert_eq!(fs::read(marker_path(&dir)).unwrap(), b"initialized\n");+ let _ = fs::remove_dir_all(dir);+ }++ #[test]+ fn marker_write_and_reset_are_idempotent() {+ let dir = temp_dir("idempotent");+ mark_initialized(&dir).unwrap();+ mark_initialized(&dir).unwrap();+ assert!(is_initialized(&dir));+ assert!(!is_reset_pending(&dir));++ reset_initialized(&dir).unwrap();+ reset_initialized(&dir).unwrap();+ assert!(!is_initialized(&dir));+ assert!(is_reset_pending(&dir));++ mark_initialized(&dir).unwrap();+ assert!(is_initialized(&dir));+ assert!(!is_reset_pending(&dir));+ let _ = fs::remove_dir_all(dir);+ }++ #[test]+ fn legacy_full_app_state_is_migrated_but_setup_state_at_any_scale_is_not() {+ let dir = temp_dir("legacy-plugin-state");+ fs::create_dir_all(&dir).unwrap();+ let state_file = ".window-state.json";+ let state_path = dir.join(state_file);++ fs::write(&state_path, window_state(1200, 800, false)).unwrap();+ assert!(should_restore_saved_layout(&dir, state_file));++ fs::write(&state_path, window_state(760, 560, false)).unwrap();+ assert!(!should_restore_saved_layout(&dir, state_file));++ fs::write(&state_path, window_state(950, 700, false)).unwrap();+ assert!(!should_restore_saved_layout(&dir, state_file));++ fs::write(&state_path, window_state(1520, 1120, false)).unwrap();+ assert!(!should_restore_saved_layout(&dir, state_file));++ fs::write(&state_path, window_state(1520, 1120, true)).unwrap();+ assert!(!should_restore_saved_layout(&dir, state_file));+ let _ = fs::remove_dir_all(dir);+ }++ #[test]+ fn explicit_reset_blocks_legacy_migration_until_app_layout_completes() {+ let dir = temp_dir("reset-migration");+ fs::create_dir_all(&dir).unwrap();+ let state_file = ".window-state.json";+ fs::write(dir.join(state_file), window_state(1200, 800, false)).unwrap();++ mark_initialized(&dir).unwrap();+ assert!(should_restore_saved_layout(&dir, state_file));+ reset_initialized(&dir).unwrap();+ assert!(!should_restore_saved_layout(&dir, state_file));+ mark_initialized(&dir).unwrap();+ assert!(should_restore_saved_layout(&dir, state_file));+ let _ = fs::remove_dir_all(dir);+ }++ #[test]+ fn corrupt_plugin_state_does_not_restore_even_with_initialized_marker() {+ let dir = temp_dir("plugin-state");+ fs::create_dir_all(&dir).unwrap();+ let state_file = ".window-state.json";+ fs::write(+ dir.join(state_file),+ r#"{"main":{"width":1200,"height":800}}"#,+ )+ .unwrap();+ mark_initialized(&dir).unwrap();+ assert!(is_initialized(&dir));+ assert!(!should_restore_saved_layout(&dir, state_file));+ let _ = fs::remove_dir_all(dir);+ }+}diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rsindex 5d41cb92175..72ea9d69854 100644--- a/studio/src-tauri/src/commands.rs+++ b/studio/src-tauri/src/commands.rs@@ -339,11 +339,21 @@ pub fn get_server_logs(state: tauri::State<'_, BackendState>) -> Vec<String> {/// Open an existing directory in the system file manager. Validates the path/// up front so callers get a clean error instead of a raw OS failure.-fn open_existing_dir(dir: &std::path::Path) -> Result<(), String> {+fn open_existing_dir_with<E>(+ dir: &std::path::Path,+ opener: impl FnOnce(&std::path::Path) -> Result<(), E>,+) -> Result<(), String>+where+ E: std::fmt::Display,+{if !dir.is_dir() {return Err(format!("Directory does not exist: {}", dir.display()));}- open::that(dir).map_err(|e| format!("Failed to open directory: {}", e))+ opener(dir).map_err(|error| format!("Failed to open directory: {error}"))+}++fn open_existing_dir(dir: &std::path::Path) -> Result<(), String> {+ open_existing_dir_with(dir, |path| open::that_detached(path))}/// Open the Unsloth Studio directory in the system file manager.@@ -641,7 +651,8 @@ pub async fn start_managed_repair(#[cfg(test)]mod tests {- use std::time::Duration;+ use std::fs;+ use std::time::{Duration, SystemTime, UNIX_EPOCH};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpListener;@@ -699,6 +710,40 @@ mod tests {port}+ #[test]+ fn existing_directory_helper_invokes_opener_and_surfaces_errors() {+ let nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let dir =+ std::env::temp_dir().join(format!("unsloth-open-dir-{}-{nanos}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ let mut opened = false;+ super::open_existing_dir_with(&dir, |path| {+ opened = true;+ assert_eq!(path, dir);+ Ok::<_, &str>(())+ })+ .unwrap();+ assert!(opened);++ let error = super::open_existing_dir_with(&dir, |_| Err("opener failed")).unwrap_err();+ assert!(error.contains("opener failed"));+ let _ = fs::remove_dir_all(dir);+ }++ #[test]+ fn existing_directory_helper_rejects_missing_path_without_opening() {+ let missing = std::env::temp_dir().join("unsloth-definitely-missing-open-dir");+ let error = super::open_existing_dir_with(&missing, |_| {+ panic!("opener must not run for an invalid directory");+ #[allow(unreachable_code)]+ Ok::<_, &str>(())+ })+ .unwrap_err();+ assert!(error.contains("Directory does not exist"));+ }#[test]fn repair_elevation_is_not_a_terminal_repair_failure() {assert!(!super::should_emit_repair_failed("NEEDS_ELEVATION"));diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 4724317601f..cfac90ae73f 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -1,5 +1,6 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]+mod app_layout;mod commands;mod desktop_auth;mod desktop_backend_owner;@@ -7,6 +8,7 @@ mod desktop_update_policy;mod diagnostics;mod install;mod native_backend_lease;+mod native_file_dialogs;mod native_intents;mod native_path_policy;mod preflight;@@ -195,6 +197,9 @@ fn main() {.manage(process::new_shutdown_flag()).manage(update::new_update_state()).invoke_handler(tauri::generate_handler![+ app_layout::has_initialized_app_window_layout,+ app_layout::mark_app_window_layout_initialized,+ app_layout::reset_app_window_layout_initialized,commands::check_install_status,commands::desktop_preflight,commands::start_install,@@ -213,6 +218,8 @@ fn main() {desktop_update_policy::check_desktop_manual_update,desktop_update_policy::desktop_update_policy,diagnostics::collect_support_diagnostics,+ native_file_dialogs::save_native_file,+ native_file_dialogs::pick_native_chat_import,native_intents::drain_native_intents,native_intents::register_native_model_path,native_intents::pick_native_model,diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rsnew file mode 100644index 00000000000..d795eb020c1--- /dev/null+++ b/studio/src-tauri/src/native_file_dialogs.rs@@ -0,0 +1,320 @@+use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};++use serde::Serialize;+use std::fs::{self, File};+use std::io::{Read, Write};+use std::path::{Path, PathBuf};+use tauri::{AppHandle, WebviewWindow};+use tauri_plugin_dialog::DialogExt;++const MAX_CHAT_IMPORT_BYTES: u64 = 64 * 1024 * 1024;+const NATIVE_FILE_NAME_HEADER: &str = "x-unsloth-default-name";+const CHAT_IMPORT_EXTENSIONS: &[&str] = &["jsonl", "ndjson", "csv"];++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeImportedFile {+ name: String,+ content: String,+}++fn default_file_name(suggested_name: &str) -> String {+ Path::new(suggested_name)+ .file_name()+ .and_then(|name| name.to_str())+ .filter(|name| !name.is_empty() && *name != "." && *name != "..")+ .unwrap_or("unsloth-export.json")+ .to_string()+}+fn decode_default_file_name(encoded_name: &str) -> Result<String, String> {+ let bytes = BASE64+ .decode(encoded_name)+ .map_err(|_| "Invalid native export filename.".to_string())?;+ let name =+ String::from_utf8(bytes).map_err(|_| "Invalid native export filename.".to_string())?;+ Ok(default_file_name(&name))+}++fn save_filter(file_name: &str) -> (&'static str, Vec<&'static str>) {+ match Path::new(file_name)+ .extension()+ .and_then(|extension| extension.to_str())+ .map(str::to_ascii_lowercase)+ .as_deref()+ {+ Some("json") => ("JSON", vec!["json"]),+ Some("jsonl") | Some("ndjson") => ("JSON Lines", vec!["jsonl", "ndjson"]),+ Some("csv") => ("CSV", vec!["csv"]),+ Some("md") | Some("markdown") => ("Markdown", vec!["md", "markdown"]),+ Some("zip") => ("ZIP archive", vec!["zip"]),+ _ => (+ "Export files",+ vec!["json", "jsonl", "ndjson", "csv", "md", "markdown", "zip"],+ ),+ }+}++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())+}++fn save_selected_file(+ selected_path: Option<PathBuf>,+ content: &[u8],+) -> Result<Option<String>, String> {+ let Some(path) = selected_path else {+ return Ok(None);+ };+ let parent = path+ .parent()+ .filter(|parent| !parent.as_os_str().is_empty())+ .unwrap_or_else(|| Path::new("."));+ let mut builder = tempfile::Builder::new();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let permissions = fs::metadata(&path)+ .map(|metadata| metadata.permissions())+ .unwrap_or_else(|_| fs::Permissions::from_mode(0o666));+ builder.permissions(permissions);+ }+ let mut temporary = builder+ .prefix(".unsloth-export-")+ .tempfile_in(parent)+ .map_err(|error| format!("Failed to prepare {}: {error}", path.display()))?;+ temporary+ .write_all(content)+ .and_then(|()| temporary.as_file().sync_all())+ .map_err(|error| format!("Failed to save {}: {error}", path.display()))?;+ temporary+ .persist(&path)+ .map_err(|error| format!("Failed to save {}: {}", path.display(), error.error))?;+ let file_name = path+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or("export")+ .to_string();+ Ok(Some(file_name))+}++fn read_selected_import(+ selected_path: Option<PathBuf>,+) -> Result<Option<NativeImportedFile>, String> {+ let Some(path) = selected_path else {+ return Ok(None);+ };+ let extension = path+ .extension()+ .and_then(|extension| extension.to_str())+ .map(str::to_ascii_lowercase)+ .ok_or_else(|| "Chat import must be a .jsonl, .ndjson, or .csv file.".to_string())?;+ if !CHAT_IMPORT_EXTENSIONS.contains(&extension.as_str()) {+ return Err("Chat import must be a .jsonl, .ndjson, or .csv file.".to_string());+ }++ let metadata = fs::metadata(&path)+ .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?;+ if !metadata.is_file() {+ return Err(format!("Selected import is not a file: {}", path.display()));+ }+ if metadata.len() > MAX_CHAT_IMPORT_BYTES {+ return Err(format!(+ "Chat import is too large (maximum {} MiB).",+ MAX_CHAT_IMPORT_BYTES / 1024 / 1024+ ));+ }++ // Limit the read too, so a file that grows after metadata inspection cannot+ // make the command allocate without bound.+ let file =+ File::open(&path).map_err(|error| format!("Failed to open {}: {error}", path.display()))?;+ let mut bytes = Vec::with_capacity(metadata.len() as usize);+ file.take(MAX_CHAT_IMPORT_BYTES + 1)+ .read_to_end(&mut bytes)+ .map_err(|error| format!("Failed to read {}: {error}", path.display()))?;+ if bytes.len() as u64 > MAX_CHAT_IMPORT_BYTES {+ return Err(format!(+ "Chat import is too large (maximum {} MiB).",+ MAX_CHAT_IMPORT_BYTES / 1024 / 1024+ ));+ }+ let content = String::from_utf8(bytes)+ .map_err(|_| format!("Chat import is not valid UTF-8: {}", path.display()))?;+ let name = path+ .file_name()+ .and_then(|name| name.to_str())+ .map(str::to_string)+ .unwrap_or_else(|| format!("chat-import.{extension}"));+ Ok(Some(NativeImportedFile { name, content }))+}++#[tauri::command]+pub async fn save_native_file(+ window: WebviewWindow,+ app: AppHandle,+ request: tauri::ipc::Request<'_>,+) -> Result<Option<String>, String> {+ crate::native_intents::ensure_main_window(&window)?;+ let encoded_name = request+ .headers()+ .get(NATIVE_FILE_NAME_HEADER)+ .ok_or_else(|| "Native export filename is missing.".to_string())?+ .to_str()+ .map_err(|_| "Invalid native export filename.".to_string())?;+ let file_name = decode_default_file_name(encoded_name)?;+ let content = match request.body() {+ tauri::ipc::InvokeBody::Raw(content) => content,+ _ => return Err("Native export content must be binary.".to_string()),+ };+ let (filter_name, extensions) = save_filter(&file_name);+ let (tx, rx) = tokio::sync::oneshot::channel();+ app.dialog()+ .file()+ .set_title("Save Unsloth export")+ .set_file_name(file_name)+ .add_filter(filter_name, &extensions)+ .save_file(move |path| {+ let _ = tx.send(path);+ });+ let selected_path = rx+ .await+ .map_err(|_| "Save dialog closed unexpectedly.".to_string())?+ .map(local_dialog_path)+ .transpose()?;+ save_selected_file(selected_path, content)+}++#[tauri::command]+pub async fn pick_native_chat_import(+ window: WebviewWindow,+ app: AppHandle,+) -> Result<Option<NativeImportedFile>, String> {+ crate::native_intents::ensure_main_window(&window)?;+ let (tx, rx) = tokio::sync::oneshot::channel();+ app.dialog()+ .file()+ .set_title("Import chats")+ .add_filter("Chat exports", CHAT_IMPORT_EXTENSIONS)+ .pick_file(move |path| {+ let _ = tx.send(path);+ });+ let selected_path = rx+ .await+ .map_err(|_| "Import dialog closed unexpectedly.".to_string())?+ .map(local_dialog_path)+ .transpose()?;+ read_selected_import(selected_path)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::{SystemTime, UNIX_EPOCH};++ fn temp_path(name: &str) -> PathBuf {+ let nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ std::env::temp_dir().join(format!(+ "unsloth-native-files-{name}-{}-{nanos}",+ std::process::id()+ ))+ }++ #[test]+ fn cancellation_is_quiet_for_save_and_import() {+ assert!(save_selected_file(None, b"x").unwrap().is_none());+ assert!(read_selected_import(None).unwrap().is_none());+ }++ #[test]+ fn writes_text_and_binary_exactly() {+ // Overwriting must stage the new content before replacing the destination.+ let text_path = temp_path("text").with_extension("json");+ let binary_path = temp_path("binary").with_extension("zip");++ fs::write(&text_path, b"previous export").unwrap();+ save_selected_file(Some(text_path.clone()), b"{\"ok\":true}").unwrap();+ save_selected_file(Some(binary_path.clone()), &[0, 1, 2, 255]).unwrap();+ assert_eq!(fs::read(&text_path).unwrap(), b"{\"ok\":true}");+ assert_eq!(fs::read(&binary_path).unwrap(), [0, 1, 2, 255]);+ let _ = fs::remove_file(text_path);+ let _ = fs::remove_file(binary_path);+ }++ #[test]+ fn markdown_exports_use_a_markdown_save_filter() {+ assert_eq!(+ save_filter("message.md"),+ ("Markdown", vec!["md", "markdown"])+ );+ }++ #[test]+ fn reads_supported_import_and_rejects_other_extensions() {+ let jsonl_path = temp_path("allowed").with_extension("JSONL");+ fs::write(&jsonl_path, "{\"messages\":[]}").unwrap();+ let imported = read_selected_import(Some(jsonl_path.clone()))+ .unwrap()+ .unwrap();+ assert_eq!(imported.content, "{\"messages\":[]}");++ let json_path = temp_path("unsupported").with_extension("json");+ fs::write(&json_path, "{}").unwrap();+ assert!(read_selected_import(Some(json_path.clone())).is_err());+ let txt_path = temp_path("denied").with_extension("txt");+ fs::write(&txt_path, "no").unwrap();+ assert!(read_selected_import(Some(txt_path.clone()))+ .unwrap_err()+ .contains(".json"));+ let _ = fs::remove_file(jsonl_path);+ let _ = fs::remove_file(json_path);+ let _ = fs::remove_file(txt_path);+ }++ #[test]+ fn read_limit_and_utf8_errors_are_concrete() {+ let oversized = temp_path("oversized").with_extension("csv");+ let file = File::create(&oversized).unwrap();+ file.set_len(MAX_CHAT_IMPORT_BYTES + 1).unwrap();+ assert!(read_selected_import(Some(oversized.clone()))+ .unwrap_err()+ .contains("too large"));++ let invalid = temp_path("invalid-utf8").with_extension("jsonl");+ fs::write(&invalid, [0xff]).unwrap();+ assert!(read_selected_import(Some(invalid.clone()))+ .unwrap_err()+ .contains("UTF-8"));+ let _ = fs::remove_file(oversized);+ let _ = fs::remove_file(invalid);+ }++ #[cfg(unix)]+ #[test]+ fn non_utf8_import_name_preserves_csv_extension() {+ use std::ffi::OsString;+ use std::os::unix::ffi::OsStringExt;++ let path = std::env::temp_dir().join(OsString::from_vec(vec![+ b'u', b'n', b's', b'l', b'o', b't', b'h', 0xff, b'.', b'c', b's', b'v',+ ]));+ fs::write(&path, "role,content\nuser,hello\n").unwrap();+ let imported = read_selected_import(Some(path.clone())).unwrap().unwrap();+ assert_eq!(imported.name, "chat-import.csv");+ let _ = fs::remove_file(path);+ }++ #[test]+ fn strips_directories_from_suggested_default_name() {+ assert_eq!(default_file_name("../../chat.jsonl"), "chat.jsonl");+ assert_eq!(default_file_name(""), "unsloth-export.json");++ assert_eq!(+ decode_default_file_name("Y2hhdC5qc29ubA==").unwrap(),+ "chat.jsonl"+ );+ }+}diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rsindex b82e516e7a2..26d4cdb61ae 100644--- a/studio/src-tauri/src/native_path_policy.rs+++ b/studio/src-tauri/src/native_path_policy.rs@@ -130,8 +130,8 @@ fn classify_existing_path(path: &Path) -> Result<ClassifiedPath, String> {.canonicalize().map_err(|e| format!("Path could not be resolved: {e}"))?;reject_network_or_device_path(&canonical_path)?;- let canonical_symlink_metadata = fs::symlink_metadata(&canonical_path)- .map_err(|e| format!("Path is not available: {e}"))?;+ let canonical_symlink_metadata =+ fs::symlink_metadata(&canonical_path).map_err(|e| format!("Path is not available: {e}"))?;if canonical_symlink_metadata.file_type().is_symlink() {return Err("Symlink paths are not supported for native intake.".to_string());}diff --git a/studio/src-tauri/tauri.macos.conf.json b/studio/src-tauri/tauri.macos.conf.jsonindex 202c9fb505d..b1517a62342 100644--- a/studio/src-tauri/tauri.macos.conf.json+++ b/studio/src-tauri/tauri.macos.conf.json@@ -2,6 +2,7 @@"bundle": {"macOS": {"entitlements": "./Entitlements.plist",+ "infoPlist": "./Info.plist","dmg": {"appPosition": { "x": 180, "y": 220 },"applicationFolderPosition": { "x": 480, "y": 220 }diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pynew file mode 100644index 00000000000..868895b8f08--- /dev/null+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -0,0 +1,131 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Static contracts for focused packaged-desktop reliability behavior."""++from pathlib import Path+++REPO = Path(__file__).resolve().parents[2]+FRONTEND = REPO / "studio/frontend/src"+NATIVE_FILES = FRONTEND / "lib/native-files.ts"+CHAT_EXPORT = FRONTEND / "features/chat/utils/export-chat-history.ts"+DATA_TAB = FRONTEND / "features/settings/tabs/data-tab.tsx"+PROMPT_STORAGE = FRONTEND / "features/chat/prompt-storage/prompt-storage-dialog.tsx"++APP_SIDEBAR = FRONTEND / "components/app-sidebar.tsx"+THREAD = FRONTEND / "components/assistant-ui/thread.tsx"+THREAD_SIDEBAR = FRONTEND / "features/chat/thread-sidebar.tsx"+SHARED_COMPOSER = FRONTEND / "features/chat/shared-composer.tsx"+TITLEBAR = FRONTEND / "components/tauri/window-titlebar.tsx"+NATIVE_DIALOGS = REPO / "studio/src-tauri/src/native_file_dialogs.rs"+++APP_PROVIDER = FRONTEND / "app/provider.tsx"+++def test_file_actions_route_through_native_commands_only_in_tauri():+ helper = NATIVE_FILES.read_text(encoding = "utf-8")+ history = CHAT_EXPORT.read_text(encoding = "utf-8")+ data_tab = DATA_TAB.read_text(encoding = "utf-8")+ prompt_storage = PROMPT_STORAGE.read_text(encoding = "utf-8")++ projects = (FRONTEND / "features/chat/projects-page.tsx").read_text(encoding = "utf-8")++ assert 'invoke<string | null>("save_native_file", bytes, {' in helper+ assert '"x-unsloth-default-name"' in helper+ assert "Array.from(new Uint8Array" not in helper+ assert 'invoke<NativeChatImport | null>("pick_native_chat_import")' in helper+ assert "if (isTauri)" in helper+ assert 'document.createElement("a")' in helper+ assert "DownloadCancelledError" in helper+ assert "throw new DownloadCancelledError()" in helper+ assert "return savedPath !== null" not in helper++ assert helper.index("if (isTauri)") < helper.index(" const blob =")+ assert "downloadFile(" in history+ assert "downloadFile(" in prompt_storage+ assert "pickNativeChatImport" in data_tab+ assert "if (!isTauri)" in data_tab++ assert "pickNativeChatImport" in projects+ assert "if (!isTauri)" in projects+ # Browser builds retain the existing hidden-input route.+ assert 'type="file"' in data_tab+ assert 'accept=".jsonl,.ndjson,.csv"' in data_tab++ native_dialogs = NATIVE_DIALOGS.read_text(encoding = "utf-8")+ assert 'CHAT_IMPORT_EXTENSIONS: &[&str] = &["jsonl", "ndjson", "csv"]' in native_dialogs+ assert "InvokeBody::Raw" in native_dialogs++ assert ".tempfile_in(parent)" in native_dialogs+ assert ".persist(&path)" in native_dialogs+ assert "fs::write(&path, content)" not in native_dialogs+++def test_chat_exports_await_native_saves_and_markdown_uses_shared_helper():+ app_sidebar = APP_SIDEBAR.read_text(encoding = "utf-8")+ prompt_storage = PROMPT_STORAGE.read_text(encoding = "utf-8")+ thread = THREAD.read_text(encoding = "utf-8")+ thread_sidebar = THREAD_SIDEBAR.read_text(encoding = "utf-8")+ shared_composer = SHARED_COMPOSER.read_text(encoding = "utf-8")++ data_tab = DATA_TAB.read_text(encoding = "utf-8")+ projects = (FRONTEND / "features/chat/projects-page.tsx").read_text(encoding = "utf-8")+ assert "async function downloadBlob(" in prompt_storage+ download_blob = prompt_storage.split("async function downloadBlob(", 1)[1].split("\n}\n", 1)[0]+ assert "return downloadFile(" in download_blob+ assert "catch (error)" not in download_blob+ assert "isDownloadCancelled(error)" in prompt_storage++ for source in (app_sidebar, thread, thread_sidebar, shared_composer, data_tab, projects):+ assert "isDownloadCancelled(error)" in source+ assert "const handleExport = useCallback(async () =>" in prompt_storage+ assert prompt_storage.count("await export") >= 12+ assert "await Promise.all(" not in app_sidebar+ assert "for (const id of ids)" in app_sidebar+ assert prompt_storage.count("await downloadBlob(") >= 5++ assert "await downloadBlob(zipped," in prompt_storage+ assert "new Blob([zipped]" not in prompt_storage+ assert "Promise.all(ids.map((id) => fn(id)))" not in thread_sidebar+ assert "for (const id of ids)" in thread_sidebar+ assert "Promise.all(exportThreadIds.map((id) => fn(id)))" not in shared_composer+ assert "for (const id of exportThreadIds)" in shared_composer+ assert "onExport={exportMessageMarkdown}" in thread+ assert '"text/markdown"' in thread+ assert "downloadFile(" in thread+++def test_full_app_layout_uses_its_own_initialized_marker():+ source = APP_PROVIDER.read_text(encoding = "utf-8")++ assert 'invoke<boolean>("has_initialized_app_window_layout")' in source+ setup_layout = source.split("async function showSetupWindow", 1)[1].split(+ "async function enforceMinimumWindowSize", 1+ )[0]+ reset_call = 'invoke("reset_app_window_layout_initialized")'+ assert reset_call in setup_layout+ assert setup_layout.index(reset_call) < setup_layout.index("win.setSize")+ assert 'invoke("mark_app_window_layout_initialized")' in source+ assert "hasInitializedAppLayout && hasSavedState" in source+++def test_expanded_titlebar_button_and_corner_match_sidebar_edge():+ source = TITLEBAR.read_text(encoding = "utf-8")++ assert 'pinned ? "gap-2 pl-3" : "justify-center"' in source+ assert "gap-2 px-3" not in source+ assert "const contentBorderLeft = pinned" in source+ assert ': "0px";' in source+ # The curved transition and sidebar-colored backing are expanded-only;+ # collapsed content is square and its divider spans the sidebar too.+ assert source.count("{showSidebarSurface && pinned && (") == 2+ assert (+ 'className="pointer-events-none absolute top-full size-3 -translate-x-px bg-sidebar"'+ in source+ )+ assert (+ 'className="pointer-events-none absolute top-full size-3 -translate-x-px rounded-tl-[12px] border-l border-t border-sidebar-border bg-background"'+ in source+ )