Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(models): export and import model settings as JSON

joshistoast2ab76ed55229
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index aedbf3b539..af469e0e7d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -920,6 +920,7 @@
"emptyCache": "Empty model cache",
"externalProviderKeyDescription": "Stored server-side and used for every request to this provider.",
"externalProviderKeysUnavailable": "Could not load external provider keys",
+ "exportSettings": "Export settings…",
"externalProvidersUnavailable": "External providers are unavailable: {{error}}",
"failedToEmptyCache": "Failed to empty model cache",
"failedToLinkModels": "Failed to link models.",
@@ -967,6 +968,7 @@
"installsDependencies_one": " (installs {{count}} dependency)",
"installsDependencies_other": " (installs {{count}} dependencies)",
"imageEncoderModelId": "Image Encoder",
+ "importSettings": "Import settings…",
"invalidDefaultSettings": "Invalid default settings.",
"invalidPathFormat": "Must be an absolute path.",
"invalidTriggerPhrase": "Invalid trigger phrase.",
@@ -1108,6 +1110,12 @@
"selectModelDescription": "Pick a model from the library to view details, edit metadata, set per-model defaults, and manage trigger phrases.",
"selectedCount_one": "{{count}} selected",
"selectedCount_other": "{{count}} selected",
+ "settingsExported": "Settings exported",
+ "settingsImportFailed": "Failed to import settings",
+ "settingsImportIncompatible": "None of the imported settings apply to this model",
+ "settingsImportInvalidFile": "Not a valid model settings file",
+ "settingsImported": "Settings imported",
+ "settingsImportedPartial": "Imported with skipped fields: {{fields}}",
"someCouldNotBeDeleted": "Some models could not be deleted",
"someCouldNotBeReidentified": "Some models could not be re-identified",
"sort": {
diff --git a/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.test.ts b/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.test.ts
new file mode 100644
index 0000000000..434829d5c4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ModelConfig } from './types';
+
+import {
+ buildExportData,
+ dataUrlToFile,
+ isImageDataUrl,
+ isSafeUrl,
+ partitionImportableFields,
+ sanitizeFilename,
+ validateImportData,
+} from './modelSettingsIO';
+
+// 1x1 transparent PNG.
+const PNG_DATA_URL =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
+
+const model = (overrides: Partial<ModelConfig>): ModelConfig =>
+ ({
+ base: 'sdxl',
+ file_size: 1,
+ format: 'checkpoint',
+ hash: 'hash',
+ key: 'key',
+ name: 'Model',
+ path: '/models/m.safetensors',
+ source: '/models/m.safetensors',
+ source_type: 'path',
+ type: 'main',
+ ...overrides,
+ }) as ModelConfig;
+
+describe('sanitizeFilename', () => {
+ it('replaces filesystem-unsafe characters with underscores', () => {
+ expect(sanitizeFilename('a/b\\c:d*e?f"g<h>i|j')).toBe('a_b_c_d_e_f_g_h_i_j');
+ expect(sanitizeFilename('Juggernaut XL v9')).toBe('Juggernaut XL v9');
+ });
+});
+
+describe('isSafeUrl', () => {
+ it('accepts only http(s)', () => {
+ expect(isSafeUrl('https://example.com')).toBe(true);
+ expect(isSafeUrl('http://example.com')).toBe(true);
+ expect(isSafeUrl('javascript:alert(1)')).toBe(false);
+ expect(isSafeUrl('file:///etc/passwd')).toBe(false);
+ });
+});
+
+describe('isImageDataUrl / dataUrlToFile', () => {
+ it('accepts base64 image data URLs and rejects everything else', () => {
+ expect(isImageDataUrl(PNG_DATA_URL)).toBe(true);
+ expect(isImageDataUrl('data:text/html;base64,PGI+')).toBe(false);
+ expect(isImageDataUrl('data:image/png,not-base64')).toBe(false);
+ expect(isImageDataUrl('https://example.com/x.png')).toBe(false);
+ });
+
+ it('decodes a valid data URL into a File and returns null otherwise', () => {
+ const file = dataUrlToFile(PNG_DATA_URL, 'cover.png');
+
+ expect(file).toBeInstanceOf(File);
+ expect(file?.type).toBe('image/png');
+ expect(file?.name).toBe('cover.png');
+
+ expect(dataUrlToFile('not-a-data-url', 'x.png')).toBeNull();
+ expect(dataUrlToFile('data:image/png;base64,', 'x.png')).toBeNull();
+ expect(dataUrlToFile('data:image/png;base64,!!!not-base64!!!', 'x.png')).toBeNull();
+ });
+});
+
+describe('buildExportData', () => {
+ it('includes only present, non-empty fields', () => {
+ expect(buildExportData(model({ description: null, name: '' }))).toEqual({});
+
+ expect(
+ buildExportData(
+ model({
+ cpu_only: false,
+ default_settings: { weight: 0.8 },
+ description: 'desc',
+ name: 'Named',
+ source_url: 'https://example.com',
+ trigger_phrases: ['t1'],
+ })
+ )
+ ).toEqual({
+ cpu_only: false,
+ default_settings: { weight: 0.8 },
+ description: 'desc',
+ name: 'Named',
+ source_url: 'https://example.com',
+ trigger_phrases: ['t1'],
+ });
+ });
+
+ it('never includes the cover image (fetched separately, async)', () => {
+ expect(buildExportData(model({ cover_image: 'present', name: 'X' }))).toEqual({ name: 'X' });
+ });
+});
+
+describe('validateImportData', () => {
+ it('accepts an empty object and a fully populated export, rejects non-objects', () => {
+ expect(validateImportData({})).toBe(true);
+ expect(
+ validateImportData({
+ cover_image: PNG_DATA_URL,
+ cpu_only: true,
+ default_settings: { weight: 1 },
+ description: 'd',
+ name: 'n',
+ source_url: 'https://example.com',
+ trigger_phrases: ['a', 'b'],
+ unknown_field: 'ignored',
+ })
+ ).toBe(true);
+ expect(validateImportData(null)).toBe(false);
+ expect(validateImportData([])).toBe(false);
+ expect(validateImportData('json')).toBe(false);
+ });
+
+ it('rejects wrong field types and unsafe values', () => {
+ expect(validateImportData({ name: 42 })).toBe(false);
+ expect(validateImportData({ description: {} })).toBe(false);
+ expect(validateImportData({ source_url: 'javascript:alert(1)' })).toBe(false);
+ expect(validateImportData({ source_url: '' })).toBe(true);
+ expect(validateImportData({ cover_image: 'https://example.com/x.png' })).toBe(false);
+ expect(validateImportData({ trigger_phrases: ['ok', 5] })).toBe(false);
+ expect(validateImportData({ default_settings: [] })).toBe(false);
+ expect(validateImportData({ cpu_only: 'yes' })).toBe(false);
+ });
+});
+
+describe('partitionImportableFields', () => {
+ it('applies fields the target config carries and skips the rest', () => {
+ const target = model({ default_settings: null, description: null, trigger_phrases: null });
+ // cpu_only is absent from this main-model config entirely.
+ const { body, skipped } = partitionImportableFields(
+ { cpu_only: true, default_settings: { steps: 20 }, name: 'Renamed', trigger_phrases: ['x'] },
+ target
+ );
+
+ expect(body).toEqual({ default_settings: { steps: 20 }, name: 'Renamed', trigger_phrases: ['x'] });
+ expect(skipped).toEqual(['cpu_only']);
+ });
+
+ it('ignores null and undefined import values', () => {
+ const { body, skipped } = partitionImportableFields({ description: null, name: undefined }, model({}));
+
+ expect(body).toEqual({});
+ expect(skipped).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.ts b/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.ts
new file mode 100644
index 0000000000..8f01e09847
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/core/modelSettingsIO.ts
@@ -0,0 +1,164 @@
+import type { ModelConfig } from './types';
+
+/**
+ * Pure logic for exporting a model's user-editable settings to JSON and
+ * validating/partitioning an import. The file format is shared with the
+ * legacy frontend: `{name?, description?, source_url?, default_settings?,
+ * trigger_phrases?, cpu_only?, cover_image? (data URL)}`. Anything that
+ * fetches or writes lives in the UI layer.
+ */
+
+export const sanitizeFilename = (name: string): string => name.replace(/[<>:"/\\|?*]/g, '_');
+
+export const isSafeUrl = (url: string): boolean => url.startsWith('https://') || url.startsWith('http://');
+
+export const isImageDataUrl = (value: string): boolean => /^data:image\/[a-zA-Z0-9.+-]+;base64,/.test(value);
+
+export const dataUrlToFile = (dataUrl: string, filename: string): File | null => {
+ const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);
+
+ if (!match) {
+ return null;
+ }
+
+ const mime = match[1];
+ const b64 = match[2];
+
+ if (!mime || !b64) {
+ return null;
+ }
+
+ try {
+ const binary = atob(b64);
+ const bytes = new Uint8Array(binary.length);
+
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+
+ return new File([bytes], filename, { type: mime });
+ } catch {
+ return null;
+ }
+};
+
+const IMPORTABLE_FIELDS = [
+ 'name',
+ 'description',
+ 'source_url',
+ 'default_settings',
+ 'trigger_phrases',
+ 'cpu_only',
+] as const;
+
+export const buildExportData = (model: ModelConfig): Record<string, unknown> => {
+ const data: Record<string, unknown> = {};
+
+ if (typeof model.name === 'string' && model.name.length > 0) {
+ data.name = model.name;
+ }
+
+ if (typeof model.description === 'string' && model.description.length > 0) {
+ data.description = model.description;
+ }
+
+ if (typeof model.source_url === 'string' && model.source_url.length > 0) {
+ data.source_url = model.source_url;
+ }
+
+ if (model.default_settings !== undefined && model.default_settings !== null) {
+ data.default_settings = model.default_settings;
+ }
+
+ if (model.trigger_phrases !== undefined && model.trigger_phrases !== null) {
+ data.trigger_phrases = model.trigger_phrases;
+ }
+
+ if (model.cpu_only !== undefined && model.cpu_only !== null) {
+ data.cpu_only = model.cpu_only;
+ }
+
+ return data;
+};
+
+export const validateImportData = (data: unknown): data is Record<string, unknown> => {
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
+ return false;
+ }
+
+ const obj = data as Record<string, unknown>;
+
+ if (obj.name !== undefined && obj.name !== null && typeof obj.name !== 'string') {
+ return false;
+ }
+
+ if (obj.description !== undefined && obj.description !== null && typeof obj.description !== 'string') {
+ return false;
+ }
+
+ if (obj.source_url !== undefined && obj.source_url !== null) {
+ if (typeof obj.source_url !== 'string') {
+ return false;
+ }
+
+ if (obj.source_url.length > 0 && !isSafeUrl(obj.source_url)) {
+ return false;
+ }
+ }
+
+ if (obj.cover_image !== undefined && obj.cover_image !== null) {
+ if (typeof obj.cover_image !== 'string' || !isImageDataUrl(obj.cover_image)) {
+ return false;
+ }
+ }
+
+ if (obj.trigger_phrases !== undefined) {
+ if (!Array.isArray(obj.trigger_phrases) || !obj.trigger_phrases.every((phrase) => typeof phrase === 'string')) {
+ return false;
+ }
+ }
+
+ if (obj.default_settings !== undefined) {
+ if (
+ typeof obj.default_settings !== 'object' ||
+ obj.default_settings === null ||
+ Array.isArray(obj.default_settings)
+ ) {
+ return false;
+ }
+ }
+
+ if (obj.cpu_only !== undefined && typeof obj.cpu_only !== 'boolean') {
+ return false;
+ }
+
+ return true;
+};
+
+/**
+ * Split validated import data into a PATCH body of fields the target model's
+ * config actually carries, and the fields skipped as incompatible (e.g.
+ * cpu_only imported onto a main model). The cover image is not part of the
+ * body — it uploads through its own endpoint.
+ */
+export const partitionImportableFields = (
+ data: Record<string, unknown>,
+ model: ModelConfig
+): { body: Record<string, unknown>; skipped: string[] } => {
+ const body: Record<string, unknown> = {};
+ const skipped: string[] = [];
+
+ for (const field of IMPORTABLE_FIELDS) {
+ if (data[field] === undefined || data[field] === null) {
+ continue;
+ }
+
+ if (field in model) {
+ body[field] = data[field];
+ } else {
+ skipped.push(field);
+ }
+ }
+
+ return { body, skipped };
+};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
index ee9bf71533..aead3d2830 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
@@ -21,6 +21,7 @@ import { DefaultSettingsSection } from './DefaultSettingsSection';
import { MissingFileBadge, ModelBaseBadge, ModelFormatBadge } from './ModelBadges';
import { ModelEditForm } from './ModelEditForm';
import { ModelImageUpload } from './ModelImageUpload';
+import { ModelSettingsMenuItems } from './ModelSettingsMenuItems';
import { RelatedModelsSection } from './RelatedModelsSection';
import { MemoizedTriggerPhrasesEditor } from './TriggerPhrasesEditor';
import { UpdatePathDialog } from './UpdatePathDialog';
@@ -311,6 +312,7 @@ const ModelDetailActions = ({
<Icon as={RefreshCcwIcon} boxSize="3.5" />
<Menu.ItemText fontSize="xs">{t('models.reidentify')}</Menu.ItemText>
</Menu.Item>
+ <ModelSettingsMenuItems modelKey={model.key} />
<Menu.Separator />
<Menu.Item color="fg.error" value="delete" onClick={() => setPendingAction('delete')}>
<Icon as={Trash2Icon} boxSize="3.5" />
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx
new file mode 100644
index 0000000000..0527d7ce8e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx
@@ -0,0 +1,196 @@
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+import { Icon, Menu } from '@chakra-ui/react';
+import {
+ buildExportData,
+ dataUrlToFile,
+ isImageDataUrl,
+ partitionImportableFields,
+ sanitizeFilename,
+ validateImportData,
+} from '@features/models/core/modelSettingsIO';
+import { getModelImageUrl, updateModel, updateModelImage } from '@features/models/data/api';
+import { getModelsSnapshot, markCoverImageChanged, replaceModelInStore } from '@features/models/data/modelsStore';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
+import { useNotify } from '@features/models/ui/useModelsNotify';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { DownloadIcon, UploadIcon } from 'lucide-react';
+import { useRef, type ChangeEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * Export/import a model's user-editable settings as JSON (format shared with
+ * the legacy frontend). Rendered inside the detail pane's overflow menu; the
+ * full config is read from the store at action time so the menu itself only
+ * needs a key.
+ */
+export const ModelSettingsMenuItems = ({ modelKey }: { modelKey: string }) => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const { run } = useScopedAction();
+
+ const findModel = () => getModelsSnapshot().models.find((candidate) => candidate.key === modelKey);
+
+ const handleExport = async () => {
+ const model = findModel();
+
+ if (!model) {
+ return;
+ }
+
+ const data = buildExportData(model);
+
+ if (model.cover_image) {
+ const dataUrl = await fetchImageAsDataUrl(getModelImageUrl(model.key));
+
+ if (dataUrl) {
+ data.cover_image = dataUrl;
+ }
+ }
+
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+
+ anchor.href = url;
+ anchor.download = `${sanitizeFilename(model.name)}.json`;
+ anchor.click();
+ URL.revokeObjectURL(url);
+ notify.success(t('models.settingsExported'), model.name);
+ };
+
+ const applyImport = (data: Record<string, unknown>) =>
+ run(
+ async (owner) => {
+ const model = findModel();
+
+ if (!model) {
+ return;
+ }
+
+ const { body, skipped } = partitionImportableFields(data, model);
+ const coverImageDataUrl =
+ typeof data.cover_image === 'string' && isImageDataUrl(data.cover_image) ? data.cover_image : null;
+
+ if (Object.keys(body).length === 0 && !coverImageDataUrl) {
+ notify.error(t('models.settingsImportIncompatible'), skipped.join(', '));
+
+ return;
+ }
+
+ let applied = false;
+
+ if (Object.keys(body).length > 0) {
+ const updated = await updateModel(model.key, body, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ replaceModelInStore(updated);
+ applied = true;
+ }
+
+ if (coverImageDataUrl) {
+ const imageFile = dataUrlToFile(coverImageDataUrl, `${model.key}.png`);
+
+ if (imageFile) {
+ try {
+ await updateModelImage(model.key, imageFile, owner.signal);
+ assertAccountScopeCurrent(owner);
+ markCoverImageChanged(model.key, true);
+ applied = true;
+ } catch {
+ assertAccountScopeCurrent(owner);
+ skipped.push('cover_image');
+ }
+ } else {
+ skipped.push('cover_image');
+ }
+ }
+
+ if (!applied) {
+ throw new Error(t('models.settingsImportFailed'));
+ }
+
+ if (skipped.length > 0) {
+ notify.info(t('models.settingsImportedPartial', { fields: skipped.join(', ') }));
+ } else {
+ notify.success(t('models.settingsImported'), model.name);
+ }
+ },
+ (message) => notify.error(t('models.settingsImportFailed'), message)
+ );
+
+ const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+
+ // Reset so re-picking the same file fires change again.
+ event.currentTarget.value = '';
+
+ if (!file) {
+ return;
+ }
+
+ let parsed: unknown;
+
+ try {
+ parsed = JSON.parse(await file.text());
+ } catch {
+ notify.error(t('models.settingsImportInvalidFile'));
+
+ return;
+ }
+
+ if (!validateImportData(parsed)) {
+ notify.error(t('models.settingsImportInvalidFile'));
+
+ return;
+ }
+
+ await applyImport(parsed);
+ };
+
+ return (
+ <>
+ <Menu.Item value="export-settings" onClick={() => void handleExport()}>
+ <Icon as={DownloadIcon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">{t('models.exportSettings')}</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Item value="import-settings" onClick={() => fileInputRef.current?.click()}>
+ <Icon as={UploadIcon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">{t('models.importSettings')}</Menu.ItemText>
+ </Menu.Item>
+ <input
+ accept="application/json,.json"
+ hidden
+ ref={fileInputRef}
+ type="file"
+ onChange={(event) => void handleFileChange(event)}
+ />
+ </>
+ );
+};
+
+const fetchImageAsDataUrl = async (url: string): Promise<string | null> => {
+ try {
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ return null;
+ }
+
+ const blob = await response.blob();
+
+ if (!blob.type.startsWith('image/')) {
+ return null;
+ }
+
+ return await new Promise<string | null>((resolve) => {
+ const reader = new FileReader();
+
+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : null);
+ reader.onerror = () => resolve(null);
+ reader.readAsDataURL(blob);
+ });
+ } catch {
+ return null;
+ }
+};