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.

9.5 KB
Raw Blame
import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';
import type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';

import { Box, Stack } from '@chakra-ui/react';
import {
  getComponentSectionPolicy,
  getComponentSlotIssue,
  type ComponentPolicyContext,
  type ComponentSlotPolicy,
} from '@features/generation/core/baseGenerationPolicies';
import { describeGenerationIssue } from '@features/generation/core/generationIssues';
import {
  DEFAULT_ANIMA_INPAINT_ADAPTER_WEIGHT,
  isMainModelConfig,
  isModelIdentifierConfig,
  isVaeModelConfig,
  MAX_ANIMA_INPAINT_ADAPTER_WEIGHT,
  MIN_ANIMA_INPAINT_ADAPTER_WEIGHT,
} from '@features/generation/core/settings';
import { useExternalStoreSelector } from '@platform/state/selectors';
import { Field } from '@platform/ui';
import { ScrubberField } from '@platform/ui/ScrubberField';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { type GenerateDraft, pickGenerateSettings } from './generateDebounce';
import { GenerationModelSelect as ModelSelect } from './GenerationUiContext';
import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';
import { GenerateIssueNotes, useGenerateSectionIssues } from './shared/GenerateIssues';
import { GenerateToggleSwitch } from './shared/GenerateToggleSwitch';

interface GenerateComponentsSectionProps {
  draft: GenerateDraft;
  selectedModel: GenerateModelConfig | undefined;
  onCommit: (patch: Partial<GenerateSettings>) => void;
}

const toComponentModel = (model: ModelConfig | null): ComponentModelConfig | null =>
  isModelIdentifierConfig(model) ? model : null;

const selectComponentSettings = pickGenerateSettings([
  'animaInpaintAdapterEnabled',
  'animaInpaintAdapterModel',
  'animaInpaintAdapterWeight',
  'clipEmbedModel',
  'clipGEmbedModel',
  'clipLEmbedModel',
  'componentSourceModel',
  'flux3PromptUpsamplerEnabled',
  'flux3PromptUpsamplerModel',
  'gemma2EncoderModel',
  'ideogram4UnconditionalModel',
  'mistralEncoderModel',
  'pidDecoderModel',
  'pidMode',
  'qwen35EncoderModel',
  'qwen3EncoderModel',
  'qwen3VLEncoderModel',
  'qwen3VLVisionTowerModel',
  'qwenVLEncoderModel',
  't5EncoderModel',
  'vae',
  'wanLowNoiseModel',
  'wanT5EncoderModel',
]);

type ComponentSettings = ReturnType<typeof selectComponentSettings>;

const getComponentPolicyContext = (
  model: GenerateModelConfig,
  settings: ComponentSettings
): ComponentPolicyContext => ({
  model,
  settings,
  selectedComponents: {
    clipEmbedModel: settings.clipEmbedModel,
    clipGEmbedModel: settings.clipGEmbedModel,
    clipLEmbedModel: settings.clipLEmbedModel,
    componentSourceModel: settings.componentSourceModel,
    mistralEncoderModel: settings.mistralEncoderModel,
    qwen3EncoderModel: settings.qwen3EncoderModel,
    qwenVLEncoderModel: settings.qwenVLEncoderModel,
    qwen3VLEncoderModel: settings.qwen3VLEncoderModel,
    qwen3VLVisionTowerModel: settings.qwen3VLVisionTowerModel,
    qwen35EncoderModel: settings.qwen35EncoderModel,
    animaInpaintAdapterModel: settings.animaInpaintAdapterModel,
    flux3PromptUpsamplerModel: settings.flux3PromptUpsamplerModel,
    wanT5EncoderModel: settings.wanT5EncoderModel,
    wanLowNoiseModel: settings.wanLowNoiseModel,
    ideogram4UnconditionalModel: settings.ideogram4UnconditionalModel,
    t5EncoderModel: settings.t5EncoderModel,
    pidDecoderModel: settings.pidDecoderModel,
    gemma2EncoderModel: settings.gemma2EncoderModel,
    vae: settings.vae,
  },
});

const ComponentPicker = ({
  ctx,
  onChange,
  slot,
}: {
  ctx: ComponentPolicyContext;
  onChange: (model: ModelConfig | null) => void;
  slot: ComponentSlotPolicy;
}) => {
  const { t } = useTranslation();
  const value = ctx.selectedComponents[slot.key];
  const filter = useCallback((model: ModelConfig) => slot.filter?.(model, ctx) ?? false, [ctx, slot]);
  const modelTypes = useMemo(() => [...slot.modelTypes], [slot.modelTypes]);
  const isIncompatible = Boolean(value && slot.filter && !filter(value as ModelConfig));
  const isRequired = Boolean(slot.required?.(ctx));
  const slotIssue = getComponentSlotIssue(slot, ctx);
  // Issues other rules aim at this slot (references that need the tower) show here too, beside its own message.
  const componentIssues = useGenerateSectionIssues('components');
  const fieldIssues = useMemo(
    () => componentIssues.filter((issue) => issue.target.field === slot.key),
    [componentIssues, slot.key]
  );
  const shownIssue = fieldIssues.find((issue) => issue.message === slotIssue) ?? fieldIssues[0];
  const error = slotIssue ?? (shownIssue ? describeGenerationIssue(t, shownIssue) : undefined);
  // A slot that names an incompatible selection keeps it visible, so the error has a value to point at and clear.
  const selectedValue = value && (!isIncompatible || slot.incompatibleMessage) ? value.key : null;

  return (
    // A fix button carries the issue id itself; without one this wrapper does, so a reveal lands on the slot.
    <Box data-issue-id={shownIssue && !shownIssue.fix ? shownIssue.id : undefined}>
      <Field label={slot.label} labelPlacement="inside" helpText={slot.helpText} error={error}>
        <ModelSelect
          filter={slot.filter ? filter : undefined}
          invalid={Boolean(error)}
          isClearable
          modelTypes={modelTypes}
          placeholder={
            isRequired
              ? t('widgets.generate.selectComponent')
              : (slot.placeholder ?? t('widgets.generate.modelDefault'))
          }
          relatedTo={ctx.model.key}
          value={selectedValue}
          onChange={onChange}
        />
      </Field>
      <GenerateIssueNotes field={slot.key} fixesOnly section="components" />
    </Box>
  );
};

export const GenerateComponentsSection = ({ draft, onCommit, selectedModel }: GenerateComponentsSectionProps) => {
  const { t } = useTranslation();
  const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectComponentSettings);
  const ctx = useMemo(
    () => (selectedModel ? getComponentPolicyContext(selectedModel, settings) : null),
    [selectedModel, settings]
  );

  const commitSlotValue = useCallback(
    (slot: ComponentSlotPolicy, model: ModelConfig | null) => {
      if (slot.valueKind === 'main') {
        onCommit({ [slot.key]: isMainModelConfig(model) ? model : null });
        return;
      }

      if (slot.valueKind === 'vae') {
        onCommit({ [slot.key]: isVaeModelConfig(model) ? model : null });
        return;
      }

      onCommit({ [slot.key]: toComponentModel(model) });
    },
    [onCommit]
  );

  if (!selectedModel || selectedModel.type === 'external_image_generator') {
    return null;
  }

  const policy = getComponentSectionPolicy(selectedModel, settings);

  if (policy.slots.length === 0) {
    return null;
  }

  return (
    <GenerateCollapsibleSection
      label={t('widgets.generate.components')}
      defaultOpen={policy.defaultOpen}
      sectionId="components"
    >
      <Stack gap="2.5">
        {policy.slots.map((slot) => (
          <ComponentPickerRow key={slot.key} commitSlotValue={commitSlotValue} ctx={ctx!} slot={slot} />
        ))}
        {settings.animaInpaintAdapterModel && policy.slots.some((slot) => slot.key === 'animaInpaintAdapterModel') ? (
          <AnimaInpaintAdapterControls
            enabled={settings.animaInpaintAdapterEnabled}
            weight={settings.animaInpaintAdapterWeight}
            onCommit={onCommit}
          />
        ) : null}
        <GenerateIssueNotes section="components" />
      </Stack>
    </GenerateCollapsibleSection>
  );
};

/** The legacy slider spanned 0 to 2 with these stops; typed values may use the node's full range. */
const ANIMA_INPAINT_ADAPTER_WEIGHT_MARKS = [0, 1, 2];

/** Switching the adapter off keeps its selection and weight, so switching back on restores them. */
const AnimaInpaintAdapterControls = ({
  enabled,
  onCommit,
  weight,
}: {
  enabled: boolean;
  onCommit: (patch: Partial<GenerateSettings>) => void;
  weight: number;
}) => {
  const { t } = useTranslation();
  const onEnabledChange = useCallback(
    (checked: boolean) => onCommit({ animaInpaintAdapterEnabled: checked }),
    [onCommit]
  );
  const onWeightChange = useCallback(
    (value: number) => {
      if (Number.isFinite(value)) {
        onCommit({ animaInpaintAdapterWeight: value });
      }
    },
    [onCommit]
  );

  return (
    <Stack gap="1.5">
      <GenerateToggleSwitch
        checked={enabled}
        helpText={enabled ? undefined : t('widgets.generate.animaInpaintAdapterOffHelp')}
        label={t('widgets.generate.animaInpaintAdapterEnabled')}
        onCheckedChange={onEnabledChange}
      />
      <ScrubberField
        defaultValue={DEFAULT_ANIMA_INPAINT_ADAPTER_WEIGHT}
        disabled={!enabled}
        inputMax={MAX_ANIMA_INPAINT_ADAPTER_WEIGHT}
        inputMin={MIN_ANIMA_INPAINT_ADAPTER_WEIGHT}
        label={t('widgets.generate.animaInpaintAdapterWeight')}
        marks={ANIMA_INPAINT_ADAPTER_WEIGHT_MARKS}
        max={2}
        min={0}
        step={0.05}
        value={weight}
        onChange={onWeightChange}
      />
    </Stack>
  );
};

const ComponentPickerRow = ({
  commitSlotValue,
  ctx,
  slot,
}: {
  commitSlotValue: (slot: ComponentSlotPolicy, model: ModelConfig | null) => void;
  ctx: ComponentPolicyContext;
  slot: ComponentSlotPolicy;
}) => {
  const onChange = useCallback((model: ModelConfig | null) => commitSlotValue(slot, model), [commitSlotValue, slot]);

  return <ComponentPicker ctx={ctx} slot={slot} onChange={onChange} />;
};