Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: add Edit image to Library image menus (#14170)

Michael Han83dfe5465f24
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 9ca25b50377..73c325806b9 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -147,6 +147,7 @@ import {
saveLastPrompt,
} from "@/lib/last-prompt";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
+import { useImageEditHandoffStore } from "@/stores/image-edit-handoff";
import { isWorkflowEnabled, useImageWorkflowStore } from "./stores/image-workflow-store";
import {
WORKFLOW_EXAMPLE_PROMPTS,
@@ -215,7 +216,7 @@ import { evictedSlotsFrom, evictedToastOptions, resyncEvicted, type EvictedSlot
import { failureMessage, isMultiModelRefusal, MULTI_MODEL_REFUSAL_TITLE, refusalHeadersOf } from "@/lib/multi-model-refusal";
import { watchSavingPhase } from "@/lib/swap-save-phase";
import { modelMemorySettingsAction } from "@/features/settings/lib/model-memory-action";
-import { MAX_UPLOAD_IMAGE_SIDE, fitImageDataUrl } from "@/lib/image-fit";
+import { MAX_UPLOAD_IMAGE_SIDE, blobToDataUrl, fitImageDataUrl } from "@/lib/image-fit";
import { loadGalleryUntil } from "@/lib/gallery-deep-link";
import { subscribeModelEjected } from "@/lib/model-lifecycle-events";
import {
@@ -467,16 +468,6 @@ const RESYNC_MAX_ATTEMPTS = 3;
// For example Unsloth_20260624-143005_123.png.
type ImageExportFormat = "png" | "jpeg" | "webp";
-function blobToDataUrl(blob: Blob): Promise<string> {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () =>
- typeof reader.result === "string" ? resolve(reader.result) : reject(new Error("Could not read the image"));
- reader.onerror = () => reject(reader.error ?? new Error("Could not read the image"));
- reader.readAsDataURL(blob);
- });
-}
-
function exportFilename(image: GalleryImage, format: ImageExportFormat = "png"): string {
const d = new Date(image.created_at * 1000);
const p = (n: number) => String(n).padStart(2, "0");
@@ -3397,24 +3388,8 @@ export function ImagesPage({
setMaskImage(null);
setMaskResetKey((k) => k + 1);
}, []);
- // Only the newest click applies: the gallery fetch can outlive a second one.
- const editRequest = useRef(0);
- const editGalleryImage = useCallback(
- async (image: GalleryImage) => {
- const claimed = ++editRequest.current;
- let dataUrl: string;
- try {
- const blob = await fetchGalleryBlob(image.url);
- dataUrl = await fitImageDataUrl(await blobToDataUrl(blob), MAX_UPLOAD_IMAGE_SIDE);
- } catch (error) {
- if (claimed === editRequest.current) {
- toast.error("Could not open the image for editing", {
- description: error instanceof Error ? error.message : String(error),
- });
- }
- return;
- }
- if (claimed !== editRequest.current) return;
+ const applyEditSource = useCallback(
+ (dataUrl: string) => {
const target: WorkflowId | null = isWorkflowEnabled("edit", supported)
? "edit"
: isWorkflowEnabled("transform", supported)
@@ -3436,6 +3411,39 @@ export function ImagesPage({
},
[supported, setWorkflow, handleInitChange],
);
+ // Only the newest click applies: the gallery fetch can outlive a second one.
+ const editRequest = useRef(0);
+ const editGalleryImage = useCallback(
+ async (image: GalleryImage) => {
+ const claimed = ++editRequest.current;
+ let dataUrl: string;
+ try {
+ const blob = await fetchGalleryBlob(image.url);
+ dataUrl = await fitImageDataUrl(await blobToDataUrl(blob), MAX_UPLOAD_IMAGE_SIDE);
+ } catch (error) {
+ if (claimed === editRequest.current) {
+ toast.error("Could not open the image for editing", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ }
+ return;
+ }
+ if (claimed === editRequest.current) applyEditSource(dataUrl);
+ },
+ [applyEditSource],
+ );
+ const pendingLibraryEdit = useImageEditHandoffStore((s) => s.pending);
+ // Held until the loaded model's workflows are known, or a later snap to Create drops the source.
+ const capabilitiesKnown = external
+ ? supported !== null
+ : status !== null && (!status.loaded || supported !== null);
+ useEffect(() => {
+ if (!pendingLibraryEdit || !capabilitiesKnown) return;
+ const dataUrl = useImageEditHandoffStore.getState().take();
+ if (!dataUrl) return;
+ editRequest.current += 1;
+ applyEditSource(dataUrl);
+ }, [pendingLibraryEdit, capabilitiesKnown, applyEditSource]);
const editImageItem = (image: GalleryImage) => (
<DropdownMenuItem onClick={() => void editGalleryImage(image)}>
<HugeiconsIcon icon={Edit03Icon} strokeWidth={1.75} className="size-icon" />
diff --git a/studio/frontend/src/features/library/actions-context.ts b/studio/frontend/src/features/library/actions-context.ts
index e3d0c080929..46268584fa5 100644
--- a/studio/frontend/src/features/library/actions-context.ts
+++ b/studio/frontend/src/features/library/actions-context.ts
@@ -13,6 +13,7 @@ export interface LibraryActions {
openItem: (item: LibraryItem) => void;
openFolder: (folderId: string) => void;
chatAbout: (target: LibraryTarget) => void;
+ editImage: (item: LibraryItem) => void;
toggleFavorite: (item: LibraryItem) => void;
download: (item: LibraryItem) => void;
rename: (target: LibraryTarget) => void;
diff --git a/studio/frontend/src/features/library/actions.ts b/studio/frontend/src/features/library/actions.ts
index b8b5d5d6c93..0c3f75e28ab 100644
--- a/studio/frontend/src/features/library/actions.ts
+++ b/studio/frontend/src/features/library/actions.ts
@@ -18,8 +18,10 @@ import {
requestModelConfigHandoff,
} from "@/features/model-picker";
import { translate } from "@/i18n";
+import { useImageEditHandoffStore } from "@/stores/image-edit-handoff";
import { MAX_AUDIO_SIZE } from "@/lib/audio-utils";
import { isTauri } from "@/lib/api-base";
+import { MAX_UPLOAD_IMAGE_SIDE, blobToDataUrl, fitImageDataUrl } from "@/lib/image-fit";
import { downloadFile, downloadUrlStreaming, isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { MAX_VIDEO_SIZE } from "@/lib/video-utils";
@@ -194,6 +196,26 @@ export async function chatAboutItems(
}
}
+// Read whole before it is fitted to the 4096 px upload limit, so a large original still opens.
+const MAX_EDIT_SOURCE_BYTES = 64 * 1024 * 1024;
+
+let editRequest = 0;
+
+export async function editLibraryImage(navigate: Navigate, item: LibraryItem): Promise<void> {
+ const epoch = getAuthSessionEpoch();
+ const claimed = ++editRequest;
+ try {
+ const file = await libraryItemFile(item, MAX_EDIT_SOURCE_BYTES);
+ const dataUrl = await fitImageDataUrl(await blobToDataUrl(file), MAX_UPLOAD_IMAGE_SIDE);
+ if (getAuthSessionEpoch() !== epoch || claimed !== editRequest) return;
+ useImageEditHandoffStore.getState().offer(dataUrl);
+ void navigate({ to: "/images" });
+ } catch (error) {
+ if (claimed !== editRequest) return;
+ toast.error(translate("library.toast.editImageFailed"), { description: errorMessage(error) });
+ }
+}
+
export async function chatWithModel(
navigate: Navigate,
item: LibraryItem,
diff --git a/studio/frontend/src/features/library/components/library-actions.tsx b/studio/frontend/src/features/library/components/library-actions.tsx
index 474b75b089a..924b6bf074b 100644
--- a/studio/frontend/src/features/library/components/library-actions.tsx
+++ b/studio/frontend/src/features/library/components/library-actions.tsx
@@ -17,6 +17,7 @@ import {
ArrowTurnBackwardIcon,
Delete02Icon,
Download01Icon,
+ Edit02Icon,
Edit03Icon,
Folder01Icon,
FolderAddIcon,
@@ -27,7 +28,7 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { MessageCircleIcon, StarPointedIcon } from "@/lib/hugeicons-derived";
import { useMemo, useState } from "react";
import type { LibraryFolder } from "../api";
-import { isDeletable, isFileItem, isModelItem } from "../file-kind";
+import { hasImagePreview, isDeletable, isFileItem, isModelItem } from "../file-kind";
import { type LibraryTarget, useLibraryActions } from "../actions-context";
import { useLibraryOrigin } from "../origin";
import { canReveal, revealInFolder, useRevealLabel } from "../reveal";
@@ -120,6 +121,12 @@ export function LibraryActionsMenu({
<HugeiconsIcon icon={MessageCircleIcon} strokeWidth={1.75} className={ICON} />
{t(item && isModelItem(item) ? "library.menu.chatWithModel" : "library.menu.chatAboutThis")}
</DropdownMenuItem>
+ {item && hasImagePreview(item) && (
+ <DropdownMenuItem onSelect={() => actions.editImage(item)}>
+ <HugeiconsIcon icon={Edit02Icon} strokeWidth={1.75} className={ICON} />
+ {t("library.menu.editImage")}
+ </DropdownMenuItem>
+ )}
{origin && (
<DropdownMenuItem onSelect={origin.open}>
<HugeiconsIcon icon={ArrowTurnBackwardIcon} strokeWidth={1.75} className={ICON} />
diff --git a/studio/frontend/src/features/library/library-page.tsx b/studio/frontend/src/features/library/library-page.tsx
index 66cdd2e50b7..91db1aa545d 100644
--- a/studio/frontend/src/features/library/library-page.tsx
+++ b/studio/frontend/src/features/library/library-page.tsx
@@ -43,6 +43,7 @@ import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } fro
import {
chatAboutItems,
chatWithModel,
+ editLibraryImage,
downloadLibraryItem,
downloadLibraryItems,
} from "./actions";
@@ -504,6 +505,7 @@ function LibraryView({ search }: { search: LibrarySearch }) {
target.kind === "item"
? chatAbout(target.item)
: void chatAboutItems(navigate, filesInFolder(target.folder.id)),
+ editImage: (item) => void editLibraryImage(navigate, item),
toggleFavorite: (item) =>
void patchItem(item.id, { favorite: !item.favorite }).catch(fail(t("library.toast.favoritesFailed"))),
download: (item) => void downloadLibraryItem(item),
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 01dcaa5017b..fc2c7efde17 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -4305,6 +4305,7 @@ export const ar = {
moreActions: "إجراءات أخرى",
chatAboutThis: "الدردشة حول هذا",
chatWithModel: "الدردشة مع هذا النموذج",
+ editImage: "تعديل الصورة",
addToFavorites: "إضافة إلى المفضلة",
regenerateTitle: "إعادة إنشاء العنوان",
removeFromFavorites: "إزالة من المفضلة",
@@ -4500,6 +4501,7 @@ export const ar = {
skippedOverLimit: "ملفات إضافية تتجاوز حد {limit} ملفات: {count}.",
chatFilesWaiting: "ستُرفق عند تحميل نموذج يمكنه قراءتها: {count}.",
openFilesFailed: "تعذّر فتح الملفات",
+ editImageFailed: "تعذّر فتح الصورة لتعديلها",
speechModel: "{name} نموذج كلام",
speechModelDescription: "اختره من قائمة النماذج في صفحة الصوت.",
noMediaLink: "لم يُرجع الخادم أي رابط لتشغيل هذا الملف.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index afec35e6200..35e64ded67d 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -4379,6 +4379,7 @@ export const de = {
moreActions: "Weitere Aktionen",
chatAboutThis: "Darüber chatten",
chatWithModel: "Mit diesem Modell chatten",
+ editImage: "Bild bearbeiten",
addToFavorites: "Zu Favoriten hinzufügen",
regenerateTitle: "Titel neu generieren",
removeFromFavorites: "Aus Favoriten entfernen",
@@ -4574,6 +4575,7 @@ export const de = {
skippedOverLimit: "{count} weitere über dem Limit von {limit} Dateien.",
chatFilesWaiting: "{count} werden angehängt, sobald ein Modell geladen ist, das sie lesen kann.",
openFilesFailed: "Die Dateien konnten nicht geöffnet werden",
+ editImageFailed: "Das Bild konnte nicht zum Bearbeiten geöffnet werden",
speechModel: "{name} ist ein Sprachmodell",
speechModelDescription: "Wählen Sie es im Modellmenü auf der Audio-Seite aus.",
noMediaLink: "Der Server hat keinen Link zum Abspielen dieser Datei zurückgegeben.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index ceea9374525..a9df7ba19b9 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -4350,6 +4350,7 @@ export const en = {
moreActions: "More actions",
chatAboutThis: "Chat about this",
chatWithModel: "Chat with this model",
+ editImage: "Edit image",
addToFavorites: "Add to Favorites",
regenerateTitle: "Regenerate title",
removeFromFavorites: "Remove from Favorites",
@@ -4559,6 +4560,7 @@ export const en = {
skippedOverLimit: "{count} more past the {limit} file limit.",
chatFilesWaiting: "{count} will be attached once a model that reads them is loaded.",
openFilesFailed: "Could not open the files",
+ editImageFailed: "Could not open the image for editing",
speechModel: "{name} is a speech model",
speechModelDescription: "Pick it from the model menu on the Audio page.",
noMediaLink: "The server returned no link to play this file.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 210ad2012dd..5310a95cd65 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -4378,6 +4378,7 @@ export const es = {
moreActions: "Más acciones",
chatAboutThis: "Chatear sobre esto",
chatWithModel: "Chatear con este modelo",
+ editImage: "Editar imagen",
addToFavorites: "Añadir a Favoritos",
regenerateTitle: "Regenerar título",
removeFromFavorites: "Quitar de Favoritos",
@@ -4573,6 +4574,7 @@ export const es = {
skippedOverLimit: "{count} más por encima del límite de {limit} archivos.",
chatFilesWaiting: "{count} se adjuntarán cuando se cargue un modelo que pueda leerlos.",
openFilesFailed: "No se pudieron abrir los archivos",
+ editImageFailed: "No se pudo abrir la imagen para editarla",
speechModel: "{name} es un modelo de voz",
speechModelDescription: "Selecciónalo en el menú de modelos de la página Audio.",
noMediaLink: "El servidor no devolvió ningún enlace para reproducir este archivo.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 367a718d123..343e1897f57 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -4390,6 +4390,7 @@ export const fr = {
moreActions: "Plus d'actions",
chatAboutThis: "Discuter de ce fichier",
chatWithModel: "Discuter avec ce modèle",
+ editImage: "Modifier l'image",
addToFavorites: "Ajouter aux favoris",
regenerateTitle: "Régénérer le titre",
removeFromFavorites: "Retirer des favoris",
@@ -4585,6 +4586,7 @@ export const fr = {
skippedOverLimit: "{count} de plus au-delà de la limite de {limit} fichiers.",
chatFilesWaiting: "{count} seront joints dès qu'un modèle capable de les lire sera chargé.",
openFilesFailed: "Impossible d'ouvrir les fichiers",
+ editImageFailed: "Impossible d'ouvrir l'image pour la modifier",
speechModel: "{name} est un modèle vocal",
speechModelDescription: "Sélectionnez-le dans le menu des modèles de la page Audio.",
noMediaLink: "Le serveur n'a renvoyé aucun lien pour lire ce fichier.",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 390bdff565d..55b47cca60b 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -4431,6 +4431,7 @@ export const he = {
moreActions: "פעולות נוספות",
chatAboutThis: "שוחח על זה",
chatWithModel: "שוחח עם מודל זה",
+ editImage: "עריכת תמונה",
addToFavorites: "הוסף למועדפים",
regenerateTitle: "יצירת כותרת מחדש",
removeFromFavorites: "הסר מהמועדפים",
@@ -4633,6 +4634,7 @@ export const he = {
skippedOverLimit: "{count} נוספים מעבר למגבלה של {limit} קבצים.",
chatFilesWaiting: "{count} יצורפו לאחר טעינת מודל שיכול לקרוא אותם.",
openFilesFailed: "לא ניתן לפתוח את הקבצים",
+ editImageFailed: "לא ניתן לפתוח את התמונה לעריכה",
speechModel: "{name} הוא מודל דיבור",
speechModelDescription: "בחר אותו מתפריט המודלים בדף האודיו.",
noMediaLink: "השרת לא החזיר קישור להפעלת קובץ זה.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index fdd0c0ee187..952a81da8e8 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -4316,6 +4316,7 @@ export const hi = {
moreActions: "और कार्रवाइयाँ",
chatAboutThis: "इसके बारे में चैट करें",
chatWithModel: "इस मॉडल से चैट करें",
+ editImage: "छवि संपादित करें",
addToFavorites: "पसंदीदा में जोड़ें",
regenerateTitle: "शीर्षक फिर से बनाएं",
removeFromFavorites: "पसंदीदा से हटाएँ",
@@ -4511,6 +4512,7 @@ export const hi = {
skippedOverLimit: "{limit} फ़ाइलों की सीमा से {count} और ज़्यादा हैं।",
chatFilesWaiting: "{count} फ़ाइलें तब अटैच होंगी जब उन्हें पढ़ सकने वाला मॉडल लोड हो जाएगा।",
openFilesFailed: "फ़ाइलें खोली नहीं जा सकीं",
+ editImageFailed: "संपादन के लिए छवि नहीं खोली जा सकी",
speechModel: "{name} एक स्पीच मॉडल है",
speechModelDescription: "इसे ऑडियो पेज के मॉडल मेनू से चुनें।",
noMediaLink: "सर्वर ने इस फ़ाइल को चलाने के लिए कोई लिंक नहीं लौटाया।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 4483f9831a2..2c963b4acbc 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -4380,6 +4380,7 @@ export const it = {
moreActions: "Altre azioni",
chatAboutThis: "Chatta su questo",
chatWithModel: "Chatta con questo modello",
+ editImage: "Modifica immagine",
addToFavorites: "Aggiungi ai preferiti",
regenerateTitle: "Rigenera titolo",
removeFromFavorites: "Rimuovi dai preferiti",
@@ -4575,6 +4576,7 @@ export const it = {
skippedOverLimit: "Altri {count} oltre il limite di {limit} file.",
chatFilesWaiting: "{count} verranno allegati appena sarà caricato un modello in grado di leggerli.",
openFilesFailed: "Impossibile aprire i file",
+ editImageFailed: "Impossibile aprire l'immagine per la modifica",
speechModel: "{name} è un modello vocale",
speechModelDescription: "Sceglilo dal menu dei modelli nella pagina Audio.",
noMediaLink: "Il server non ha restituito alcun link per riprodurre questo file.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 7d99b729797..bd467ff7f77 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -4252,6 +4252,7 @@ export const ja = {
moreActions: "その他の操作",
chatAboutThis: "これについてチャット",
chatWithModel: "このモデルとチャット",
+ editImage: "画像を編集",
addToFavorites: "お気に入りに追加",
regenerateTitle: "タイトルを再生成",
removeFromFavorites: "お気に入りから削除",
@@ -4447,6 +4448,7 @@ export const ja = {
skippedOverLimit: "{limit} ファイルの上限を超えた {count} 個は添付されていません。",
chatFilesWaiting: "{count} 個は、読み取れるモデルが読み込まれると添付されます。",
openFilesFailed: "ファイルを開けませんでした",
+ editImageFailed: "編集のために画像を開けませんでした",
speechModel: "{name} は音声モデルです",
speechModelDescription: "音声ページのモデルメニューから選択してください。",
noMediaLink: "サーバーからこのファイルを再生するためのリンクが返されませんでした。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index a1b1b4831f1..07bfa1a046f 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -4294,6 +4294,7 @@ export const ko = {
moreActions: "추가 작업",
chatAboutThis: "이 파일로 채팅",
chatWithModel: "이 모델과 채팅",
+ editImage: "이미지 편집",
addToFavorites: "즐겨찾기에 추가",
regenerateTitle: "제목 다시 생성",
removeFromFavorites: "즐겨찾기에서 제거",
@@ -4489,6 +4490,7 @@ export const ko = {
skippedOverLimit: "{limit}개 파일 한도를 넘는 {count}개는 제외되었습니다.",
chatFilesWaiting: "{count}개는 이를 읽을 수 있는 모델이 로드되면 첨부됩니다.",
openFilesFailed: "파일을 열지 못했습니다",
+ editImageFailed: "편집할 이미지를 열 수 없습니다",
speechModel: "{name}은(는) 음성 모델입니다",
speechModelDescription: "오디오 페이지의 모델 메뉴에서 선택하세요.",
noMediaLink: "서버가 이 파일을 재생할 링크를 반환하지 않았습니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index dd36b1ad812..abdf7269f93 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -4338,6 +4338,7 @@ export const ptBR = {
moreActions: "Mais ações",
chatAboutThis: "Conversar sobre isto",
chatWithModel: "Conversar com este modelo",
+ editImage: "Editar imagem",
addToFavorites: "Adicionar aos Favoritos",
regenerateTitle: "Regenerar título",
removeFromFavorites: "Remover dos Favoritos",
@@ -4533,6 +4534,7 @@ export const ptBR = {
skippedOverLimit: "Mais {count} além do limite de {limit} arquivos.",
chatFilesWaiting: "{count} serão anexados assim que um modelo capaz de lê-los for carregado.",
openFilesFailed: "Não foi possível abrir os arquivos",
+ editImageFailed: "Não foi possível abrir a imagem para edição",
speechModel: "{name} é um modelo de fala",
speechModelDescription: "Escolha-o no menu de modelos da página Áudio.",
noMediaLink: "O servidor não retornou nenhum link para reproduzir este arquivo.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 79bd8c961d5..c8c1b4e5665 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -4336,6 +4336,7 @@ export const ru = {
moreActions: "Другие действия",
chatAboutThis: "Обсудить в чате",
chatWithModel: "Чат с этой моделью",
+ editImage: "Редактировать изображение",
addToFavorites: "Добавить в избранное",
regenerateTitle: "Создать название заново",
removeFromFavorites: "Удалить из избранного",
@@ -4531,6 +4532,7 @@ export const ru = {
skippedOverLimit: "Сверх лимита в {limit} файлов: ещё {count}.",
chatFilesWaiting: "Будут прикреплены после загрузки модели, которая может их прочитать: {count}.",
openFilesFailed: "Не удалось открыть файлы",
+ editImageFailed: "Не удалось открыть изображение для редактирования",
speechModel: "{name} — модель синтеза речи",
speechModelDescription: "Выберите её в меню моделей на странице «Аудио».",
noMediaLink: "Сервер не вернул ссылку для воспроизведения этого файла.",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 066be332007..aa1b616c940 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -4575,6 +4575,7 @@ export const sv = {
moreActions: "Fler åtgärder",
chatAboutThis: "Chatta om detta",
chatWithModel: "Chatta med den här modellen",
+ editImage: "Redigera bild",
addToFavorites: "Lägg till i Favoriter",
regenerateTitle: "Generera om titel",
removeFromFavorites: "Ta bort från Favoriter",
@@ -4780,6 +4781,7 @@ export const sv = {
chatFilesWaiting:
"{count} bifogas när en modell som kan läsa dem har lästs in.",
openFilesFailed: "Det gick inte att öppna filerna",
+ editImageFailed: "Det gick inte att öppna bilden för redigering",
speechModel: "{name} är en talmodell",
speechModelDescription: "Välj den i modellmenyn på sidan Ljud.",
noMediaLink:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index df9bfcda793..0a5713b1b98 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -4206,6 +4206,7 @@ export const zhCN = {
moreActions: "更多操作",
chatAboutThis: "就此聊天",
chatWithModel: "与此模型聊天",
+ editImage: "编辑图片",
addToFavorites: "加入收藏",
regenerateTitle: "重新生成标题",
removeFromFavorites: "取消收藏",
@@ -4401,6 +4402,7 @@ export const zhCN = {
skippedOverLimit: "另有 {count} 个超出 {limit} 个文件的上限。",
chatFilesWaiting: "{count} 个文件将在加载可读取它们的模型后附加。",
openFilesFailed: "无法打开这些文件",
+ editImageFailed: "无法打开图片进行编辑",
speechModel: "{name} 是语音模型",
speechModelDescription: "请在音频页面的模型菜单中选择它。",
noMediaLink: "服务器未返回用于播放此文件的链接。",
diff --git a/studio/frontend/src/lib/image-fit.ts b/studio/frontend/src/lib/image-fit.ts
index c9768cffed7..d2f375aa228 100644
--- a/studio/frontend/src/lib/image-fit.ts
+++ b/studio/frontend/src/lib/image-fit.ts
@@ -25,6 +25,16 @@ export function fitOutputType(dataUrl: string): "image/jpeg" | "image/png" {
return /^data:image\/(jpeg|jpg|pjpeg)[;,]/i.test(dataUrl) ? "image/jpeg" : "image/png";
}
+export function blobToDataUrl(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () =>
+ typeof reader.result === "string" ? resolve(reader.result) : reject(new Error("Could not read the image"));
+ reader.onerror = () => reject(reader.error ?? new Error("Could not read the image"));
+ reader.readAsDataURL(blob);
+ });
+}
+
/** Anything that fits, or that this browser cannot decode, is returned unchanged so the server still reports it. */
export async function fitImageDataUrl(dataUrl: string, maxSide: number): Promise<string> {
let image: HTMLImageElement;
diff --git a/studio/frontend/src/stores/image-edit-handoff.ts b/studio/frontend/src/stores/image-edit-handoff.ts
new file mode 100644
index 00000000000..c1b853ef972
--- /dev/null
+++ b/studio/frontend/src/stores/image-edit-handoff.ts
@@ -0,0 +1,31 @@
+// 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 { create } from "zustand";
+import { AUTH_SESSION_CLEARED_EVENT } from "@/features/auth";
+
+// "Edit image" from the Library: the Images page may mount on navigation or already be mounted
+// off-route, so the source image waits here until the page takes it.
+interface ImageEditHandoffState {
+ pending: string | null;
+ offer: (dataUrl: string) => void;
+ take: () => string | null;
+}
+
+export const useImageEditHandoffStore = create<ImageEditHandoffState>(
+ (set, get) => ({
+ pending: null,
+ offer: (pending) => set({ pending }),
+ take: () => {
+ const pending = get().pending;
+ if (pending) set({ pending: null });
+ return pending;
+ },
+ }),
+);
+
+if (typeof window !== "undefined") {
+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, () => {
+ useImageEditHandoffStore.setState({ pending: null });
+ });
+}
diff --git a/studio/frontend/tests/library-audio.test.ts b/studio/frontend/tests/library-audio.test.ts
index bf82f216c18..f0a9749e4c6 100644
--- a/studio/frontend/tests/library-audio.test.ts
+++ b/studio/frontend/tests/library-audio.test.ts
@@ -133,7 +133,9 @@ function chatWithModelFor(lora: { audio_type: string; export_type: string }, dev
"@/i18n": { translate: (key: string) => key },
"@/lib/audio-utils": {},
"@/lib/api-base": { isTauri: false },
+ "@/lib/image-fit": {},
"@/lib/native-files": {},
+ "@/stores/image-edit-handoff": {},
"@/lib/toast": { toast: (title: unknown) => toasts.push(title) },
"@/lib/video-utils": {},
"./api": {},
diff --git a/studio/frontend/tests/library-edit-image.test.ts b/studio/frontend/tests/library-edit-image.test.ts
new file mode 100644
index 00000000000..abc1f8fd0f0
--- /dev/null
+++ b/studio/frontend/tests/library-edit-image.test.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+function editLibraryImageWith({ fail = false, epochAfterRead = 0 } = {}) {
+ const offered: string[] = [];
+ const navigations: unknown[] = [];
+ const errors: unknown[] = [];
+ let epoch = 0;
+ const { editLibraryImage } = loadWithStubs<{
+ editLibraryImage: (navigate: (to: unknown) => Promise<void>, item: unknown) => Promise<void>;
+ }>(new URL("../src/features/library/actions.ts", import.meta.url), {
+ fflate: {},
+ "@/config/env": {},
+ "@/features/audio/audio-page-policy": {},
+ "@/features/audio/workflows": {},
+ "@/features/auth": { getAuthSessionEpoch: () => epoch },
+ "@/features/chat": {},
+ "@/features/model-picker": {},
+ "@/i18n": { translate: (key: string) => key },
+ "@/lib/audio-utils": {},
+ "@/lib/api-base": { isTauri: false },
+ "@/lib/image-fit": {
+ MAX_UPLOAD_IMAGE_SIDE: 4096,
+ blobToDataUrl: async () => "data:image/png;base64,AAAA",
+ fitImageDataUrl: async (dataUrl: string) => `${dataUrl}#fit`,
+ },
+ "@/lib/native-files": {},
+ "@/lib/toast": { toast: { error: (title: unknown) => errors.push(title) } },
+ "@/lib/video-utils": {},
+ "@/stores/image-edit-handoff": {
+ useImageEditHandoffStore: { getState: () => ({ offer: (url: string) => offered.push(url) }) },
+ },
+ "./api": {
+ LibraryFileTooLarge: class extends Error {},
+ errorMessage: (error: unknown) => String(error),
+ libraryItemFile: async () => {
+ if (fail) throw new Error("gone");
+ epoch = epochAfterRead;
+ return new Blob(["x"], { type: "image/png" });
+ },
+ },
+ "./file-kind": {},
+ "./file-name": {},
+ "./start-chat": {},
+ });
+ return editLibraryImage(async (to) => void navigations.push(to), { name: "cat.png" }).then(() => ({
+ offered,
+ navigations,
+ errors,
+ }));
+}
+
+test("Edit image hands the fitted image to the Images page and opens it", async () => {
+ const { offered, navigations, errors } = await editLibraryImageWith();
+ assert.deepEqual(offered, ["data:image/png;base64,AAAA#fit"]);
+ assert.deepEqual(navigations, [{ to: "/images" }]);
+ assert.deepEqual(errors, []);
+});
+
+test("Edit image says so when the file cannot be read, and opens nothing", async () => {
+ const { offered, navigations, errors } = await editLibraryImageWith({ fail: true });
+ assert.deepEqual(offered, []);
+ assert.deepEqual(navigations, []);
+ assert.deepEqual(errors, ["library.toast.editImageFailed"]);
+});
+
+test("Edit image hands nothing to an account that signed in during the read", async () => {
+ const { offered, navigations } = await editLibraryImageWith({ epochAfterRead: 1 });
+ assert.deepEqual(offered, []);
+ assert.deepEqual(navigations, []);
+});
+
+test("Edit image keeps only the newest click when an earlier read finishes last", async () => {
+ const offered: string[] = [];
+ const reads = new Map<string, (blob: Blob) => void>();
+ const { editLibraryImage } = loadWithStubs<{
+ editLibraryImage: (navigate: (to: unknown) => Promise<void>, item: { name: string }) => Promise<void>;
+ }>(new URL("../src/features/library/actions.ts", import.meta.url), {
+ fflate: {},
+ "@/config/env": {},
+ "@/features/audio/audio-page-policy": {},
+ "@/features/audio/workflows": {},
+ "@/features/auth": { getAuthSessionEpoch: () => 0 },
+ "@/features/chat": {},
+ "@/features/model-picker": {},
+ "@/i18n": { translate: (key: string) => key },
+ "@/lib/audio-utils": {},
+ "@/lib/api-base": { isTauri: false },
+ "@/lib/image-fit": {
+ MAX_UPLOAD_IMAGE_SIDE: 4096,
+ blobToDataUrl: async (blob: Blob) => `data:${await blob.text()}`,
+ fitImageDataUrl: async (dataUrl: string) => dataUrl,
+ },
+ "@/lib/native-files": {},
+ "@/lib/toast": { toast: { error: () => {} } },
+ "@/lib/video-utils": {},
+ "@/stores/image-edit-handoff": {
+ useImageEditHandoffStore: { getState: () => ({ offer: (url: string) => offered.push(url) }) },
+ },
+ "./api": {
+ LibraryFileTooLarge: class extends Error {},
+ errorMessage: (error: unknown) => String(error),
+ libraryItemFile: (item: { name: string }) =>
+ new Promise<Blob>((resolve) => reads.set(item.name, resolve)),
+ },
+ "./file-kind": {},
+ "./file-name": {},
+ "./start-chat": {},
+ });
+ const navigate = async () => {};
+ const first = editLibraryImage(navigate, { name: "first" });
+ const second = editLibraryImage(navigate, { name: "second" });
+ reads.get("second")?.(new Blob(["second"]));
+ await second;
+ reads.get("first")?.(new Blob(["first"]));
+ await first;
+ assert.deepEqual(offered, ["data:second"]);
+});
diff --git a/studio/frontend/tests/library-state.test.ts b/studio/frontend/tests/library-state.test.ts
index 655d27c769f..c50b177afe1 100644
--- a/studio/frontend/tests/library-state.test.ts
+++ b/studio/frontend/tests/library-state.test.ts
@@ -406,6 +406,8 @@ function loadDownloads(
"@/i18n": { translate: (key: string) => key },
"@/lib/audio-utils": {},
"@/lib/api-base": { isTauri: false },
+ "@/lib/image-fit": {},
+ "@/stores/image-edit-handoff": {},
"@/lib/native-files": {
downloadFile: async (f: File | Blob) => saved.push(f),
isDownloadCancelled: () => false,