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.

23.4 KB
Raw Blame
/* 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 { chakra, DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text } from '@chakra-ui/react';
import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';
import {
  supportsExternalModelSettings,
  type ExternalModelSettingsModel,
} from '@features/models/core/externalModelFields';
import { isSafeUrl } from '@features/models/core/modelSettingsIO';
import { isLinkableModel } from '@features/models/core/relationships';
import { isAbsoluteModelPath, resolveModelAbsolutePath } from '@features/models/core/schemas';
import {
  getModelSourceHref,
  getModelTypeLabel,
  getModelVariantLabel,
  getUnrecordedModelFact,
} from '@features/models/core/taxonomy';
import { supportsWorkingMemoryCalibration } from '@features/models/core/workingMemory';
import { useModelsSelector, type ModelsSnapshot } from '@features/models/data/modelsStore';
import {
  discardModelDraft,
  openModelIdentityDraft,
  useModelDraft,
  type ModelDraft,
} from '@features/models/ui/modelDraftsStore';
import { useModelsUi } from '@features/models/ui/ModelsUiContext';
import { ModelActionMenuItems, type PendingModelAction } from '@features/models/ui/shared/ModelActionsMenu';
import { useNotify } from '@features/models/ui/useModelsNotify';
import { formatBytes } from '@platform/i18n/languages';
import { useExitPresence } from '@platform/react/useExitRetainedValue';
import { areArraysEqual } from '@platform/state/selectors';
import { Button, IconButton, MenuContent } from '@platform/ui';
import { HuggingFaceIcon } from '@platform/ui/VendoredIcon';
import { ExternalLinkIcon, MoreHorizontalIcon, PencilIcon } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { CpuOnlySetting, supportsCpuOnlySetting } from './CpuOnlySetting';
import { supportsDefaultSettings, type DefaultSettingsModel } from './defaultSettingsFields';
import { DefaultSettingsSection } from './DefaultSettingsSection';
import { ExternalModelSection } from './ExternalModelSection';
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 { UnrecordedFactNotice } from './UnrecordedFactNotice';
import { UpdatePathDialog } from './UpdatePathDialog';
import { WorkingMemorySection } from './WorkingMemorySection';

const EMPTY_TRIGGER_PHRASES: readonly string[] = [];

type ModelDetailShellModel = Pick<ModelConfig, 'key' | 'roles' | 'type'> & {
  hasCpuOnlySetting: boolean;
  hasTriggerPhrases: boolean;
};
type TriggerPhrasesModel = Pick<ModelConfig, 'key' | 'trigger_phrases'>;
type CpuOnlyModel = Pick<ModelConfig, 'cpu_only' | 'key' | 'name' | 'type'>;
type ModelIdentityModel = Pick<
  ModelConfig,
  | 'base'
  | 'cond_in_channels'
  | 'config_path'
  | 'cover_image'
  | 'description'
  | 'file_size'
  | 'format'
  | 'hash'
  | 'image_encoder_model_id'
  | 'key'
  | 'name'
  | 'path'
  | 'prediction_type'
  | 'provider_id'
  | 'provider_model_id'
  | 'repo_variant'
  | 'roles'
  | 'scale'
  | 'source'
  | 'source_type'
  | 'source_url'
  | 'source_urls'
  | 'type'
  | 'variant'
>;

const isIdentityEditorOpen = (draft: ModelDraft | undefined): boolean => draft?.identity !== undefined;

const findModel = (snapshot: ModelsSnapshot, modelKey: string): ModelConfig | undefined =>
  snapshot.modelsByKey.get(modelKey);

const selectModelShell = (snapshot: ModelsSnapshot, modelKey: string): ModelDetailShellModel | null => {
  const model = findModel(snapshot, modelKey);

  // The backend serializes `cpu_only` and `trigger_phrases` (null when unset) on exactly the configs that store them,
  // so presence decides which editors appear. Control LoRAs store `trigger_phrases` but prompt triggers never read
  // them, so they get no editor. Flags rather than the values, so editing them does not re-render the whole detail.
  return model
    ? {
        hasCpuOnlySetting: supportsCpuOnlySetting(model),
        hasTriggerPhrases: model.trigger_phrases !== undefined && model.type !== 'control_lora',
        key: model.key,
        roles: model.roles,
        type: model.type,
      }
    : null;
};

const selectModelIdentity = (snapshot: ModelsSnapshot, modelKey: string): ModelIdentityModel | null => {
  const model = findModel(snapshot, modelKey);

  return model
    ? {
        base: model.base,
        cond_in_channels: model.cond_in_channels,
        config_path: model.config_path,
        cover_image: model.cover_image,
        description: model.description,
        file_size: model.file_size,
        format: model.format,
        hash: model.hash,
        image_encoder_model_id: model.image_encoder_model_id,
        key: model.key,
        name: model.name,
        path: model.path,
        prediction_type: model.prediction_type,
        provider_id: model.provider_id,
        provider_model_id: model.provider_model_id,
        repo_variant: model.repo_variant,
        roles: model.roles,
        scale: model.scale,
        source: model.source,
        source_type: model.source_type,
        source_url: model.source_url,
        source_urls: model.source_urls,
        type: model.type,
        variant: model.variant,
      }
    : null;
};

const selectDefaultSettingsModel = (snapshot: ModelsSnapshot, modelKey: string): DefaultSettingsModel | null => {
  const model = findModel(snapshot, modelKey);

  // `base` and `format` are projected too: together with the type they are the loader key the backend answers the FP8
  // Storage question on, and all three parts change the answer. `variant` joins them for Generate's scheduler rules,
  // which differ by variant within a base; `name` and `submodels` join them for its component rules.
  return model
    ? {
        base: model.base,
        default_settings: model.default_settings,
        format: model.format,
        key: model.key,
        name: model.name,
        submodels: model.submodels,
        type: model.type,
        variant: model.variant,
      }
    : null;
};

const selectExternalModel = (snapshot: ModelsSnapshot, modelKey: string): ExternalModelSettingsModel | null => {
  const model = findModel(snapshot, modelKey);

  return model
    ? {
        capabilities: model.capabilities,
        default_settings: model.default_settings,
        key: model.key,
        name: model.name,
        provider_id: model.provider_id,
        provider_model_id: model.provider_model_id,
        source: model.source,
        type: model.type,
      }
    : null;
};

const selectTriggerPhrasesModel = (snapshot: ModelsSnapshot, modelKey: string): TriggerPhrasesModel | null => {
  const model = findModel(snapshot, modelKey);

  return model ? { key: model.key, trigger_phrases: model.trigger_phrases } : null;
};

const selectCpuOnlyModel = (snapshot: ModelsSnapshot, modelKey: string): CpuOnlyModel | null => {
  const model = findModel(snapshot, modelKey);

  return model ? { cpu_only: model.cpu_only, key: model.key, name: model.name, type: model.type } : null;
};

const areTriggerPhrasesModelsEqual = (left: TriggerPhrasesModel | null, right: TriggerPhrasesModel | null): boolean =>
  left?.key === right?.key && areArraysEqual(left?.trigger_phrases ?? [], right?.trigger_phrases ?? []);

type RequestModelActionConfirm = (pending: NonNullable<PendingModelAction>) => void;

/**
 * Mount keyed by model key so detail forms cannot leak state between models. The host owns the confirmation dialog
 * because a delete unmounts this detail before the dialog finishes closing.
 */
export const ModelDetail = ({
  modelKey,
  onRequestConfirm,
}: {
  modelKey: string;
  onRequestConfirm: RequestModelActionConfirm;
}) => {
  const { t } = useTranslation();
  const model = useModelsSelector((snapshot) => selectModelShell(snapshot, modelKey));
  const { canManageModels } = useModelsUi();

  if (!model) {
    return (
      <Stack align="start" gap="2" p="1">
        <Text color="fg.subtle" fontSize="md">
          {t('models.modelNoLongerInLibrary')}
        </Text>
      </Stack>
    );
  }

  return (
    <Stack gap="4" pb="4">
      <ModelIdentitySectionContainer modelKey={model.key} onRequestConfirm={onRequestConfirm} />

      {model.hasCpuOnlySetting ? (
        <>
          <Separator borderColor="border.subtle" />
          <CpuOnlySettingContainer modelKey={model.key} />
        </>
      ) : null}

      {supportsExternalModelSettings(model) ? (
        <>
          <Separator borderColor="border.subtle" />
          <ExternalModelSectionContainer modelKey={model.key} />
        </>
      ) : null}

      {supportsDefaultSettings(model) ? (
        <>
          <Separator borderColor="border.subtle" />
          <DefaultSettingsSectionContainer modelKey={model.key} />
        </>
      ) : null}

      {isLinkableModel(model) ? (
        <>
          <Separator borderColor="border.subtle" />
          <RelatedModelsSectionContainer modelKey={model.key} />
        </>
      ) : null}

      {model.hasTriggerPhrases ? (
        <>
          <Separator borderColor="border.subtle" />
          <TriggerPhrasesEditorContainer modelKey={model.key} />
        </>
      ) : null}

      {/* Last and collapsed: calibration is a rare, admin-only task. */}
      {canManageModels && supportsWorkingMemoryCalibration(model) ? (
        <>
          <Separator borderColor="border.subtle" />
          <WorkingMemorySection modelKey={model.key} />
        </>
      ) : null}
    </Stack>
  );
};

interface ModelIdentitySectionProps {
  isMissing: boolean;
  model: ModelIdentityModel;
  onRequestConfirm: RequestModelActionConfirm;
}

const ModelIdentitySectionContainer = memo(function ModelIdentitySectionContainer({
  modelKey,
  onRequestConfirm,
}: {
  modelKey: string;
  onRequestConfirm: RequestModelActionConfirm;
}) {
  const model = useModelsSelector((snapshot) => selectModelIdentity(snapshot, modelKey));
  const isMissing = useModelsSelector((snapshot) => snapshot.missingModelKeys.has(modelKey));

  if (!model) {
    return null;
  }

  return <ModelIdentitySection isMissing={isMissing} model={model} onRequestConfirm={onRequestConfirm} />;
});

const ModelIdentitySection = memo(function ModelIdentitySection({
  isMissing,
  model,
  onRequestConfirm,
}: ModelIdentitySectionProps) {
  const notify = useNotify();
  const { t } = useTranslation();
  const { canManageModels } = useModelsUi();
  const unrecordedFact = getUnrecordedModelFact(model);
  // The open editor lives with the model's retained draft, so it survives leaving the pane and coming back.
  const isEditing = useModelDraft(model.key, isIdentityEditorOpen);

  return (
    <>
      {/* Below about 34rem the actions wrap under the title rather than crush it. */}
      <HStack align="start" gap="3" wrap="wrap">
        <ModelImageUpload
          key={model.key}
          model={model}
          onError={(message) => notify.error(t('models.modelImage'), message)}
          onUpdated={() => notify.success(t('models.modelImageUpdated'))}
        />
        <Stack flex="1 1 10rem" gap="1" minW="0">
          <Text fontSize="lg" fontWeight="700" lineClamp={2}>
            {model.name}
          </Text>
          <HStack gap="1" minW="0" wrap="wrap">
            <ModelBaseBadge base={model.base} />
            <ModelFormatBadge format={model.format} />
          </HStack>
          {isMissing ? (
            <HStack gap="1.5">
              <MissingFileBadge />
              <Text color="fg.subtle" fontSize="xs">
                {t('models.fileNotFoundOnDisk')}
              </Text>
            </HStack>
          ) : null}
          {model.description ? (
            <Text color="fg.muted" fontSize="xs" lineClamp={3}>
              {model.description}
            </Text>
          ) : null}
        </Stack>
        <ModelDetailActions
          isEditing={isEditing}
          model={model}
          onRequestConfirm={onRequestConfirm}
          onToggleEditing={() =>
            isEditing ? discardModelDraft(model.key, 'identity') : openModelIdentityDraft(model.key)
          }
        />
      </HStack>

      {unrecordedFact ? (
        <UnrecordedFactNotice
          fact={unrecordedFact}
          onReidentify={canManageModels ? () => onRequestConfirm({ kind: 'reidentify', model }) : null}
        />
      ) : null}

      {isEditing ? (
        <ModelEditForm
          model={model}
          onCancel={() => discardModelDraft(model.key, 'identity')}
          // The draft store settles the save itself, closing the editor unless edits were made meanwhile.
          onSaved={() => notify.success(t('models.modelUpdated'), model.name)}
        />
      ) : (
        <ModelAttributes isMissing={isMissing} model={model} />
      )}
    </>
  );
});

const ModelDetailActions = ({
  isEditing,
  model,
  onRequestConfirm,
  onToggleEditing,
}: {
  isEditing: boolean;
  model: ModelIdentityModel;
  onRequestConfirm: RequestModelActionConfirm;
  onToggleEditing: () => void;
}) => {
  const { t } = useTranslation();
  const [isActionBusy, setIsActionBusy] = useState(false);

  return (
    <HStack flexShrink={0} gap="1" justify="flex-end" ms="auto" wrap="wrap">
      {isConvertibleToDiffusers(model) ? (
        <Button variant="outline" onClick={() => onRequestConfirm({ kind: 'convert', model })}>
          <Icon as={HuggingFaceIcon} boxSize="3" />
          {t('models.convertToDiffusers')}
        </Button>
      ) : null}
      <Button variant={isEditing ? 'solid' : 'outline'} onClick={onToggleEditing}>
        <Icon as={PencilIcon} boxSize="3" />
        {isEditing ? t('models.editing') : t('common.edit')}
      </Button>
      <Menu.Root positioning={{ placement: 'bottom-end' }}>
        <Menu.Trigger asChild>
          <IconButton
            aria-label={t('models.actions')}
            data-model-actions-trigger=""
            loading={isActionBusy}
            variant="ghost"
          >
            <Icon as={MoreHorizontalIcon} boxSize="4" />
          </IconButton>
        </Menu.Trigger>
        <Portal>
          <Menu.Positioner>
            <MenuContent minW="12rem">
              <ModelActionMenuItems
                extraItems={<ModelSettingsMenuItems modelKey={model.key} />}
                model={model}
                onBusyChange={setIsActionBusy}
                onRequestConfirm={onRequestConfirm}
              />
            </MenuContent>
          </Menu.Positioner>
        </Portal>
      </Menu.Root>
    </HStack>
  );
};

const DefaultSettingsSectionContainer = memo(function DefaultSettingsSectionContainer({
  modelKey,
}: {
  modelKey: string;
}) {
  const notify = useNotify();
  const { t } = useTranslation();
  const model = useModelsSelector((snapshot) => selectDefaultSettingsModel(snapshot, modelKey));

  if (!model || !supportsDefaultSettings(model)) {
    return null;
  }

  return (
    <DefaultSettingsSection
      model={model}
      onError={(message) => notify.error(t('models.defaultSettings'), message)}
      onSaved={() => notify.success(t('models.defaultSettingsSaved'))}
    />
  );
});

const ExternalModelSectionContainer = memo(function ExternalModelSectionContainer({ modelKey }: { modelKey: string }) {
  const notify = useNotify();
  const { t } = useTranslation();
  const model = useModelsSelector((snapshot) => selectExternalModel(snapshot, modelKey));

  if (!model || !supportsExternalModelSettings(model)) {
    return null;
  }

  return (
    <ExternalModelSection
      model={model}
      onError={(message) => notify.error(t('models.externalProvider'), message)}
      onSaved={() => notify.success(t('models.externalSettingsSaved'))}
    />
  );
});

const CpuOnlySettingContainer = memo(function CpuOnlySettingContainer({ modelKey }: { modelKey: string }) {
  const notify = useNotify();
  const { t } = useTranslation();
  const model = useModelsSelector((snapshot) => selectCpuOnlyModel(snapshot, modelKey));

  if (!model || !supportsCpuOnlySetting(model)) {
    return null;
  }

  return (
    <CpuOnlySetting
      model={model}
      onError={(message) => notify.error(t('models.failedToSaveCpuSetting'), message)}
      onSaved={() => notify.success(t('models.cpuSettingSaved'), model.name)}
    />
  );
});

const TriggerPhrasesEditorContainer = memo(function TriggerPhrasesEditorContainer({ modelKey }: { modelKey: string }) {
  const notify = useNotify();
  const { t } = useTranslation();
  const handleError = useCallback((message: string) => notify.error(t('models.triggerPhrases'), message), [notify, t]);
  const model = useModelsSelector(
    (snapshot) => selectTriggerPhrasesModel(snapshot, modelKey),
    areTriggerPhrasesModelsEqual
  );

  if (!model) {
    return null;
  }

  return (
    <MemoizedTriggerPhrasesEditor
      modelKey={model.key}
      phrases={model.trigger_phrases ?? EMPTY_TRIGGER_PHRASES}
      onError={handleError}
    />
  );
});

const RelatedModelsSectionContainer = memo(function RelatedModelsSectionContainer({ modelKey }: { modelKey: string }) {
  const notify = useNotify();
  const { t } = useTranslation();
  const model = useModelsSelector(
    (snapshot) => {
      const candidate = snapshot.modelsByKey.get(modelKey);

      return candidate
        ? {
            base: candidate.base,
            key: candidate.key,
            latent_channels: candidate.latent_channels,
            roles: candidate.roles,
            type: candidate.type,
            variant: candidate.variant,
          }
        : null;
    },
    (left, right) =>
      left?.key === right?.key &&
      left?.base === right?.base &&
      left?.type === right?.type &&
      left?.variant === right?.variant &&
      left?.latent_channels === right?.latent_channels &&
      left?.roles === right?.roles
  );
  const handleSectionError = useCallback(
    (message: string) => notify.error(t('models.modelManager'), message),
    [notify, t]
  );

  if (!model) {
    return null;
  }

  return <RelatedModelsSection model={model} onError={handleSectionError} />;
});

const AttributeValue = ({ href, value }: { href: string | undefined; value: string }) =>
  href ? (
    <chakra.a
      alignItems="center"
      display="inline-flex"
      gap="1"
      href={href}
      minW="0"
      rel="noreferrer"
      target="_blank"
      wordBreak="break-all"
      _hover={{ textDecoration: 'underline' }}
    >
      {value}
      <Icon as={ExternalLinkIcon} boxSize="3" color="fg.subtle" flexShrink={0} />
    </chakra.a>
  ) : (
    value
  );

const ModelAttributes = ({ isMissing, model }: { isMissing: boolean; model: ModelIdentityModel }) => {
  const { i18n, t } = useTranslation();
  const modelsDir = useModelsSelector((snapshot) => snapshot.modelsDir);
  const [isPathDialogOpen, setIsPathDialogOpen] = useState(false);
  const pathDialog = useExitPresence(isPathDialogOpen);
  // Managed models store paths relative to the models directory; show the resolved absolute path so it can be found on
  // disk.
  const fullPath = resolveModelAbsolutePath(model.path, modelsDir);
  // Allow repointing absolute-path installs, including missing files.
  const canUpdatePath = isAbsoluteModelPath(model.path) || isMissing;

  const sourceHref = getModelSourceHref(model.source, model.source_type);
  const modelPages = [...new Set(model.source_urls ?? [])].filter(
    (url) => url !== model.source_url && url !== sourceHref
  );

  const attributes: ({ action?: ReactNode; label: string } & (
    | { href?: string; value: string }
    | { links: readonly 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 ?? '—' },
    ...(model.roles?.length
      ? [
          {
            label: t('models.alsoUsableAs'),
            value: new Intl.ListFormat(i18n.resolvedLanguage, { style: 'long', type: 'conjunction' }).format(
              model.roles.map((role) =>
                role.variant
                  ? `${getModelTypeLabel(role.type)} · ${getModelVariantLabel(role.variant)}`
                  : getModelTypeLabel(role.type)
              )
            ),
          },
        ]
      : []),
    // Recorded by the probe for upscalers; an unrecorded one is explained by the notice above instead.
    ...(typeof model.scale === 'number'
      ? [{ label: t('models.nativeScale'), value: t('models.nativeScaleValue', { scale: model.scale }) }]
      : []),
    { label: t('models.hash'), value: model.hash },
    {
      action: canUpdatePath ? (
        <IconButton
          aria-label={t('models.updatePath')}
          size="sm"
          variant="ghost"
          onClick={() => setIsPathDialogOpen(true)}
        >
          <Icon as={PencilIcon} boxSize="3" />
        </IconButton>
      ) : undefined,
      label: t('models.path'),
      value: fullPath,
    },
    {
      href: sourceHref ?? undefined,
      label: t('models.source'),
      value: model.source,
    },
    ...(model.source_url
      ? [
          {
            href: isSafeUrl(model.source_url) ? model.source_url : undefined,
            label: t('models.sourceUrl'),
            value: model.source_url,
          },
        ]
      : []),
    ...(modelPages.length ? [{ label: t('models.modelPage', { count: modelPages.length }), links: modelPages }] : []),
    // Format-specific attrs; truthiness also skips repo_variant's '' default.
    ...(model.format === 'diffusers' && model.repo_variant
      ? [{ label: t('models.repoVariant'), value: model.repo_variant }]
      : []),
    ...(model.format === 'checkpoint' && model.config_path
      ? [{ label: t('models.configPath'), value: model.config_path }]
      : []),
    ...(model.image_encoder_model_id
      ? [{ label: t('models.imageEncoderModelId'), value: model.image_encoder_model_id }]
      : []),
    ...(model.provider_id ? [{ label: t('models.providerId'), value: model.provider_id }] : []),
    ...(model.provider_model_id ? [{ label: t('models.providerModelId'), value: model.provider_model_id }] : []),
  ];

  return (
    <>
      <DataList.Root gap="2.5" orientation="horizontal" variant="subtle">
        {attributes.map((attribute) => (
          <DataList.Item key={attribute.label}>
            <DataList.ItemLabel color="fg.muted" fontSize="xs" minW="8rem" textTransform="uppercase">
              {attribute.label}
            </DataList.ItemLabel>
            <DataList.ItemValue alignItems="center" display="flex" fontSize="xs" gap="1" overflowWrap="anywhere">
              {'links' in attribute ? (
                <Stack alignItems="flex-start" gap="1" minW="0">
                  {attribute.links.map((url) => (
                    <AttributeValue key={url} href={isSafeUrl(url) ? url : undefined} value={url} />
                  ))}
                </Stack>
              ) : (
                <AttributeValue href={attribute.href} value={attribute.value} />
              )}
              {attribute.action ?? null}
            </DataList.ItemValue>
          </DataList.Item>
        ))}
      </DataList.Root>
      {pathDialog.isMounted ? (
        <UpdatePathDialog
          key={pathDialog.generation}
          isOpen={pathDialog.isOpen}
          model={model}
          onClose={() => setIsPathDialogOpen(false)}
          onExitComplete={pathDialog.release}
        />
      ) : null}
    </>
  );
};