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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(models): relocate in-place model paths from the detail pane
joshistoast6389ee1a5093
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 2acdce91b1..7a80ae56a6 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -842,6 +842,7 @@"bundleInstallQueuedDescription_other": "{{name}}: {{count}} installs queued.","bytePlusApiKeyPlaceholder": "API key from BytePlus console","cacheEmptied": "Model cache emptied",+ "currentPath": "Current path","cancelAllInstalls": "Cancel all installs","cancelFailed": "Cancel failed","cancelInstall": "Cancel install",@@ -966,6 +967,7 @@"installsDependencies_one": " (installs {{count}} dependency)","installsDependencies_other": " (installs {{count}} dependencies)","invalidDefaultSettings": "Invalid default settings.",+ "invalidPathFormat": "Must be an absolute path.","invalidTriggerPhrase": "Invalid trigger phrase.","keyStatus": {"configured": "Configured",@@ -1015,6 +1017,8 @@"noInstallsYet": "No installs yet","noModelFilesFound": "No model files found in {{path}}.","noModelFilesFoundTitle": "No model files found",+ "newPath": "New path",+ "newPathPlaceholder": "/absolute/path/to/model.safetensors","noOrphaned": "No orphaned model folders found — your library is clean.","noRelatedModels": "No related models linked yet.","noStarterModelsPull": "No starter models match - press Pull to install the source you entered.",@@ -1033,6 +1037,8 @@"orphanedTitle": "Orphaned Models","overrideBaseUrl": "Override base URL","path": "Path",+ "pathUpdateFailed": "Failed to update path",+ "pathUpdated": "Path updated","pauseAllDownloads": "Pause all downloads","pauseAllInstalls": "Pause all installs","pauseDownload": "Pause download",@@ -1131,6 +1137,8 @@"type": "Type","unlink": "Unlink","unlinkNamed": "Unlink {{name}}",+ "updatePath": "Update path",+ "updatePathDescription": "If the model file moved on disk, point Invoke at its new location. The file is not moved or copied.","uploadCoverImageFor": "Upload cover image for {{name}}","useSupportedImage": "Use a PNG, JPEG, or WebP image.","vaeCpuSettingSaved": "VAE CPU setting saved",diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.test.tsnew file mode 100644index 0000000000..58219c6ba3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';++import { isAbsoluteModelPath, modelPathSchema } from './schemas';++describe('isAbsoluteModelPath', () => {+ it.each([+ '/models/sdxl.safetensors',+ 'C:\\models\\sdxl.safetensors',+ 'C:/models/sdxl.safetensors',+ '\\\\nas\\models\\x.ckpt',+ ])('accepts the absolute path %s', (path) => {+ expect(isAbsoluteModelPath(path)).toBe(true);+ });++ it.each(['models/sdxl.safetensors', './models/sdxl.safetensors', '../x.ckpt', 'sdxl.safetensors', ''])(+ 'rejects the relative path %j',+ (path) => {+ expect(isAbsoluteModelPath(path)).toBe(false);+ }+ );+});++describe('modelPathSchema', () => {+ it('trims and accepts an absolute path', () => {+ expect(modelPathSchema.parse(' /models/x.safetensors ')).toBe('/models/x.safetensors');+ });++ it('rejects empty and relative paths', () => {+ expect(modelPathSchema.safeParse(' ').success).toBe(false);+ expect(modelPathSchema.safeParse('models/x.safetensors').success).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/core/schemas.ts b/invokeai/frontend/webv2/src/features/models/core/schemas.tsindex 150554735c..8351193f0d 100644--- a/invokeai/frontend/webv2/src/features/models/core/schemas.ts+++ b/invokeai/frontend/webv2/src/features/models/core/schemas.ts@@ -90,6 +90,19 @@ export const loraDefaultSettingsSchema = zexport type LoraDefaultSettingsFormValues = z.infer<typeof loraDefaultSettingsSchema>;+/** POSIX (/x), Windows drive (C:\ or C:/), or UNC (\\server) — the shapes in-place installs record. */+export const isAbsoluteModelPath = (path: string): boolean =>+ path.startsWith('/') || path.startsWith('\\\\') || /^[A-Za-z]:[\\/]/.test(path);++/**+ * Replacement path for a relocated model. Only absolute paths are accepted:+ * managed models store paths relative to the models directory and must not be+ * relocated this way.+ */+export const modelPathSchema = trimmed+ .min(1, 'Path is required.')+ .refine(isAbsoluteModelPath, 'Must be an absolute path.');+export const triggerPhraseSchema = trimmed.min(1, 'Trigger phrase cannot be empty.').max(200, 'Keep trigger phrases under 200 characters.');diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tsindex 9c2269a8e3..35b6d66a74 100644--- a/invokeai/frontend/webv2/src/features/models/core/types.ts+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts@@ -144,6 +144,7 @@ export interface ModelConfig {/** Body for PATCH `/api/v2/models/i/{key}` — all fields optional. */export interface ModelRecordChanges {name?: string;+ path?: string;description?: string | null;source_url?: string | null;base?: ModelBase;diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxindex e450e533d1..488f9fb397 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx@@ -1,9 +1,11 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import type { ModelConfig } from '@features/models/core/types';+import type { ReactNode } from 'react';import { DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text } from '@chakra-ui/react';import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';import { isLinkableType } from '@features/models/core/relationships';+import { isAbsoluteModelPath } from '@features/models/core/schemas';import { formatBytes } from '@features/models/core/taxonomy';import { useModelsSelector } from '@features/models/data/modelsStore';import { useNotify } from '@features/models/ui/useModelsNotify';@@ -21,6 +23,7 @@ import { ModelEditForm } from './ModelEditForm';import { ModelImageUpload } from './ModelImageUpload';import { RelatedModelsSection } from './RelatedModelsSection';import { MemoizedTriggerPhrasesEditor } from './TriggerPhrasesEditor';+import { UpdatePathDialog } from './UpdatePathDialog';import { useModelActions } from './useModelActions';import { supportsVaeCpuOnlySetting, VaeCpuOnlySetting } from './VaeCpuOnlySetting';@@ -243,7 +246,7 @@ const ModelIdentitySection = memo(function ModelIdentitySection({}}/>) : (- <ModelAttributes model={model} />+ <ModelAttributes isMissing={isMissing} model={model} />)}</>);@@ -421,37 +424,56 @@ const RelatedModelsSectionContainer = memo(function RelatedModelsSectionContainereturn <RelatedModelsSection model={model} onError={handleSectionError} />;});-const isAbsolutePath = (path: string): boolean => path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path);--const ModelAttributes = ({ model }: { model: ModelIdentityModel }) => {+const ModelAttributes = ({ isMissing, model }: { isMissing: boolean; model: ModelIdentityModel }) => {const { t } = useTranslation();const modelsDir = useModelsSelector((snapshot) => snapshot.modelsDir);+ const [isPathDialogOpen, setIsPathDialogOpen] = useState(false);// Managed models store paths relative to the models directory; show the// resolved absolute path so it can be found on disk.const fullPath =- isAbsolutePath(model.path) || !modelsDir ? model.path : `${modelsDir.replace(/\/+$/, '')}/${model.path}`;+ isAbsoluteModelPath(model.path) || !modelsDir ? model.path : `${modelsDir.replace(/\/+$/, '')}/${model.path}`;+ // In-place installs (absolute paths) may be repointed after the file moves;+ // a missing model gets the affordance too — that is exactly when it helps.+ const canUpdatePath = isAbsoluteModelPath(model.path) || isMissing;- const attributes: { label: string; value: string }[] = [+ const attributes: { action?: ReactNode; label: string; value: string }[] = [{ label: t('models.fileSize'), value: formatBytes(model.file_size) },{ label: t('models.variant'), value: model.variant ?? '—' },{ label: t('models.predictionType'), value: model.prediction_type ?? '—' },{ label: t('models.hash'), value: model.hash },- { label: t('models.path'), value: fullPath },+ {+ action: canUpdatePath ? (+ <IconButton+ aria-label={t('models.updatePath')}+ size="2xs"+ variant="ghost"+ onClick={() => setIsPathDialogOpen(true)}+ >+ <Icon as={PencilIcon} boxSize="3" />+ </IconButton>+ ) : undefined,+ label: t('models.path'),+ value: fullPath,+ },{ label: t('models.source'), value: model.source },];return (- <DataList.Root gap="2.5" orientation="horizontal" size="sm" variant="subtle">- {attributes.map((attribute) => (- <DataList.Item key={attribute.label}>- <DataList.ItemLabel color="fg.subtle" fontSize="2xs" minW="8rem" textTransform="uppercase">- {attribute.label}- </DataList.ItemLabel>- <DataList.ItemValue fontSize="2xs" overflowWrap="anywhere">- {attribute.value}- </DataList.ItemValue>- </DataList.Item>- ))}- </DataList.Root>+ <>+ <DataList.Root gap="2.5" orientation="horizontal" size="sm" variant="subtle">+ {attributes.map((attribute) => (+ <DataList.Item key={attribute.label}>+ <DataList.ItemLabel color="fg.subtle" fontSize="2xs" minW="8rem" textTransform="uppercase">+ {attribute.label}+ </DataList.ItemLabel>+ <DataList.ItemValue alignItems="center" display="flex" fontSize="2xs" gap="1" overflowWrap="anywhere">+ {attribute.value}+ {attribute.action ?? null}+ </DataList.ItemValue>+ </DataList.Item>+ ))}+ </DataList.Root>+ {isPathDialogOpen ? <UpdatePathDialog model={model} onClose={() => setIsPathDialogOpen(false)} /> : null}+ </>);};diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsxnew file mode 100644index 0000000000..caf5d7d25a--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/UpdatePathDialog.tsx@@ -0,0 +1,123 @@+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */+import type { ModelConfig } from '@features/models/core/types';++import { Dialog, Input, Portal, Stack, Text } from '@chakra-ui/react';+import { modelPathSchema } from '@features/models/core/schemas';+import { updateModel } from '@features/models/data/api';+import { 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 { Button, CloseButton, Field } from '@platform/ui';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * Repoints a model whose file moved on disk. The file itself is not moved or+ * copied — only the record's path changes, and only absolute paths are+ * accepted (managed models store paths relative to the models directory).+ */+export const UpdatePathDialog = ({+ model,+ onClose,+}: {+ model: Pick<ModelConfig, 'key' | 'name' | 'path'>;+ onClose: () => void;+}) => {+ const { t } = useTranslation();+ const notify = useNotify();+ const [path, setPath] = useState(model.path);+ const [validationError, setValidationError] = useState<string | null>(null);+ const { isBusy, run } = useScopedAction();++ const handleSave = async () => {+ const parsed = modelPathSchema.safeParse(path);++ if (!parsed.success) {+ setValidationError(parsed.error.issues[0]?.message ?? t('models.invalidPathFormat'));++ return;+ }++ await run(+ async (owner) => {+ const updated = await updateModel(model.key, { path: parsed.data }, owner.signal);++ assertAccountScopeCurrent(owner);+ replaceModelInStore(updated);+ notify.success(t('models.pathUpdated'), model.name);+ onClose();+ },+ (message) => notify.error(t('models.pathUpdateFailed'), message)+ );+ };++ return (+ <Dialog.Root+ open+ placement="center"+ size="md"+ onOpenChange={(event) => {+ if (!event.open) {+ onClose();+ }+ }}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content>+ <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">+ <Stack gap="0.5">+ <Dialog.Title fontSize="sm" fontWeight="700">+ {t('models.updatePath')}+ </Dialog.Title>+ <Text color="fg.subtle" fontSize="2xs">+ {t('models.updatePathDescription')}+ </Text>+ </Stack>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="3" py="2">+ <Field label={t('models.currentPath')}>+ <Text color="fg.muted" fontSize="2xs" overflowWrap="anywhere">+ {model.path}+ </Text>+ </Field>+ <Field error={validationError} label={t('models.newPath')}>+ <Input+ aria-invalid={validationError ? true : undefined}+ placeholder={t('models.newPathPlaceholder')}+ size="sm"+ value={path}+ onChange={(event) => {+ setPath(event.currentTarget.value);+ setValidationError(null);+ }}+ />+ </Field>+ </Stack>+ </Dialog.Body>+ <Dialog.Footer gap="2">+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={onClose}>+ {t('common.cancel')}+ </Button>+ <Button+ disabled={path.trim() === model.path}+ loading={isBusy}+ size="xs"+ variant="solid"+ onClick={() => void handleSave()}+ >+ {t('models.updatePath')}+ </Button>+ </Dialog.Footer>+ <Dialog.CloseTrigger asChild>+ <CloseButton color="fg.muted" size="sm" />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};