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(image-map): add a clustering-strength control

Lincoln Stein074191691acb
diff --git a/invokeai/app/services/image_index/projection.py b/invokeai/app/services/image_index/projection.py
index 44e5f5e4ba..c1e54f61d6 100644
--- a/invokeai/app/services/image_index/projection.py
+++ b/invokeai/app/services/image_index/projection.py
@@ -176,7 +176,9 @@ class EpsResolution:
coord_span: float
"""Widest coordinate extent of the projection; 0.0 for a single point."""
span_clamped_eps: float
- """After the MAX_EPS_SPAN_FRACTION clamp, before the floor."""
+ """After the MAX_EPS_SPAN_FRACTION clamp, before the floor. Equal to the
+ requested eps when the caller supplied one: the clamp guards the
+ heuristic, not the user."""
floored_eps: float
"""After the 0.01 floor. Reported apart from the clamp because the two are
separate causes of an over-tight eps, and a single number cannot say which
@@ -203,6 +205,7 @@ def resolve_cluster_eps(
"""
requested_eps = eps
adaptive_eps: Optional[float] = None
+ span = float(np.ptp(coords, axis=0).max()) if coords.shape[0] > 1 else 0.0
if eps is None:
# Cap at the API's own upper bound (le=2.0) so a reported adaptive
# eps can always be passed back explicitly. Values that large only
@@ -210,9 +213,16 @@ def resolve_cluster_eps(
# more (correct) noise.
adaptive_eps = adaptive_cluster_eps(coords, min_samples)
eps = min(adaptive_eps, 2.0)
- span = float(np.ptp(coords, axis=0).max()) if coords.shape[0] > 1 else 0.0
- if span > 0:
- eps = min(eps, span * MAX_EPS_SPAN_FRACTION)
+ # The span clamp applies ONLY to a derived value. A number the user
+ # typed into the clustering-strength control is theirs to keep:
+ # silently retuning it makes the control lie about what it does, and
+ # on a small map (span 2, clamp 0.1) it would override most of the
+ # range the control offers. A derived eps a large fraction of the
+ # whole map's width, by contrast, means there is no density structure
+ # to find, so bounding that one is a sanity check on the heuristic.
+ # The pair budget below is the memory bound and applies to both.
+ if span > 0:
+ eps = min(eps, span * MAX_EPS_SPAN_FRACTION)
# Floor at the API's lower bound (ge=0.01) for pass-back validity, but do
# it BEFORE the budget shrink, never after: applied afterwards it silently
# re-inflated eps past the neighbor-pair budget the shrink had just
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 3d55701e36..f160c52899 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4038,7 +4038,12 @@
"fields": {
"comparisonMode": "Comparison mode",
"showClusterLabels": "Show cluster labels",
- "clickSelectsCluster": "Select clusters on click"
+ "clickSelectsCluster": "Select clusters on click",
+ "clusterStrength": "Clustering strength",
+ "clusterStrengthHint": "Higher values create larger clusters",
+ "clusterStrengthAuto": "auto",
+ "clusterStrengthIncomplete": "Not a number yet \u2014 the clustering strength is unchanged.",
+ "clusterStrengthRange": "Clustering strength must be between {{min}} and {{max}}."
},
"changedFromDefault": "Changed from default",
"changedSetting": "{{setting}}: changed from default"
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterEps.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterEps.test.ts
new file mode 100644
index 0000000000..610bb3bf6f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterEps.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { getImageMapClusterEps, MAX_CLUSTER_EPS, MIN_CLUSTER_EPS } from './imageMapSettings';
+
+describe('getImageMapClusterEps', () => {
+ it('reads a chosen strength', () => {
+ expect(getImageMapClusterEps({ clusterEps: 0.25 })).toBe(0.25);
+ });
+
+ it('means "derive it" when unset', () => {
+ // The default, and the state the control returns to when cleared.
+ expect(getImageMapClusterEps({})).toBeNull();
+ expect(getImageMapClusterEps({ clusterEps: null })).toBeNull();
+ });
+
+ it('rejects stored values the endpoint would refuse', () => {
+ // Persisted widget values survive upgrades and hand-edited project files,
+ // so a bad one must fall back to the heuristic rather than 422 every
+ // points request and leave the map permanently empty.
+ expect(getImageMapClusterEps({ clusterEps: 0 })).toBeNull();
+ expect(getImageMapClusterEps({ clusterEps: -1 })).toBeNull();
+ expect(getImageMapClusterEps({ clusterEps: Number.NaN })).toBeNull();
+ expect(getImageMapClusterEps({ clusterEps: Infinity })).toBeNull();
+ expect(getImageMapClusterEps({ clusterEps: '0.2' })).toBeNull();
+ expect(getImageMapClusterEps({ clusterEps: MIN_CLUSTER_EPS / 2 })).toBeNull();
+ });
+
+ it('keeps the bounds the control and the endpoint agree on', () => {
+ expect(getImageMapClusterEps({ clusterEps: MIN_CLUSTER_EPS })).toBe(MIN_CLUSTER_EPS);
+ expect(getImageMapClusterEps({ clusterEps: MAX_CLUSTER_EPS })).toBe(MAX_CLUSTER_EPS);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts
index 1516572f3b..0c89ce3be5 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts
@@ -9,3 +9,19 @@ export const getImageMapClickSelectsCluster = (values: Record<string, unknown>):
/** Labels are drawn unless the user has turned them off. */
export const getImageMapShowClusterLabels = (values: Record<string, unknown>): boolean =>
values.showClusterLabels !== false;
+
+/** Lowest eps the backend will cluster with; below it the server floors the value anyway. */
+export const MIN_CLUSTER_EPS = 0.01;
+/** The API's own upper bound on the eps query parameter. */
+export const MAX_CLUSTER_EPS = 2;
+
+/**
+ * The DBSCAN eps the user chose, or null while the server's adaptive value
+ * is in use. Null is the default and the way back: clearing the control
+ * hands the choice to the heuristic again.
+ */
+export const getImageMapClusterEps = (values: Record<string, unknown>): number | null => {
+ const raw = values.clusterEps;
+
+ return typeof raw === 'number' && Number.isFinite(raw) && raw >= MIN_CLUSTER_EPS ? raw : null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
index ee2508711a..30f0fef094 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
@@ -92,6 +92,30 @@ registerAccountOwnedResource({
name: 'image-map',
});
+/**
+ * The eps the clustering-strength control has been set to, or null for the
+ * server's adaptive value. Pushed down from the widget rather than passed by
+ * callers: every refresh — socket-driven, manual, or the first load — has to
+ * cluster at the strength the user chose, and only this module sees them all.
+ */
+let clusterEps: number | null = null;
+
+export const setClusterEps = (eps: number | null): void => {
+ if (eps === clusterEps) {
+ return;
+ }
+
+ clusterEps = eps;
+
+ // Nothing has been fetched yet, so the first fetch will carry the new value
+ // on its own; refreshing here would race it for no gain.
+ if (imageMapStore.getSnapshot().loadState === 'idle') {
+ return;
+ }
+
+ void refreshImageMapPoints();
+};
+
export const refreshImageMapPoints = (): Promise<void> => {
if (inflight) {
// A refresh requested mid-flight (e.g. projection_ready arriving while
@@ -105,7 +129,7 @@ export const refreshImageMapPoints = (): Promise<void> => {
const owner = captureAccountScope();
imageMapStore.patchSnapshot({ loadState: 'loading' });
- const refresh = fetchImageMapPoints()
+ const refresh = fetchImageMapPoints(clusterEps !== null ? { eps: clusterEps } : undefined)
.then((data) => {
if (!isAccountScopeCurrent(owner)) {
return;
diff --git a/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.ts b/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.ts
index e4de01a75d..51289e1159 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.ts
+++ b/invokeai/frontend/webv2/src/workbench/settings/useWidgetSettingsTarget.ts
@@ -7,7 +7,7 @@ import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } f
import { useCallback, useState } from 'react';
/** Selects only one field and fences writes against removed instances and project/account changes. */
-export const useWidgetSettingsTarget = <Value extends boolean | string | number>(
+export const useWidgetSettingsTarget = <Value extends boolean | string | number | null>(
widgetId: WidgetTypeId,
target: SettingsTarget | undefined,
read: (values: Record<string, unknown>) => Value
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx
new file mode 100644
index 0000000000..4b0bd90ca1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx
@@ -0,0 +1,216 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { imageMapStore } from '@workbench/image-map/imageMapStore';
+import { act, useSyncExternalStore } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { imageMapSettingsContribution } from './settingsContribution';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ ({
+ 'settingsDialog.fields.clusterStrength': 'Clustering strength',
+ 'settingsDialog.fields.clusterStrengthAuto': 'auto',
+ 'settingsDialog.fields.clusterStrengthHint': 'Higher values create larger clusters',
+ })[key] ?? key,
+ }),
+}));
+
+// A real subscribable stand-in for the widget's persisted values: committing
+// has to re-render the field, which is how the box learns the edit landed.
+const settings = vi.hoisted(() => {
+ const listeners = new Set<() => void>();
+ let value: number | null = null;
+
+ return {
+ get: () => value,
+ patch: vi.fn((values: Record<string, unknown>) => {
+ value = (values.clusterEps as number | null) ?? null;
+ for (const listener of listeners) {
+ listener();
+ }
+ }),
+ reset: () => {
+ value = null;
+ listeners.clear();
+ },
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+
+ return () => listeners.delete(listener);
+ },
+ };
+});
+
+vi.mock('@workbench/settings/useWidgetSettingsTarget', () => ({
+ useWidgetSettingsTarget: () => ({
+ disabled: false,
+ patch: settings.patch,
+ value: useSyncExternalStore(settings.subscribe, settings.get, settings.get),
+ }),
+}));
+
+const { ClusterStrengthField } = await import('./ClusterStrengthField');
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+/** Longer than the field's own debounce, so a commit has certainly fired. */
+const settle = () =>
+ act(async () => {
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 900);
+ });
+ });
+
+const field = imageMapSettingsContribution.fields.find((entry) => entry.id === 'clusterEps')!;
+
+/** `resolved` is what the server says it clustered with. */
+const render = async (resolved: number | null) => {
+ imageMapStore.setSnapshot({
+ clusterLabels: null,
+ clusterLabelsHash: null,
+ data: {
+ clusterEps: resolved,
+ modelName: null,
+ pointCount: 1,
+ points: [],
+ stale: false,
+ state: 'ready',
+ updatedAt: null,
+ visibleHash: null,
+ },
+ error: null,
+ indexCounts: null,
+ indexUpdatedAt: null,
+ loadState: 'loaded',
+ renderError: null,
+ });
+
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <ClusterStrengthField field={field} surface="dialog" {...({} as Partial<SettingFieldProps>)} />
+ </ChakraProvider>
+ )
+ );
+};
+
+/** The "auto" badge is hidden rather than unmounted, to keep the row from shifting. */
+const autoBadgeShown = (): boolean => {
+ const badge = host?.querySelector('[data-testid="cluster-strength-auto"]');
+
+ return badge instanceof HTMLElement && globalThis.getComputedStyle(badge).visibility === 'visible';
+};
+
+const spinner = (): HTMLInputElement => {
+ const input = host?.querySelector('input[type="number"]');
+
+ if (!(input instanceof HTMLInputElement)) {
+ throw new Error('the clustering-strength spinner is not in the document');
+ }
+
+ return input;
+};
+
+beforeEach(() => {
+ settings.reset();
+ settings.patch.mockClear();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('ClusterStrengthField', () => {
+ it('shows the strength the server derived, marked as not the user’s', async () => {
+ await render(0.0945);
+
+ expect(spinner().value).toBe('0.095');
+ expect(autoBadgeShown()).toBe(true);
+ expect(host?.textContent).toContain('Higher values create larger clusters');
+ });
+
+ it('commits a typed strength once, after the edit settles', async () => {
+ await render(0.0945);
+
+ await userEvent.fill(spinner(), '0.25');
+ expect(settings.patch).not.toHaveBeenCalled();
+
+ await settle();
+
+ expect(settings.patch).toHaveBeenCalledTimes(1);
+ expect(settings.patch).toHaveBeenCalledWith({ clusterEps: 0.25 });
+ expect(autoBadgeShown()).toBe(false);
+ });
+
+ it('hands the choice back to the heuristic when cleared', async () => {
+ await render(0.0945);
+ await userEvent.fill(spinner(), '0.25');
+ await settle();
+ settings.patch.mockClear();
+
+ await userEvent.clear(spinner());
+ await settle();
+
+ expect(settings.patch).toHaveBeenCalledWith({ clusterEps: null });
+ // And the box refills with the derived value rather than staying empty.
+ expect(spinner().value).toBe('0.095');
+ expect(autoBadgeShown()).toBe(true);
+ });
+
+ it('does not mistake a half-typed number for a cleared box', async () => {
+ // `type="number"` reports an empty value for "0." too. Reading that as
+ // "use the heuristic" would throw the user's setting away mid-keystroke.
+ await render(0.0945);
+ await userEvent.fill(spinner(), '0.25');
+ await settle();
+ settings.patch.mockClear();
+
+ await userEvent.clear(spinner());
+ await userEvent.type(spinner(), '.');
+ // The box reads as empty here, which is the whole trap.
+ expect(spinner().value).toBe('');
+ expect(spinner().validity.badInput).toBe(true);
+
+ await settle();
+
+ expect(settings.patch).not.toHaveBeenCalled();
+ });
+
+ it('does not complain on the way through an incomplete number', async () => {
+ // "0.15" passes through "0", which is below the minimum. Validating per
+ // keystroke would flash a range error at a user typing a fine value.
+ await render(0.0945);
+ await userEvent.clear(spinner());
+ await userEvent.type(spinner(), '0.15');
+
+ expect(host?.textContent).not.toContain('clusterStrengthRange');
+
+ await settle();
+
+ expect(settings.patch).toHaveBeenCalledWith({ clusterEps: 0.15 });
+ });
+
+ it('refuses a strength the endpoint would reject', async () => {
+ await render(0.0945);
+
+ await userEvent.fill(spinner(), '9');
+ await settle();
+
+ expect(settings.patch).not.toHaveBeenCalled();
+ expect(host?.textContent).toContain('clusterStrengthRange');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.tsx
new file mode 100644
index 0000000000..10c6c1aa13
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.tsx
@@ -0,0 +1,216 @@
+import type { SettingFieldProps } from '@platform/ui/settings/contracts';
+
+import { Badge, Field, HStack, Input, Stack } from '@chakra-ui/react';
+import { resolveSettingsText } from '@platform/ui/settings/contracts';
+import { ModifiedSettingIndicator } from '@platform/ui/settings/ModifiedSettingIndicator';
+import { getImageMapClusterEps, MAX_CLUSTER_EPS, MIN_CLUSTER_EPS } from '@workbench/image-map/imageMapSettings';
+import { imageMapStore } from '@workbench/image-map/imageMapStore';
+import { useWidgetSettingsTarget } from '@workbench/settings/useWidgetSettingsTarget';
+import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * Long enough that a spinner held down, or a three-digit number typed in
+ * full, costs one recluster rather than one per keystroke — reclustering a
+ * six-figure gallery is seconds of server CPU. Short enough that a deliberate
+ * edit feels answered.
+ */
+const COMMIT_DEBOUNCE_MS = 500;
+
+const DIALOG_DIRECTION = { base: 'column', md: 'row' } as const;
+const DIALOG_ALIGNMENT = { base: 'stretch', md: 'center' } as const;
+
+/** Trims the heuristic's float to something a 0.01 spinner can step from. */
+const forDisplay = (eps: number): string => String(Number(eps.toFixed(3)));
+
+/**
+ * "Clustering strength" — the DBSCAN eps, as a number the user can nudge.
+ *
+ * Not a shared `number` setting because of the empty state: blank means "go
+ * back to deriving it", which is the only way out of a value once chosen, and
+ * the shared control cannot express it (it is fully controlled and drops
+ * anything unparseable). The derived value is shown in the box rather than as
+ * a placeholder, so the number on screen is always the one the map used.
+ */
+export const ClusterStrengthField = ({ field, surface, target }: SettingFieldProps) => {
+ const { t } = useTranslation();
+ const { disabled, patch, value: chosen } = useWidgetSettingsTarget('image-map', target, getImageMapClusterEps);
+ // What the server actually clustered with, which is the heuristic's answer
+ // whenever nothing has been chosen.
+ const resolved = imageMapStore.useSnapshot().data?.clusterEps ?? null;
+ const shown = chosen ?? resolved;
+ const [invalid, setInvalid] = useState<string | null>(null);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const pending = useRef(false);
+ // Uncontrolled on purpose. A controlled `value` driven from the element
+ // would erase exactly the input this field has to tolerate: `type="number"`
+ // reports "" for a half-typed "0.", so React would write that "" straight
+ // back and wipe the keystrokes out from under the cursor — taking
+ // `badInput` with them, which is the only signal distinguishing a partial
+ // number from a deliberately cleared box.
+ const input = useRef<HTMLInputElement | null>(null);
+
+ const commit = useCallback(
+ (eps: number | null) => {
+ pending.current = false;
+ patch({ clusterEps: eps });
+ },
+ [patch]
+ );
+
+ // Anything arriving from outside — a recluster's resolved value, another
+ // surface changing the setting — must not move the number under the
+ // cursor, so it waits until the edit has settled.
+ useEffect(() => {
+ if (pending.current || !input.current) {
+ return;
+ }
+
+ setInvalid(null);
+ input.current.value = shown === null ? '' : forDisplay(shown);
+ }, [shown]);
+
+ useEffect(
+ () => () => {
+ if (timer.current !== null) {
+ clearTimeout(timer.current);
+ }
+ },
+ []
+ );
+
+ /**
+ * Decide what the field now holds. Deferred behind the debounce rather than
+ * run per keystroke, so the complaints only appear once the user has
+ * stopped: validating eagerly makes "0.15" flash "must be at least 0.01"
+ * on its way past "0".
+ */
+ const resolve = useCallback(
+ (text: string, badInput: boolean) => {
+ timer.current = null;
+
+ // `type="number"` reports an empty value for anything it cannot parse
+ // yet — ".", "-", "1e" — so an empty box alone cannot be read as "use
+ // the heuristic". `badInput` is what separates a half-typed number from
+ // a deliberately cleared one; without it, a pause mid-keystroke throws
+ // away the strength the map was tuned to.
+ if (badInput) {
+ setInvalid(t('settingsDialog.fields.clusterStrengthIncomplete'));
+
+ return;
+ }
+
+ if (text.trim() === '') {
+ commit(null);
+
+ return;
+ }
+
+ const eps = Number(text);
+
+ if (!Number.isFinite(eps) || eps < MIN_CLUSTER_EPS || eps > MAX_CLUSTER_EPS) {
+ // Refused rather than clamped: the endpoint rejects anything outside
+ // this range, and quietly substituting a different number would make
+ // the control disagree with the map.
+ setInvalid(t('settingsDialog.fields.clusterStrengthRange', { max: MAX_CLUSTER_EPS, min: MIN_CLUSTER_EPS }));
+
+ return;
+ }
+
+ commit(eps);
+ },
+ [commit, t]
+ );
+
+ const onChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const { validity, value } = event.currentTarget;
+
+ pending.current = true;
+ setInvalid(null);
+
+ if (timer.current !== null) {
+ clearTimeout(timer.current);
+ }
+
+ timer.current = setTimeout(() => resolve(value, validity.badInput), COMMIT_DEBOUNCE_MS);
+ },
+ [resolve]
+ );
+
+ // Leaving the field ends the edit: flush a pending commit so a value typed
+ // and then dismissed still takes effect, and otherwise release the guard so
+ // a refused edit does not read as mid-edit forever.
+ const onBlur = useCallback(() => {
+ if (timer.current !== null) {
+ clearTimeout(timer.current);
+ const field = input.current;
+ resolve(field?.value ?? '', field?.validity.badInput === true);
+
+ return;
+ }
+
+ pending.current = false;
+ setInvalid(null);
+
+ if (input.current) {
+ input.current.value = shown === null ? '' : forDisplay(shown);
+ }
+ }, [resolve, shown]);
+
+ const label = resolveSettingsText(field.label, t);
+ const description = field.description ? resolveSettingsText(field.description, t) : undefined;
+
+ return (
+ <Field.Root
+ alignItems={surface === 'quick' ? 'stretch' : DIALOG_ALIGNMENT}
+ disabled={disabled}
+ display="flex"
+ flexDirection={surface === 'quick' ? 'column' : DIALOG_DIRECTION}
+ gap="3"
+ invalid={invalid !== null}
+ justifyContent="space-between"
+ >
+ <Stack flex="1" gap="1">
+ <HStack gap="2">
+ <Field.Label fontSize={surface === 'quick' ? 'xs' : 'sm'} fontWeight="500">
+ {label}
+ </Field.Label>
+ {chosen !== null ? <ModifiedSettingIndicator label={label} /> : null}
+ </HStack>
+ {description ? (
+ <Field.HelperText color="fg.muted" fontSize="xs">
+ {description}
+ </Field.HelperText>
+ ) : null}
+ {invalid ? <Field.ErrorText fontSize="xs">{invalid}</Field.ErrorText> : null}
+ </Stack>
+ <HStack flexShrink={0} gap="2">
+ <Input
+ aria-label={label}
+ defaultValue={shown === null ? '' : forDisplay(shown)}
+ disabled={disabled}
+ max={MAX_CLUSTER_EPS}
+ min={MIN_CLUSTER_EPS}
+ ref={input}
+ size="sm"
+ step="0.01"
+ type="number"
+ w="24"
+ onBlur={onBlur}
+ onChange={onChange}
+ />
+ {/* Says whose number this is: without it a derived value and a chosen
+ one are the same digits in the same box. */}
+ <Badge
+ data-testid="cluster-strength-auto"
+ size="sm"
+ variant="subtle"
+ visibility={chosen === null ? 'visible' : 'hidden'}
+ >
+ {t('settingsDialog.fields.clusterStrengthAuto')}
+ </Badge>
+ </HStack>
+ </Field.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
index f3f7253153..15dfc48b03 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
@@ -8,7 +8,11 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@workbench/WorkbenchContext', () => ({
- useWidgetValuesSelector: () => false,
+ // Applied to an empty value bag rather than answering `false` to every
+ // selector: each accessor owns its own default, and handing a boolean to a
+ // setting that is a number or null makes the widget act on a value it could
+ // never be given in production.
+ useWidgetValuesSelector: (_widgetId: string, select: (values: Record<string, unknown>) => unknown) => select({}),
}));
// The real one pulls the ~1.5MB plotly chunk; the badge under test is its
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
index 3f85e35d11..269fbd9d37 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
@@ -11,12 +11,17 @@ import {
useStartersSelector,
} from '@features/models';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { getImageMapClickSelectsCluster, getImageMapShowClusterLabels } from '@workbench/image-map/imageMapSettings';
+import {
+ getImageMapClickSelectsCluster,
+ getImageMapClusterEps,
+ getImageMapShowClusterLabels,
+} from '@workbench/image-map/imageMapSettings';
import {
ensureImageMapLoaded,
imageMapStore,
refreshImageIndexStatus,
refreshImageMapPoints,
+ setClusterEps,
setClusterLabelsEnabled,
} from '@workbench/image-map/imageMapStore';
import { isIndexing } from '@workbench/image-map/indexProgress';
@@ -65,8 +70,15 @@ const plotLoadingFallback = (
export const ImageMapWidgetView = (_props: WidgetViewProps) => {
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);
+ // Before the first load, so it carries the chosen strength rather than
+ // fetching at the default and immediately refetching.
+ useEffect(() => {
+ setClusterEps(clusterEps);
+ }, [clusterEps]);
+
useEffect(() => {
ensureImageMapLoaded();
}, []);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx
index 8b6b8db2e8..f69ecf29e5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsBindings.tsx
@@ -3,9 +3,19 @@ import type { SettingFieldProps } from '@platform/ui/settings/contracts';
import { SettingControl } from '@platform/ui/settings/SettingControl';
import { getImageMapClickSelectsCluster, getImageMapShowClusterLabels } from '@workbench/image-map/imageMapSettings';
import { useWidgetSettingsTarget } from '@workbench/settings/useWidgetSettingsTarget';
+import { ClusterStrengthField } from '@workbench/widgets/image-map/ClusterStrengthField';
import { useCallback } from 'react';
-export const Field = ({ field, surface, target }: SettingFieldProps) => {
+export const Field = (props: SettingFieldProps) => {
+ // Its empty state means "derive it", which no shared control expresses.
+ if (props.field.id === 'clusterEps') {
+ return <ClusterStrengthField {...props} />;
+ }
+
+ return <BooleanField {...props} />;
+};
+
+const BooleanField = ({ field, surface, target }: SettingFieldProps) => {
const { disabled, patch, value } = useWidgetSettingsTarget(
'image-map',
target,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts
index bfa9b58966..5abb2ba9b4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts
@@ -11,6 +11,14 @@ export const imageMapSettingsContribution: SettingsContribution = {
scope: 'instance',
keywords: 'tags text display',
},
+ {
+ id: 'clusterEps',
+ kind: 'custom',
+ label: (t) => t('settingsDialog.fields.clusterStrength'),
+ description: (t) => t('settingsDialog.fields.clusterStrengthHint'),
+ scope: 'instance',
+ keywords: 'dbscan eps clustering density granularity',
+ },
{
id: 'clickSelectsCluster',
kind: 'boolean',
diff --git a/tests/app/services/image_index/test_projection.py b/tests/app/services/image_index/test_projection.py
index b3f41f8446..74537aa1c8 100644
--- a/tests/app/services/image_index/test_projection.py
+++ b/tests/app/services/image_index/test_projection.py
@@ -141,13 +141,36 @@ def test_resolve_cluster_eps_is_idempotent() -> None:
assert resolve_cluster_eps(coords, eps=resolved).resolved_eps == resolved
-def test_compute_clusters_clamps_eps_to_span_fraction() -> None:
- # Span ~1: an eps near the span would make every point a neighbor of
- # every other (the sklearn DBSCAN memory blowup); the clamp keeps distant
- # pairs from ever merging.
- coords = np.array([[0, 0], [0.01, 0], [1, 1], [1.01, 1]], dtype=np.float32)
- labels = compute_clusters(coords, eps=2.0, min_samples=2)
- assert labels[0] == labels[1] != labels[2] == labels[3]
+def test_a_derived_eps_is_clamped_to_the_span_fraction() -> None:
+ # 20 scattered points: the median k-distance is half the map wide, which
+ # says there is no density structure to find. Clustering at that radius
+ # would merge everything, so the heuristic's own answer is bounded.
+ rng = np.random.default_rng(4)
+ coords = rng.uniform(0.0, 1.0, size=(20, 2)).astype(np.float32)
+ resolution = resolve_cluster_eps(coords, None, 10)
+
+ assert resolution.adaptive_eps is not None
+ assert resolution.adaptive_eps > resolution.coord_span * MAX_EPS_SPAN_FRACTION
+ assert resolution.span_clamped_eps == resolution.coord_span * MAX_EPS_SPAN_FRACTION
+
+
+def test_a_requested_eps_is_not_clamped_to_the_span_fraction() -> None:
+ """The clustering-strength control has to mean what it says.
+
+ Clamping a number the user typed would silently retune it — on a small
+ map (span 2, clamp 0.1) that overrides most of the range the control
+ offers, and the value reported back would not be the one they chose. The
+ pair budget still applies to both, because that one is a memory bound.
+ """
+ rng = np.random.default_rng(4)
+ coords = rng.uniform(0.0, 1.0, size=(20, 2)).astype(np.float32)
+ resolution = resolve_cluster_eps(coords, 0.5, 10)
+
+ assert 0.5 > resolution.coord_span * MAX_EPS_SPAN_FRACTION, "the clamp would bind if it were applied"
+ assert resolution.span_clamped_eps == 0.5
+ assert resolution.resolved_eps == 0.5
+ # And it reaches DBSCAN: at 0.5 on a span-0.88 map everything is one cluster.
+ assert set(compute_clusters(coords, eps=0.5, min_samples=2)) == {0}
def test_compute_clusters_skips_huge_point_sets() -> None:
@@ -275,23 +298,24 @@ def test_diagnostics_report_each_link_of_the_eps_chain() -> None:
assert resolution.requested_eps == 5.0
assert resolution.adaptive_eps is None, "an explicit eps must not be reported as an adaptive one"
assert resolution.coord_span == 30.0
- assert resolution.span_clamped_eps == 30.0 * MAX_EPS_SPAN_FRACTION
- assert resolution.floored_eps == resolution.span_clamped_eps, "1.5 is above the floor; the floor must not move it"
- assert resolution.resolved_eps == resolution.floored_eps, "6 pairs is under any budget"
+ assert resolution.span_clamped_eps == 5.0, "a requested eps passes the clamp untouched"
+ assert resolution.floored_eps == 5.0, "5.0 is above the floor; the floor must not move it"
+ assert resolution.resolved_eps == 5.0, "4 pairs is under any budget"
def test_diagnostics_separate_the_span_clamp_from_the_eps_floor() -> None:
"""Both can produce a too-tight eps, and the log has to say which one did."""
- # Span 0.08, so the clamp gives 0.004 and the 0.01 floor then lifts it.
- coords = np.array([[0.0, 0.0], [0.08, 0.0], [0.04, 0.0]], dtype=np.float32)
- resolution = resolve_cluster_eps(coords, eps=2.0, min_samples=2)
-
- assert resolution.span_clamped_eps < 0.01
- assert resolution.floored_eps == 0.01
- assert (
- "span_clamped_eps=0.004 floored_eps=0.01"
- in cluster_with_diagnostics(coords, eps=2.0, min_samples=2)[1].signature()
- )
+ # A 0.07-wide map: the clamp takes the derived eps to 0.0037, and the 0.01
+ # floor then lifts it back. One number could not distinguish the two.
+ rng = np.random.default_rng(4)
+ rng.uniform(0.0, 1.0, size=(20, 2))
+ coords = rng.uniform(0.0, 0.08, size=(30, 2)).astype(np.float32)
+ resolution = resolve_cluster_eps(coords, None, 10)
+
+ assert resolution.adaptive_eps is not None and resolution.adaptive_eps > 0.01
+ assert resolution.span_clamped_eps < 0.01, "the clamp took it below the floor"
+ assert resolution.floored_eps == 0.01, "and the floor put it back"
+ assert "floored_eps=0.01" in cluster_with_diagnostics(coords, min_samples=10)[1].signature()
def test_the_pair_budget_shrink_can_succeed_short_of_its_floor(monkeypatch) -> None: