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
import type { StarterModel } from '@features/models';
import type { WidgetViewProps } from '@workbench/widgetContracts';
import type { ReactNode } from 'react';
import { Box, Button, Center, Link, Spinner, Stack, Text } from '@chakra-ui/react';
import { getGalleryMediaFilter, toGalleryMediaKind } from '@features/gallery/contracts';
import { useCapabilities } from '@features/identity';
import {
ensureStartersLoaded,
getStarterModelInstallSources,
useActiveInstallSources,
useOpenAddModelsSearch,
useStartersSelector,
} from '@features/models';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
getImageMapClickSelectsCluster,
getImageMapClusterEps,
getImageMapShowClusterLabels,
IMAGE_MAP_MEDIA_FILTER_TRIGGER_ID,
} from '@workbench/image-map/imageMapSettings';
import {
attachImageMapStatusPolling,
attachImageMapViewer,
ensureImageMapLoaded,
imageMapStore,
refreshImageIndexStatus,
refreshImageMapPoints,
requestImageMapRecompute,
setClusterEps,
setClusterLabelsEnabled,
setImageMapMediaKind,
} from '@workbench/image-map/imageMapStore';
import { isIndexing } from '@workbench/image-map/indexProgress';
import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { ClusterSelectionChip } from './ClusterSelectionChip';
import { ImageIndexActivityBadge, ImageIndexProgressPanel } from './ImageIndexProgress';
import { useClearClusterSelection } from './useSelectMapImage';
const CLEAR_CLUSTER_SELECTION_COMMAND = 'image-map.clearClusterSelection';
// In the center area the view selector floats over the content's top-left corner; the shell publishes its height so
// overlays can start below it.
const OVERLAY_COLUMN_TOP = 'calc(var(--chakra-spacing-2) + var(--wb-center-chrome-inset, 0px))';
const MAP_SURFACE_FOCUS_STYLE = { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' } as const;
// Load Plotly only when the map widget is shown.
const ImageMapPlot = lazy(() => import('./ImageMapPlot'));
const handleRefresh = () => {
void refreshImageMapPoints();
// Retry counts as well as points; stale progress is often why retry was requested.
refreshImageIndexStatus();
};
const handleRecompute = () => {
void requestImageMapRecompute();
refreshImageIndexStatus();
};
// Use the configured default model name when older/empty responses cannot name the missing encoder.
const DEFAULT_IMAGE_INDEX_MODEL = 'DFN2B-CLIP-ViT-L-14-39B';
const EMPTY_STARTERS: readonly StarterModel[] = [];
const selectStarterModels = (snapshot: {
response: { starter_models: StarterModel[] } | null;
}): readonly StarterModel[] => snapshot.response?.starter_models ?? EMPTY_STARTERS;
const plotLoadingFallback = (
<Center h="full">
<Spinner size="2xl" />
</Center>
);
/** Show backend embeddings projected by UMAP and colored by cluster; point selection drives Gallery and Preview. */
export const ImageMapWidgetView = ({ runtime }: WidgetViewProps) => {
const { t } = useTranslation();
// Server configuration and installed models are the administrator's; others are told whom to ask.
const { canManageAppConfig, canManageModels } = useCapabilities();
const { data, error, indexCounts, indexUpdatedAt, loadState, renderError } = imageMapStore.useSnapshot();
const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);
const clusterEps = useWidgetValuesSelector('image-map', getImageMapClusterEps);
const showClusterLabels = useWidgetValuesSelector('image-map', getImageMapShowClusterLabels);
const mediaFilter = useWidgetValuesSelector('gallery', getGalleryMediaFilter);
const { gallery: galleryCommands } = useWorkbenchCommands();
// The button leaves with the empty state; focus moves to the header control that owns the filter.
const handleShowAllMedia = useCallback(() => {
document.getElementById(IMAGE_MAP_MEDIA_FILTER_TRIGGER_ID)?.focus();
galleryCommands.updateSettings({ mediaFilter: 'all' });
}, [galleryCommands]);
const clearClusterSelection = useClearClusterSelection();
// Esc while the map owns focus, the keyboard path to the chip's clear.
const { commands: runtimeCommands, hotkeys: runtimeHotkeys } = runtime;
useEffect(() => {
const clearClusterSelectionLabel = t('widgets.imageMap.clearClusterSelection');
const disposers = [
runtimeCommands.register({
handler: clearClusterSelection,
id: CLEAR_CLUSTER_SELECTION_COMMAND,
title: clearClusterSelectionLabel,
}),
runtimeHotkeys.register({
allowInEditable: false,
commandId: CLEAR_CLUSTER_SELECTION_COMMAND,
defaultKeys: ['esc'],
id: CLEAR_CLUSTER_SELECTION_COMMAND,
title: clearClusterSelectionLabel,
}),
];
return () => {
disposers.forEach((dispose) => dispose());
};
}, [clearClusterSelection, runtimeCommands, runtimeHotkeys, t]);
// Before the first load, so it carries the chosen strength rather than fetching at the default and immediately
// refetching.
useEffect(() => {
setClusterEps(clusterEps);
}, [clusterEps]);
useMountEffect(() => {
const detachViewer = attachImageMapViewer();
// Before the first load, like the strength: a cold start under a media filter must not cluster both kinds first.
setImageMapMediaKind(toGalleryMediaKind(mediaFilter));
ensureImageMapLoaded();
const detachPolling = attachImageMapStatusPolling();
return () => {
detachPolling();
detachViewer();
};
});
// Pushed into the store so turning labels off stops the request, not just the drawing of what it returns.
useEffect(() => {
setClusterLabelsEnabled(showClusterLabels);
}, [showClusterLabels]);
// Handle render failure before points so the same broken canvas cannot remount until refresh clears it.
if (renderError) {
return (
<CenteredMessage
actionLabel={t('common.retry')}
detail={renderError}
onAction={handleRefresh}
title={t('widgets.imageMap.unavailableTitle')}
/>
);
}
// A working map beats a full-screen error: when a refresh fails but prior points exist, keep showing them (the next
// successful refresh recovers).
if (data && data.points.length > 0) {
// Keep a nested Suspense boundary around Plotly so its separate lazy load preserves widget chrome and places
// loading feedback in the plot area.
return (
// Overlay indexing status on usable stale points because this branch bypasses the progress panel.
<Box
_focusVisible={MAP_SURFACE_FOCUS_STYLE}
data-image-map-surface=""
h="full"
outline="none"
position="relative"
tabIndex={-1}
w="full"
>
<Suspense fallback={plotLoadingFallback}>
<ImageMapPlot clickSelectsCluster={clickSelectsCluster} showClusterLabels={showClusterLabels} />
</Suspense>
{/* One corner, stacked: the selection first, since the user made it. The column passes pointer events through,
because the plot under it is drag-panned and wheel-zoomed across its whole area; each overlay takes its own
back. */}
<Stack
align="flex-start"
gap="1.5"
insetStart="2"
maxW="calc(100% - 1rem)"
pointerEvents="none"
position="absolute"
top={OVERLAY_COLUMN_TOP}
zIndex="1"
>
<ClusterSelectionChip />
{isIndexing(indexCounts) ? <ImageIndexActivityBadge counts={indexCounts} updatedAt={indexUpdatedAt} /> : null}
</Stack>
</Box>
);
}
const loadFailed = error ?? t('widgets.imageMap.loadFailed');
const retainedDataError = loadState === 'error' ? loadFailed : null;
// Ahead of the loading spinner, unlike every other message: a refresh from this state flips `loadState` to `loading`,
// and flashing a spinner over the message would unmount the model link — losing the "refresh when the download lands"
// watcher with it. The diagnosis is also what a refresh is least likely to change.
if (data?.state === 'model_missing') {
const modelName = data.modelName?.trim() || DEFAULT_IMAGE_INDEX_MODEL;
return (
<CenteredMessage
// Keep a standing refresh action to discover newly installed encoders while the indexer is otherwise inert.
actionLabel={retainedDataError ? t('common.retry') : t('widgets.imageMap.checkAgain')}
detail={
canManageModels ? (
// oxlint-disable-next-line react-perf/jsx-no-jsx-as-prop -- one message on a cold state.
<Trans
// oxlint-disable-next-line react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-object-as-prop -- the link sits inside the sentence.
components={{ model: <ImageIndexModelInstallLink modelName={modelName} /> }}
i18nKey="widgets.imageMap.modelMissingAdmin"
t={t}
/>
) : (
t('widgets.imageMap.modelMissingMember', { name: modelName })
)
}
errorDetail={retainedDataError}
onAction={handleRefresh}
title={t('widgets.imageMap.modelMissingTitle')}
/>
);
}
if (loadState === 'idle' || loadState === 'loading') {
return (
<Center h="full">
<Spinner size="2xl" />
</Center>
);
}
if (loadState === 'error' && !data) {
return (
<CenteredMessage
actionLabel={t('common.retry')}
detail={loadFailed}
onAction={handleRefresh}
title={t('widgets.imageMap.unavailableTitle')}
/>
);
}
if (!data || data.state === 'disabled') {
return (
<CenteredMessage
actionLabel={retainedDataError ? t('common.retry') : undefined}
detail={canManageAppConfig ? t('widgets.imageMap.indexingOffAdmin') : t('widgets.imageMap.indexingOffMember')}
errorDetail={retainedDataError}
onAction={retainedDataError ? handleRefresh : undefined}
title={t('widgets.imageMap.indexingOffTitle')}
/>
);
}
// Prioritize backfill progress over computing/empty states before points exist.
if (isIndexing(indexCounts)) {
return (
<Center h="full" p="6">
<ImageIndexProgressPanel
counts={indexCounts}
error={retainedDataError}
updatedAt={indexUpdatedAt}
onRetry={handleRefresh}
/>
</Center>
);
}
if (data.state === 'computing') {
return (
<Center h="full">
<Stack align="center" gap="3">
<Spinner size="2xl" />
<Text color="fg.muted" fontSize="lg">
{t('widgets.imageMap.computing')}
</Text>
{/* A failed fit also sits here during the cooldown, so this has to be able to bypass it. */}
<Button onClick={handleRecompute} variant="outline">
{t('widgets.imageMap.checkAgain')}
</Button>
</Stack>
</Center>
);
}
if (loadState === 'error') {
return (
<CenteredMessage
actionLabel={t('common.retry')}
detail={loadFailed}
onAction={handleRefresh}
title={t('widgets.imageMap.unavailableTitle')}
/>
);
}
// The shared media filter can empty a map that has points of the other kind.
if (mediaFilter !== 'all') {
return (
<CenteredMessage
actionLabel={t('widgets.imageMap.showAllMedia')}
detail={
mediaFilter === 'video'
? t('widgets.imageMap.filteredVideosDetail')
: t('widgets.imageMap.filteredImagesDetail')
}
onAction={handleShowAllMedia}
title={
mediaFilter === 'video'
? t('widgets.imageMap.filteredVideosTitle')
: t('widgets.imageMap.filteredImagesTitle')
}
/>
);
}
return <CenteredMessage detail={t('widgets.imageMap.emptyDetail')} title={t('widgets.imageMap.emptyTitle')} />;
};
const CenteredMessage = ({
actionLabel,
detail,
errorDetail,
onAction,
title,
}: {
title: string;
detail: ReactNode;
actionLabel?: string;
errorDetail?: string | null;
onAction?: () => void;
}) => (
<Center h="full" p="6">
<Stack align="center" gap="2" maxW="sm" textAlign="center">
<Text fontSize="xl" fontWeight="semibold">
{title}
</Text>
<Text color="fg.muted" fontSize="lg">
{detail}
</Text>
{errorDetail ? (
<Text color="fg.error" fontSize="lg" maxW="full" minW="0" overflowWrap="anywhere" role="alert">
{errorDetail}
</Text>
) : null}
{actionLabel && onAction ? (
<Button mt="2" onClick={onAction} variant="outline">
{actionLabel}
</Button>
) : null}
</Stack>
</Center>
);
/** Links the encoder to Add Models; plain text when uncatalogued, downloading, or unmanageable. */
const ImageIndexModelInstallLink = ({ modelName }: { modelName: string }) => {
const { t } = useTranslation();
const starterModels = useStartersSelector(selectStarterModels);
const activeInstallSources = useActiveInstallSources();
const openAddModelsSearch = useOpenAddModelsSearch();
useMountEffect(() => {
ensureStartersLoaded();
});
const sources = useMemo(() => {
const starter = starterModels.find((candidate) => candidate.name === modelName);
return starter ? getStarterModelInstallSources(starter) : [];
}, [modelName, starterModels]);
const installing = sources.some((entry) => activeInstallSources.has(entry.source));
const wasInstalling = useRef(false);
// The server picks a freshly installed encoder up on the next map request, so ask for one as soon as the download
// lands: without it the panel keeps saying "not installed" until someone reopens it.
useEffect(() => {
if (wasInstalling.current && !installing) {
handleRefresh();
}
wasInstalling.current = installing;
}, [installing]);
const handleOpen = useCallback(() => openAddModelsSearch?.(modelName), [modelName, openAddModelsSearch]);
if (sources.length === 0 || installing || !openAddModelsSearch) {
return (
<Text as="span" fontWeight="medium">
{installing ? t('widgets.imageMap.modelInstalling', { name: modelName }) : modelName}
</Text>
);
}
return (
<Link as="button" colorPalette="accent" onClick={handleOpen} type="button" variant="underline">
{modelName}
</Link>
);
};