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(webv2): show indexed videos on the image map

Lincoln Stein47cf78be3f1f
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
index c154220855..52e48a0376 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -720,3 +720,50 @@ test('copying media mints fresh identities and deleting a project keeps its medi
);
});
});
+
+test('the image map serves videos only on request and keeps its two endpoints comparable', async () => {
+ await withRepresentativeBackend(async (backend) => {
+ const imagesOnly = await getJson(backend, '/api/v1/image_map/points');
+ const withVideos = await getJson(backend, '/api/v1/image_map/points?include_videos=true');
+
+ // The opt-in gate, which is the contract the real backend enforces: a
+ // client that cannot render videos must not be sent any.
+ assert.equal(
+ imagesOnly.points.some((point) => point.kind === 'video'),
+ false
+ );
+ assert.equal(
+ withVideos.points.some((point) => point.kind === 'video'),
+ true
+ );
+ // The footer reports point_count, so it has to match what was served.
+ assert.equal(imagesOnly.point_count, imagesOnly.points.length);
+ assert.equal(withVideos.point_count, withVideos.points.length);
+ assert.equal(withVideos.points.length > imagesOnly.points.length, true);
+
+ // The client discards a label set whose projection or visible set differs
+ // from the points it is holding, so a mock that answers inconsistently
+ // silently shows an unlabelled map.
+ const labels = await getJson(backend, '/api/v1/image_map/cluster_labels?include_videos=true');
+ assert.equal(labels.updated_at, withVideos.updated_at);
+ assert.equal(labels.visible_hash, withVideos.visible_hash);
+
+ // Every point names a real item of the kind it claims. Deliberately a
+ // video whose name is in no image: the fixtures include a video named like
+ // an image, and the cross-namespace assertion below needs a genuine miss.
+ const imageNames = new Set(imagesOnly.points.map((point) => point.image_name));
+ const video = withVideos.points.find((point) => point.kind === 'video' && !imageNames.has(point.image_name));
+ assert.equal((await getJson(backend, `/api/v1/videos/i/${video.image_name}`)).video_name, video.image_name);
+
+ const videoLabels = await getJson(
+ backend,
+ `/api/v1/image_map/image_labels?image_name=${video.image_name}&kind=video`
+ );
+ assert.equal(typeof videoLabels.label, 'string');
+ // A name from the other namespace is a miss, not another item's labels.
+ const crossed = await fetch(
+ `${backend.origin}/api/v1/image_map/image_labels?image_name=${video.image_name}&kind=image`
+ );
+ assert.equal(crossed.status, 404);
+ });
+});
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 97f7df94ca..4225206c28 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -130,6 +130,42 @@ const timestamp = (state) => {
return value;
};
+/**
+ * The projection's timestamp. Fixed, and deliberately NOT `timestamp(state)`:
+ * that advances the fixture's mutation clock on every call, so the map's two
+ * endpoints would answer with different `updated_at` values and the client
+ * would discard every cluster-label response as belonging to another
+ * projection — and it would drift the clock on plain GETs besides.
+ */
+const IMAGE_MAP_UPDATED_AT = '2026-01-01 00:00:00.000';
+
+/**
+ * One map point per gallery item, at deterministic coordinates so the map is
+ * comparable across runs. Cluster ids are assigned round-robin rather than
+ * derived from position — nothing here runs DBSCAN, and the client only needs
+ * ids that are stable and non-empty. Videos plot beside images, which is the
+ * whole point of the kind field.
+ */
+const imageMapPoints = (state, includeVideos) => {
+ const items = [
+ ...[...state.images.keys()].map((name) => ({ kind: 'image', name })),
+ ...(includeVideos ? [...state.videos.keys()].map((name) => ({ kind: 'video', name })) : []),
+ ];
+
+ return items.map((item, index) => {
+ const angle = index * 2.399;
+ const cluster = index % 3 === 2 ? -1 : index % 2;
+
+ return {
+ cluster,
+ image_name: item.name,
+ kind: item.kind,
+ x: Math.cos(angle) * (2 + cluster) + cluster * 6,
+ y: Math.sin(angle) * (2 + cluster),
+ };
+ });
+};
+
const summaryOf = (project) => ({
board_id: project.board_id,
created_at: project.created_at,
@@ -666,6 +702,65 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
});
}
+ // --- Image map -------------------------------------------------------
+ // Enough of the semantic map for the widget to render: every fixture
+ // item gets a point, laid out on a deterministic spiral so clusters are
+ // stable across runs. Videos are served only when the client asks for
+ // them, exactly as the backend does.
+ if (method === 'GET' && path === '/api/v1/image_map/points') {
+ const includeVideos = url.searchParams.get('include_videos') === 'true';
+ const points = imageMapPoints(state, includeVideos);
+
+ return json(200, {
+ cluster_eps: 0.5,
+ point_count: points.length,
+ points,
+ stale: false,
+ state: 'ready',
+ updated_at: IMAGE_MAP_UPDATED_AT,
+ visible_hash: `visible-${String(includeVideos)}`,
+ });
+ }
+
+ if (method === 'GET' && path === '/api/v1/image_map/cluster_labels') {
+ return json(200, {
+ labels: { 0: { alternates: ['sunset', 'coastline'], label: 'beaches' } },
+ // Same value and same kind filter as /points: the client compares
+ // both before it will use a label set.
+ updated_at: IMAGE_MAP_UPDATED_AT,
+ visible_hash: `visible-${String(url.searchParams.get('include_videos') === 'true')}`,
+ });
+ }
+
+ if (method === 'GET' && path === '/api/v1/image_map/image_labels') {
+ const name = url.searchParams.get('image_name') ?? '';
+ const isVideo = url.searchParams.get('kind') === 'video';
+ const exists = isVideo ? state.videos.has(name) : state.images.has(name);
+
+ // 404 for an item this namespace does not hold, like the real route —
+ // which is what lets the label cache's definitive-miss path be
+ // exercised against the mock at all.
+ if (!exists) {
+ return json(404, { detail: 'This item has no stored embedding to label' });
+ }
+
+ return json(200, { alternates: ['surf', 'shoreline'], label: isVideo ? 'clip' : 'photo' });
+ }
+
+ if (method === 'GET' && path === '/api/v1/image_map/status') {
+ const total = state.images.size + state.videos.size;
+
+ return json(200, {
+ enabled: true,
+ index: { embedded: total, failed: 0, total },
+ projection: { point_count: total, stale: false, state: 'ready', updated_at: IMAGE_MAP_UPDATED_AT },
+ });
+ }
+
+ if (method === 'POST' && path === '/api/v1/image_map/refresh') {
+ return json(200, { enqueued: true });
+ }
+
if (method === 'GET' && path === '/api/v1/app/version') {
return json(200, { version: 'fixture' });
}
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts
index 81fedc88e2..0c4c88bb98 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts
@@ -28,25 +28,39 @@ describe('external image registry', () => {
describe('image cluster registry', () => {
it('holds a single slot: registering a new cluster evicts the previous one', () => {
- const firstId = registerImageCluster(['a.png', 'b.png'], 'first cluster');
+ const firstId = registerImageCluster(['image:a.png', 'image:b.png'], 'first cluster');
- expect(getImageCluster(firstId)).toEqual({ imageNames: ['a.png', 'b.png'], label: 'first cluster' });
+ expect(getImageCluster(firstId)).toEqual({ itemKeys: ['image:a.png', 'image:b.png'], label: 'first cluster' });
- const secondId = registerImageCluster(['c.png'], 'second cluster');
+ const secondId = registerImageCluster(['image:c.png'], 'second cluster');
expect(secondId).not.toBe(firstId);
expect(getImageCluster(firstId)).toBe(null);
- expect(getImageCluster(secondId)).toEqual({ imageNames: ['c.png'], label: 'second cluster' });
+ expect(getImageCluster(secondId)).toEqual({ itemKeys: ['image:c.png'], label: 'second cluster' });
+ });
+
+ it('prunes a deleted video member, which is why the delete patch keys by kind', () => {
+ // Video deletions used to be filtered out of the prune, so a cluster kept
+ // counting a clip that no longer existed: the member list is client-owned,
+ // so no refetch reconciles it, and the trailing page holds a cell that can
+ // never hydrate.
+ const clusterId = registerImageCluster(['image:a.png', 'video:clip.mp4'], 'beaches');
+
+ const rollback = pruneImageClusterMembers(['video:clip.mp4']);
+
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:a.png']);
+ rollback();
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:a.png', 'video:clip.mp4']);
});
it('prunes deleted members with a rollback, preserving order', () => {
- const clusterId = registerImageCluster(['a.png', 'b.png', 'c.png'], 'beaches');
- const rollback = pruneImageClusterMembers(['b.png', 'unrelated.png']);
+ const clusterId = registerImageCluster(['image:a.png', 'image:b.png', 'image:c.png'], 'beaches');
+ const rollback = pruneImageClusterMembers(['image:b.png', 'image:unrelated.png']);
- expect(getImageCluster(clusterId)?.imageNames).toEqual(['a.png', 'c.png']);
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:a.png', 'image:c.png']);
rollback();
- expect(getImageCluster(clusterId)?.imageNames).toEqual(['a.png', 'b.png', 'c.png']);
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:a.png', 'image:b.png', 'image:c.png']);
});
it('rolls back only its own removals when another prune interleaves', () => {
@@ -55,31 +69,31 @@ describe('image cluster registry', () => {
// resurrect the second deletion's image; an identity guard would skip the
// restore entirely and strand the failed deletion's image outside the
// cluster for good.
- const clusterId = registerImageCluster(['a.png', 'b.png', 'c.png'], 'beaches');
- const rollbackFirst = pruneImageClusterMembers(['a.png']);
+ const clusterId = registerImageCluster(['image:a.png', 'image:b.png', 'image:c.png'], 'beaches');
+ const rollbackFirst = pruneImageClusterMembers(['image:a.png']);
- pruneImageClusterMembers(['b.png']);
- expect(getImageCluster(clusterId)?.imageNames).toEqual(['c.png']);
+ pruneImageClusterMembers(['image:b.png']);
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:c.png']);
rollbackFirst();
- expect(getImageCluster(clusterId)?.imageNames).toEqual(['a.png', 'c.png']);
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:a.png', 'image:c.png']);
});
it('makes pruning a no-op when nothing matches, and rollback a no-op once superseded', () => {
- const clusterId = registerImageCluster(['a.png'], 'beaches');
+ const clusterId = registerImageCluster(['image:a.png'], 'beaches');
// Nothing to prune: the entry is untouched.
- pruneImageClusterMembers(['other.png']);
- expect(getImageCluster(clusterId)?.imageNames).toEqual(['a.png']);
+ pruneImageClusterMembers(['image:other.png']);
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:a.png']);
// A rollback captured before a newer registration must not resurrect the
// old list into the newer cluster's slot.
- const rollback = pruneImageClusterMembers(['a.png']);
- const newerId = registerImageCluster(['x.png'], 'newer');
+ const rollback = pruneImageClusterMembers(['image:a.png']);
+ const newerId = registerImageCluster(['image:x.png'], 'newer');
rollback();
expect(getImageCluster(clusterId)).toBe(null);
- expect(getImageCluster(newerId)?.imageNames).toEqual(['x.png']);
+ expect(getImageCluster(newerId)?.itemKeys).toEqual(['image:x.png']);
});
});
@@ -150,7 +164,7 @@ describe('parseGallerySemanticReference', () => {
});
it('parses cluster references while registered and drops dangling cluster keys', () => {
- const clusterId = registerImageCluster(['a.png', 'b.png'], 'beaches');
+ const clusterId = registerImageCluster(['image:a.png', 'image:b.png'], 'beaches');
expect(parseGallerySemanticReference({ clusterId, kind: 'cluster', label: 'beaches' })).toEqual({
clusterId,
@@ -166,7 +180,7 @@ describe('parseGallerySemanticReference', () => {
});
// Registering evicts prior entries, so a stale key reads as no search —
// exactly how a reload behaves.
- registerImageCluster(['c.png'], 'newer');
+ registerImageCluster(['image:c.png'], 'newer');
expect(parseGallerySemanticReference({ clusterId, kind: 'cluster', label: 'beaches' })).toBe(null);
});
});
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts
index fcfc20a7ec..6556f463ed 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts
@@ -1,3 +1,5 @@
+import type { GalleryItemKey } from './items';
+
/**
* Identity of a semantic gallery search: a text prompt, a gallery image, a
* web image URL, a dropped file held in the external-image registry, or an
@@ -91,17 +93,21 @@ export const getExternalImageFile = (fileId: string): { blob: Blob; label: strin
/*
* In-memory registry for image-map cluster queries, mirroring the file
* registry above: a cluster's member list (which can run to thousands of
- * names) cannot live in persisted widget values, so the persisted value keeps
+ * items) cannot live in persisted widget values, so the persisted value keeps
* a registry key, and a key that no longer resolves (e.g. after a reload)
* reads as a cleared search. Only one cluster query is active at a time, so
* registering a new cluster evicts the previous one.
+ *
+ * Members are item keys rather than bare names: a cluster on the map can hold
+ * videos as well as images, and the gallery resolves each member through the
+ * endpoint its kind names.
*/
let nextClusterId = 0;
-const clusters = new Map<string, { imageNames: string[]; label: string }>();
+const clusters = new Map<string, { itemKeys: GalleryItemKey[]; label: string }>();
-export const registerImageCluster = (imageNames: string[], label: string): string => {
+export const registerImageCluster = (itemKeys: GalleryItemKey[], label: string): string => {
nextClusterId += 1;
// Same shape as file ids: the random token keeps a persisted id from a
// previous JS realm (another tab, a reload) from resolving to this realm's
@@ -109,41 +115,41 @@ export const registerImageCluster = (imageNames: string[], label: string): strin
const clusterId = `cluster-${String(nextClusterId)}-${Math.random().toString(36).slice(2, 10)}`;
clusters.clear();
- clusters.set(clusterId, { imageNames, label });
+ clusters.set(clusterId, { itemKeys, label });
return clusterId;
};
-export const getImageCluster = (clusterId: string): { imageNames: string[]; label: string } | null =>
+export const getImageCluster = (clusterId: string): { itemKeys: GalleryItemKey[]; label: string } | null =>
clusters.get(clusterId) ?? null;
/**
- * Drops deleted images from the registered cluster, in step with the gallery's
+ * Drops deleted items from the registered cluster, in step with the gallery's
* optimistic cache patch: the member list is client-owned, so without this the
- * cluster view's total (and its trailing page) would keep counting images that
- * no longer exist. Returns a rollback that puts back exactly the names THIS
+ * cluster view's total (and its trailing page) would keep counting items that
+ * no longer exist. Returns a rollback that puts back exactly the members THIS
* call removed — a no-op once a different registration owns the slot.
*/
-export const pruneImageClusterMembers = (imageNames: readonly string[]): (() => void) => {
+export const pruneImageClusterMembers = (itemKeys: readonly GalleryItemKey[]): (() => void) => {
const entry = [...clusters.entries()].at(0);
- if (!entry || imageNames.length === 0) {
+ if (!entry || itemKeys.length === 0) {
return () => undefined;
}
const [clusterId, cluster] = entry;
- const requested = new Set(imageNames);
- const originalNames = cluster.imageNames;
- const removedNames = originalNames.filter((name) => requested.has(name));
+ const requested = new Set(itemKeys);
+ const originalKeys = cluster.itemKeys;
+ const removedKeys = originalKeys.filter((key) => requested.has(key));
- if (removedNames.length === 0) {
+ if (removedKeys.length === 0) {
return () => undefined;
}
- const removed = new Set(removedNames);
+ const removed = new Set(removedKeys);
clusters.set(clusterId, {
- imageNames: originalNames.filter((name) => !removed.has(name)),
+ itemKeys: originalKeys.filter((key) => !removed.has(key)),
label: cluster.label,
});
@@ -158,12 +164,12 @@ export const pruneImageClusterMembers = (imageNames: readonly string[]): (() =>
// that a concurrent deletion's prune (or its rollback) landing in between
// survives: whatever this call did not remove keeps whatever state the
// other call left it in. Restoring the captured array instead would either
- // resurrect that deletion's images or — guarded on identity — skip the
- // restore entirely and strand a failed deletion's image outside the list.
- const restored = new Set([...current.imageNames, ...removedNames]);
+ // resurrect that deletion's items or — guarded on identity — skip the
+ // restore entirely and strand a failed deletion's item outside the list.
+ const restored = new Set([...current.itemKeys, ...removedKeys]);
clusters.set(clusterId, {
- imageNames: originalNames.filter((name) => restored.has(name)),
+ itemKeys: originalKeys.filter((key) => restored.has(key)),
label: current.label,
});
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index a60133e0bd..25eed60260 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -19,6 +19,7 @@ import type {
GalleryView,
} from '@features/gallery/core/types';
+import { parseGalleryItemKey } from '@features/gallery/core/items';
import { getExternalImageFile, getImageCluster } from '@features/gallery/core/semanticImageQuery';
import { isTimestampInRange } from '@platform/search/dateTokens';
import {
@@ -823,28 +824,38 @@ export const listGalleryItems = async ({
export const SEMANTIC_SEARCH_MAX_RESULTS = 500;
export interface GallerySemanticResult {
- imageName: string;
+ ref: GalleryItemRef;
/** Cosine similarity to the query; higher is more similar. */
score: number;
}
-type SemanticSearchBody = { results: { image_name: string; score: number }[] };
+type SemanticSearchBody = { results: { image_name: string; kind?: string; score: number }[] };
const toSemanticResults = (body: SemanticSearchBody): GallerySemanticResult[] =>
- body.results.map((result) => ({ imageName: result.image_name, score: result.score }));
+ // `image_name` carries the name whatever the kind is; `kind` says which
+ // namespace it belongs to. Only `video` names the other namespace — anything
+ // else reads as an image, which is the kind every hit used to be.
+ body.results.map((result) => ({
+ ref: { kind: result.kind === 'video' ? 'video' : 'image', name: result.image_name },
+ score: result.score,
+ }));
/**
- * Ranks the caller's accessible images by similarity to the query. Text and
- * gallery-image queries hit the GET endpoint; URLs and dropped files POST to
- * the by-image endpoint (the file as multipart from the external-image
+ * Ranks the caller's accessible gallery items by similarity to the query. Text
+ * and gallery-image queries hit the GET endpoint; URLs and dropped files POST
+ * to the by-image endpoint (the file as multipart from the external-image
* registry).
+ *
+ * `include_videos` is what opts this client into video results: the backend
+ * indexes them either way and serves them only to clients that say they can
+ * resolve each hit through the endpoint its kind names, which this one does.
*/
export const searchGallerySemantic = async (
query: Exclude<GallerySemanticQuery, { kind: 'cluster' }>,
{ limit = SEMANTIC_SEARCH_MAX_RESULTS, signal }: { limit?: number; signal?: AbortSignal } = {}
): Promise<GallerySemanticResult[]> => {
if (query.kind === 'url') {
- const params = toSearchParams({ image_url: query.url, limit });
+ const params = toSearchParams({ image_url: query.url, include_videos: true, limit });
return toSemanticResults(
await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search_by_image?${params}`, {
@@ -866,16 +877,21 @@ export const searchGallerySemantic = async (
form.append('image', entry.blob, entry.label || 'image');
return toSemanticResults(
- await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search_by_image?${toSearchParams({ limit })}`, {
- body: form,
- method: 'POST',
- signal,
- })
+ await apiFetchJson<SemanticSearchBody>(
+ `/api/v1/image_map/search_by_image?${toSearchParams({ include_videos: true, limit })}`,
+ {
+ body: form,
+ method: 'POST',
+ signal,
+ }
+ )
);
}
const params = toSearchParams(
- query.kind === 'text' ? { limit, q: query.query } : { image_name: query.imageName, limit }
+ query.kind === 'text'
+ ? { include_videos: true, limit, q: query.query }
+ : { image_name: query.imageName, include_videos: true, limit }
);
return toSemanticResults(await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search?${params}`, { signal }));
@@ -884,8 +900,8 @@ export const searchGallerySemantic = async (
/**
* The ranked result set as item refs, in relevance order. Pages hydrate
* slices of this list (`hydrateGalleryDateBoardItemPage`), and range
- * selection / deletion neighbors read it directly. Semantic results are
- * image-only.
+ * selection / deletion neighbors read it directly. Results carry both media
+ * kinds: an indexed gallery is its images plus its videos.
*/
export const listSemanticGalleryItemNames = async ({
query,
@@ -897,19 +913,18 @@ export const listSemanticGalleryItemNames = async ({
// A cluster query is an explicit member list held client-side (in proximity
// order from the clicked map point); there is nothing to ask the server.
if (query.kind === 'cluster') {
- const cluster = getImageCluster(query.clusterId);
- const imageNames = cluster?.imageNames ?? [];
+ const itemKeys = getImageCluster(query.clusterId)?.itemKeys ?? [];
return {
- items: imageNames.map((name) => ({ kind: 'image', name })),
- total: imageNames.length,
+ items: itemKeys.map(parseGalleryItemKey),
+ total: itemKeys.length,
};
}
const results = await searchGallerySemantic(query, { signal });
return {
- items: results.map((result) => ({ kind: 'image', name: result.imageName })),
+ items: results.map((result) => result.ref),
total: results.length,
};
};
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
index 4babc96255..eb09c7be5b 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts
@@ -2,6 +2,7 @@ import type { GalleryItem, GalleryItemMutationResult, GalleryItemsPage } from '@
import type { GalleryBoard } from '@features/gallery/core/types';
import type { AccountScope } from '@platform/state/accountLifecycle';
+import { getImageCluster, registerImageCluster } from '@features/gallery/core/semanticImageQuery';
import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
import { InfiniteQueryObserver, QueryClient, type InfiniteData } from '@tanstack/react-query';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -196,6 +197,24 @@ describe('Gallery item cache patches', () => {
expect(getData(client, key).pages[0]?.items[0]).toEqual({ ...target, starred: true });
});
+ it('prunes a deleted video from the active cluster filter, and restores it on rollback', () => {
+ // The cluster's member list is client-owned, so nothing on the server can
+ // reconcile it: a video deletion that skipped the prune would leave the
+ // cluster view counting a clip that no longer exists, with a trailing page
+ // cell that can never hydrate.
+ const client = createClient();
+ const clusterId = registerImageCluster(['image:kept.png', 'video:gone.mp4'], 'beaches');
+
+ const rollback = patchGalleryItemCaches(client, {
+ kind: 'delete',
+ result: getResult([{ kind: 'video', name: 'gone.mp4' }]),
+ });
+
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:kept.png']);
+ rollback();
+ expect(getImageCluster(clusterId)?.itemKeys).toEqual(['image:kept.png', 'video:gone.mp4']);
+ });
+
it('deletes matching qualified items across pages and keeps each page total consistent', () => {
const client = createClient();
const firstTarget = createItem('shared-name', 'board-1', false, 'image');
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
index 08fa4d7864..27a04609e0 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts
@@ -218,9 +218,7 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCa
// never reconcile it: prune it in the same optimistic step (and restore it
// with the same rollback) as the list caches it feeds.
const rollbackClusterMembers =
- patch.kind === 'delete'
- ? pruneImageClusterMembers(patch.result.succeeded.filter((ref) => ref.kind === 'image').map((ref) => ref.name))
- : null;
+ patch.kind === 'delete' ? pruneImageClusterMembers(patch.result.succeeded.map(toGalleryItemKey)) : null;
const rollbackEntries: ItemCacheRollbackEntry[] = [];
for (const query of getGalleryItemListQueries(client)) {
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts
index a085339821..edd9cf4141 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts
@@ -39,10 +39,31 @@ describe('searchGallerySemantic', () => {
const results = await searchGallerySemantic({ kind: 'text', query: 'red barn' }, { limit: 50 });
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/search?limit=50&q=red+barn', {
- signal: undefined,
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith(
+ '/api/v1/image_map/search?include_videos=true&limit=50&q=red+barn',
+ {
+ signal: undefined,
+ }
+ );
+ expect(results).toEqual([{ ref: { kind: 'image', name: 'a.png' }, score: 0.9 }]);
+ });
+
+ it('carries each hit kind so videos hydrate through their own endpoint', async () => {
+ mocks.apiFetchJson.mockResolvedValue({
+ results: [
+ { image_name: 'clip.mp4', kind: 'video', score: 0.9 },
+ { image_name: 'a.png', kind: 'image', score: 0.5 },
+ ],
});
- expect(results).toEqual([{ imageName: 'a.png', score: 0.9 }]);
+
+ const results = await searchGallerySemantic({ kind: 'text', query: 'surf' });
+
+ // Reading a video hit as an image sends the gallery to /images/i/<name>,
+ // which 404s — a ranked result that renders as a broken tile.
+ expect(results).toEqual([
+ { ref: { kind: 'video', name: 'clip.mp4' }, score: 0.9 },
+ { ref: { kind: 'image', name: 'a.png' }, score: 0.5 },
+ ]);
});
it('builds image-similarity queries with the default result cap', async () => {
@@ -50,9 +71,12 @@ describe('searchGallerySemantic', () => {
await searchGallerySemantic({ imageName: 'ref.png', kind: 'image' });
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/search?image_name=ref.png&limit=500', {
- signal: undefined,
- });
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith(
+ '/api/v1/image_map/search?image_name=ref.png&include_videos=true&limit=500',
+ {
+ signal: undefined,
+ }
+ );
});
it('POSTs url queries to the by-image endpoint', async () => {
@@ -61,10 +85,10 @@ describe('searchGallerySemantic', () => {
const results = await searchGallerySemantic({ kind: 'url', url: 'https://example.com/cat.jpg' }, { limit: 25 });
expect(mocks.apiFetchJson).toHaveBeenCalledWith(
- '/api/v1/image_map/search_by_image?image_url=https%3A%2F%2Fexample.com%2Fcat.jpg&limit=25',
+ '/api/v1/image_map/search_by_image?image_url=https%3A%2F%2Fexample.com%2Fcat.jpg&include_videos=true&limit=25',
{ method: 'POST', signal: undefined }
);
- expect(results).toEqual([{ imageName: 'a.png', score: 0.8 }]);
+ expect(results).toEqual([{ ref: { kind: 'image', name: 'a.png' }, score: 0.8 }]);
});
it('POSTs registered dropped files as multipart and fails clearly when the blob is gone', async () => {
@@ -75,7 +99,7 @@ describe('searchGallerySemantic', () => {
const [path, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
- expect(path).toBe('/api/v1/image_map/search_by_image?limit=10');
+ expect(path).toBe('/api/v1/image_map/search_by_image?include_videos=true&limit=10');
expect(init.method).toBe('POST');
expect(init.body).toBeInstanceOf(FormData);
expect((init.body as FormData).get('image')).toBeInstanceOf(Blob);
@@ -134,19 +158,21 @@ describe('listSemanticGalleryItemNames', () => {
it('answers cluster queries from the registry without a server round trip', async () => {
mocks.apiFetchJson.mockReset();
- const clusterId = registerImageCluster(['near.png', 'far.png'], 'beaches');
+ const clusterId = registerImageCluster(['image:near.png', 'video:clip.mp4'], 'beaches');
await expect(listSemanticGalleryItemNames({ query: { clusterId, kind: 'cluster' } })).resolves.toEqual({
items: [
{ kind: 'image', name: 'near.png' },
- { kind: 'image', name: 'far.png' },
+ // A clip clustered with the images it resembles is listed as a video,
+ // so the gallery hydrates it through the videos endpoint.
+ { kind: 'video', name: 'clip.mp4' },
],
total: 2,
});
// An evicted key (another cluster registered, or a reload) degrades to an
// empty list rather than an error — the parse layer clears the reference
// before the UI would ever show that.
- registerImageCluster(['other.png'], 'newer');
+ registerImageCluster(['image:other.png'], 'newer');
await expect(listSemanticGalleryItemNames({ query: { clusterId, kind: 'cluster' } })).resolves.toEqual({
items: [],
total: 0,
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/api.ts b/invokeai/frontend/webv2/src/workbench/image-map/api.ts
index 80b4fc5894..cfa79d68dc 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/api.ts
@@ -1,3 +1,6 @@
+import type { GalleryItemKey, GalleryItemRef } from '@features/gallery/contracts';
+
+import { toGalleryItemKey } from '@features/gallery/contracts';
import { apiFetchJson } from '@platform/transport/http';
import type { ImageIndexCounts } from './indexProgress';
@@ -8,7 +11,15 @@ export type ImageMapState = 'disabled' | 'model_missing' | 'empty' | 'computing'
export interface ImageMapPoint {
x: number;
y: number;
- imageName: string;
+ /** The gallery item this point stands for; videos plot beside images. */
+ item: GalleryItemRef;
+ /**
+ * `item`'s gallery key, derived once here. Every comparison the map makes —
+ * hit-testing a click, masking the selection, keying a hover — is against a
+ * key, and a 100k-point map re-scans on each wheel-zoom event, so deriving
+ * it per comparison would allocate a string per point per frame.
+ */
+ key: GalleryItemKey;
/** DBSCAN cluster label; -1 means unclustered noise. */
cluster: number;
}
@@ -31,7 +42,10 @@ export interface ImageMapPoints {
interface BackendImageMapPoint {
x: number;
y: number;
+ /** The item's name, whatever its kind; `kind` says which namespace it is in. */
image_name: string;
+ /** Optional on the wire: a backend older than indexed videos omits it. */
+ kind?: string;
cluster: number;
}
@@ -46,16 +60,25 @@ interface BackendImageMapPointsResponse {
updated_at: string | null;
}
+/**
+ * Opts this client into video items. The backend indexes videos either way and
+ * serves them only to clients that resolve each item through the endpoint its
+ * `kind` names — which this one does, so every map request asks for them.
+ */
+const INCLUDE_VIDEOS_PARAM = { include_videos: 'true' } as const;
+
const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({
clusterEps: body.cluster_eps ?? null,
modelName: body.model_name ?? null,
pointCount: body.point_count,
- points: body.points.map((point) => ({
- cluster: point.cluster,
- imageName: point.image_name,
- x: point.x,
- y: point.y,
- })),
+ points: body.points.map((point) => {
+ // Only `video` names the other namespace; anything else is an image, so an
+ // unexpected value degrades to the kind that has always been on the map
+ // rather than producing an item no endpoint can resolve.
+ const item: GalleryItemRef = { kind: point.kind === 'video' ? 'video' : 'image', name: point.image_name };
+
+ return { cluster: point.cluster, item, key: toGalleryItemKey(item), x: point.x, y: point.y };
+ }),
stale: body.stale,
state: body.state,
updatedAt: body.updated_at ?? null,
@@ -63,7 +86,7 @@ const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({
});
export const fetchImageMapPoints = async (options?: { eps?: number; minSamples?: number }): Promise<ImageMapPoints> => {
- const query = new URLSearchParams();
+ const query = new URLSearchParams(INCLUDE_VIDEOS_PARAM);
if (options?.eps !== undefined) {
query.set('eps', String(options.eps));
@@ -99,7 +122,13 @@ interface BackendImageMapStatusResponse {
* the counts are the one thing no other call returns.
*/
export const fetchImageMapStatus = async (): Promise<ImageMapStatus> => {
- const body = await apiFetchJson<BackendImageMapStatusResponse>('/api/v1/image_map/status');
+ // Sent for consistency with the map's other calls: this reader keeps only
+ // `index` (which counts both kinds), but the response's projection half is
+ // kind-filtered by this flag, and a future reader of it should not have to
+ // discover that the call it inherited asked for a different map.
+ const body = await apiFetchJson<BackendImageMapStatusResponse>(
+ `/api/v1/image_map/status?${new URLSearchParams(INCLUDE_VIDEOS_PARAM).toString()}`
+ );
if (!body.index) {
return { index: null };
@@ -141,7 +170,9 @@ export const fetchImageMapClusterLabels = async (options?: {
eps?: number;
minSamples?: number;
}): Promise<ImageMapClusterLabels> => {
- const query = new URLSearchParams();
+ // Must match /points exactly: the two responses' visible hashes are compared
+ // before the labels are used, and a set difference discards every label.
+ const query = new URLSearchParams(INCLUDE_VIDEOS_PARAM);
if (options?.eps !== undefined) {
query.set('eps', String(options.eps));
@@ -177,8 +208,8 @@ export interface ImageMapImageLabels {
alternates: string[];
}
-export const fetchImageMapImageLabels = async (imageName: string): Promise<ImageMapImageLabels> => {
- const query = new URLSearchParams({ image_name: imageName });
+export const fetchImageMapImageLabels = async (item: GalleryItemRef): Promise<ImageMapImageLabels> => {
+ const query = new URLSearchParams({ image_name: item.name, kind: item.kind });
const body = await apiFetchJson<{ label: string; alternates?: string[] }>(
`/api/v1/image_map/image_labels?${query.toString()}`
);
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
index 48bb1a0981..3aa4905bba 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
@@ -1,3 +1,6 @@
+import type { GalleryItemRef } from '@features/gallery/contracts';
+
+import { toGalleryItemKey } from '@features/gallery/contracts';
import { describe, expect, it } from 'vitest';
import type { ImageMapPoint } from './api';
@@ -10,45 +13,73 @@ import {
HIGHLIGHTED_POINTS_TRACE,
} from './imageMapTraces';
-const point = (imageName: string, x: number, y: number, cluster: number): ImageMapPoint => ({
- cluster,
- imageName,
- x,
- y,
-});
+const point = (name: string, x: number, y: number, cluster: number): ImageMapPoint => {
+ const item: GalleryItemRef = { kind: name.endsWith('.mp4') ? 'video' : 'image', name };
+
+ return { cluster, item, key: toGalleryItemKey(item), x, y };
+};
const POINTS = [
point('a.png', 0, 0, 0),
point('b.png', 3, 0, 0),
point('c.png', 1, 0, 0),
+ // A clip that landed in the same cluster as the images it looks like.
+ point('clip.mp4', 2, 0, 0),
point('other.png', 50, 50, 1),
point('noise.png', -50, 50, -1),
];
describe('collectClusterSelection', () => {
it('returns the clicked cluster ordered by distance from the click', () => {
- expect(collectClusterSelection(POINTS, 'b.png')).toEqual(['b.png', 'c.png', 'a.png']);
+ // Members are kind-tagged keys: the gallery resolves each through the
+ // endpoint its kind names, so a video member cannot be read as an image.
+ expect(collectClusterSelection(POINTS, 'image:b.png')).toEqual([
+ 'image:b.png',
+ 'video:clip.mp4',
+ 'image:c.png',
+ 'image:a.png',
+ ]);
+ });
+
+ it('selects the cluster around a clicked video just as it does around an image', () => {
+ // b and c are equidistant from the clip, so input order breaks the tie.
+ expect(collectClusterSelection(POINTS, 'video:clip.mp4')).toEqual([
+ 'video:clip.mp4',
+ 'image:b.png',
+ 'image:c.png',
+ 'image:a.png',
+ ]);
});
- it('returns null for noise points and unknown names', () => {
- expect(collectClusterSelection(POINTS, 'noise.png')).toBeNull();
- expect(collectClusterSelection(POINTS, 'missing.png')).toBeNull();
+ it('returns null for noise points and unknown items', () => {
+ expect(collectClusterSelection(POINTS, 'image:noise.png')).toBeNull();
+ expect(collectClusterSelection(POINTS, 'image:missing.png')).toBeNull();
+ // The same name in the other namespace is a different item.
+ expect(collectClusterSelection(POINTS, 'image:clip.mp4')).toBeNull();
});
it('caps oversized clusters, keeping the nearest members', () => {
- const capped = collectClusterSelection(POINTS, 'a.png', 2);
- expect(capped).toEqual(['a.png', 'c.png']);
+ const capped = collectClusterSelection(POINTS, 'image:a.png', 2);
+ expect(capped).toEqual(['image:a.png', 'image:c.png']);
});
});
describe('buildHighlightedPointsTrace', () => {
+ it('keeps each kind\u2019s shape under the selection overlay', () => {
+ // The overlay is drawn over the base point, so a selected video that lost
+ // its diamond here would read as an image for as long as it is selected.
+ const multi = buildHighlightedPointsTrace(POINTS, new Set(['image:a.png' as const, 'video:clip.mp4' as const]));
+
+ expect(multi.marker.symbol).toEqual(['circle', 'diamond']);
+ });
+
it('draws only multi-selections, larger and outlined', () => {
- const single = buildHighlightedPointsTrace(POINTS, new Set(['a.png']));
+ const single = buildHighlightedPointsTrace(POINTS, new Set(['image:a.png' as const]));
expect(single.x).toEqual([]);
- const multi = buildHighlightedPointsTrace(POINTS, new Set(['a.png', 'c.png']));
+ const multi = buildHighlightedPointsTrace(POINTS, new Set(['image:a.png' as const, 'video:clip.mp4' as const]));
expect(multi.name).toBe(HIGHLIGHTED_POINTS_TRACE);
- expect(multi.customdata).toEqual(['a.png', 'c.png']);
+ expect(multi.customdata).toEqual(['image:a.png', 'video:clip.mp4']);
expect(multi.marker.size).toBe(8);
expect(multi.marker.line).toEqual({ color: '#FFFFFF', width: 1 });
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts
index cbd1fdcd0a..d15f90532f 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.ts
@@ -1,9 +1,14 @@
+import type { GalleryItemKey } from '@features/gallery/contracts';
+
import type { ImageMapPoint } from './api';
/**
* Cluster-click selection: everything in the clicked point's cluster,
* ordered by distance from the clicked point (PhotoMapAI's proximity
* ordering) so gallery multi-selection walks outward from the click.
+ *
+ * Members are item keys: a cluster groups by what the encoder saw, so a video
+ * sits in the same cluster as the images that look like it.
*/
/** Selection size guard; DBSCAN can put most of a huge gallery in one cluster. */
@@ -11,10 +16,10 @@ export const MAX_CLUSTER_SELECTION = 5000;
export const collectClusterSelection = (
points: ImageMapPoint[],
- clickedImageName: string,
+ clickedKey: GalleryItemKey,
cap: number = MAX_CLUSTER_SELECTION
-): string[] | null => {
- const clicked = points.find((point) => point.imageName === clickedImageName);
+): GalleryItemKey[] | null => {
+ const clicked = points.find((point) => point.key === clickedKey);
if (!clicked || clicked.cluster < 0) {
return null;
@@ -24,9 +29,9 @@ export const collectClusterSelection = (
.filter((point) => point.cluster === clicked.cluster)
.map((point) => ({
distance: (point.x - clicked.x) ** 2 + (point.y - clicked.y) ** 2,
- name: point.imageName,
+ key: point.key,
}))
.sort((left, right) => left.distance - right.distance)
.slice(0, cap)
- .map((entry) => entry.name);
+ .map((entry) => entry.key);
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts
index e42a4db86d..da20311f6b 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.test.ts
@@ -25,26 +25,61 @@ describe('image map image-label cache', () => {
accountLifecycle.activate('user-a');
});
- it('caches resolved labels per image name', async () => {
+ it('caches resolved labels per item', async () => {
mocks.apiFetchJson.mockResolvedValue({ alternates: ['boat', 'harbor'], label: 'ship' });
- await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: ['boat', 'harbor'], label: 'ship' });
- await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: ['boat', 'harbor'], label: 'ship' });
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ alternates: ['boat', 'harbor'],
+ label: 'ship',
+ });
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ alternates: ['boat', 'harbor'],
+ label: 'ship',
+ });
expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
});
- it('caches a definitive per-image failure but retries transient ones', async () => {
+ it('keeps labels for a video apart from an image with the same name', async () => {
+ // The fixtures ship exactly this: a video named like an image. Keying the
+ // cache by name alone would serve one item's tags for the other.
+ mocks.apiFetchJson.mockResolvedValueOnce({ alternates: [], label: 'photo' });
+ mocks.apiFetchJson.mockResolvedValueOnce({ alternates: [], label: 'clip' });
+
+ await expect(getImageLabels({ kind: 'image', name: 'shared.png' })).resolves.toEqual({
+ alternates: [],
+ label: 'photo',
+ });
+ await expect(getImageLabels({ kind: 'video', name: 'shared.png' })).resolves.toEqual({
+ alternates: [],
+ label: 'clip',
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
+ });
+
+ it('asks for video labels in the video namespace', async () => {
+ mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'surf' });
+
+ await getImageLabels({ kind: 'video', name: 'clip.mp4' });
+
+ // Without the kind the backend would look the name up among images and
+ // answer 404, which the cache would then remember as "no labels".
+ const [url] = mocks.apiFetchJson.mock.calls[0] as [string];
+ expect(url).toContain('image_name=clip.mp4');
+ expect(url).toContain('kind=video');
+ });
+
+ it('caches a definitive per-item failure but retries transient ones', async () => {
// 404: the image is simply not indexed; asking again cannot change that.
mocks.apiFetchJson.mockRejectedValue(new ApiError('not indexed', 404));
- await expect(getImageLabels('a.png')).resolves.toBeNull();
- await expect(getImageLabels('a.png')).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();
expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
// A network failure is retried on the next hover.
mocks.apiFetchJson.mockRejectedValue(new Error('offline'));
- await expect(getImageLabels('b.png')).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toBeNull();
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });
- await expect(getImageLabels('b.png')).resolves.toEqual({ alternates: [], label: 'ship' });
+ await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toEqual({ alternates: [], label: 'ship' });
});
it('backs a server error off instead of caching it as "this image has no labels"', async () => {
@@ -54,14 +89,17 @@ describe('image map image-label cache', () => {
// A backend or proxy restart mid-sweep must not permanently blank the
// tags of every image the pointer crossed during the outage...
mocks.apiFetchJson.mockRejectedValue(new ApiError('bad gateway', 502));
- await expect(getImageLabels('a.png')).resolves.toBeNull();
- await expect(getImageLabels('b.png')).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toBeNull();
// ...but a deterministic 500 must not refire on every hover either.
expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
vi.setSystemTime(Date.now() + 61_000);
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });
- await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'ship' });
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ alternates: [],
+ label: 'ship',
+ });
} finally {
vi.useRealTimers();
}
@@ -73,16 +111,19 @@ describe('image map image-label cache', () => {
try {
mocks.apiFetchJson.mockRejectedValue(new ApiError('still being prepared', 409));
- await expect(getImageLabels('a.png')).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();
// Server-wide, so sweeping the map must not fire one request per point.
- await expect(getImageLabels('b.png')).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toBeNull();
expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
// The vocabulary is built lazily by the index worker: a 409 can simply
// mean "not ready yet", so the cooldown must expire rather than latch.
vi.setSystemTime(Date.now() + 61_000);
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });
- await expect(getImageLabels('c.png')).resolves.toEqual({ alternates: [], label: 'ship' });
+ await expect(getImageLabels({ kind: 'image', name: 'c.png' })).resolves.toEqual({
+ alternates: [],
+ label: 'ship',
+ });
} finally {
vi.useRealTimers();
}
@@ -90,13 +131,13 @@ describe('image map image-label cache', () => {
it('keeps serving labels it already has while a 409 cooldown is active', async () => {
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });
- await getImageLabels('a.png');
+ await getImageLabels({ kind: 'image', name: 'a.png' });
mocks.apiFetchJson.mockRejectedValue(new ApiError('still being prepared', 409));
- await expect(getImageLabels('b.png')).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toBeNull();
// The cooldown suppresses new requests, never cached results.
- await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'ship' });
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({ alternates: [], label: 'ship' });
});
it('drops cached labels when a vocabulary rebuild lands', async () => {
@@ -104,28 +145,31 @@ describe('image map image-label cache', () => {
// makes every cached answer stale — including a cooldown that was only
// ever waiting for that rebuild.
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });
- await getImageLabels('a.png');
+ await getImageLabels({ kind: 'image', name: 'a.png' });
expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
clearImageLabels();
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'sailboat' });
- await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'sailboat' });
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ alternates: [],
+ label: 'sailboat',
+ });
});
it('clears the cooldown on account switch', async () => {
mocks.apiFetchJson.mockRejectedValue(new ApiError('index disabled', 409));
- await expect(getImageLabels('a.png')).resolves.toBeNull();
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toBeNull();
accountLifecycle.invalidate();
accountLifecycle.activate('user-b');
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'ship' });
- await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'ship' });
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({ alternates: [], label: 'ship' });
});
it('clears settled entries and stale in-flight results on account invalidation', async () => {
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'user-a-label' });
- await getImageLabels('a.png');
+ await getImageLabels({ kind: 'image', name: 'a.png' });
// A request still in flight when the account switches must not seed the
// next account's cache.
@@ -136,7 +180,7 @@ describe('image map image-label cache', () => {
resolveLate = resolve;
})
);
- const late = getImageLabels('b.png');
+ const late = getImageLabels({ kind: 'image', name: 'b.png' });
accountLifecycle.invalidate();
resolveLate({ alternates: [], label: 'stale-b-label' });
@@ -144,7 +188,13 @@ describe('image map image-label cache', () => {
accountLifecycle.activate('user-b');
mocks.apiFetchJson.mockResolvedValue({ alternates: [], label: 'user-b-label' });
- await expect(getImageLabels('a.png')).resolves.toEqual({ alternates: [], label: 'user-b-label' });
- await expect(getImageLabels('b.png')).resolves.toEqual({ alternates: [], label: 'user-b-label' });
+ await expect(getImageLabels({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ alternates: [],
+ label: 'user-b-label',
+ });
+ await expect(getImageLabels({ kind: 'image', name: 'b.png' })).resolves.toEqual({
+ alternates: [],
+ label: 'user-b-label',
+ });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts
index 622855bd1d..1bff4fdcbc 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageLabelCache.ts
@@ -1,3 +1,6 @@
+import type { GalleryItemRef } from '@features/gallery/contracts';
+
+import { toGalleryItemKey } from '@features/gallery/contracts';
import {
captureAccountScope,
isAccountScopeCurrent,
@@ -10,10 +13,10 @@ import type { ImageMapImageLabels } from './api';
import { fetchImageMapImageLabels } from './api';
/**
- * Image-name → vocabulary-labels cache for map hover cards. Labels derive from
- * the image's stored embedding, which never changes, and the labeling
+ * Item-key → vocabulary-labels cache for map hover cards. Labels derive from
+ * the item's stored embedding, which never changes, and the labeling
* vocabulary, which does: an admin can edit the supplementary term list. So
- * results (including "no labels for this image") are cached until a
+ * results (including "no labels for this item") are cached until a
* vocabulary rebuild lands, at which point `clearImageLabels` drops them.
*/
const labels = new Map<string, ImageMapImageLabels | null>();
@@ -56,16 +59,17 @@ export const clearImageLabels = (): void => {
unavailableUntil = 0;
};
-export const getImageLabels = (imageName: string): Promise<ImageMapImageLabels | null> => {
- // Checked before the cooldown: labels already fetched for this image stay
+export const getImageLabels = (item: GalleryItemRef): Promise<ImageMapImageLabels | null> => {
+ const key = toGalleryItemKey(item);
+ // Checked before the cooldown: labels already fetched for this item stay
// available even while a server-wide 409 is being backed off.
- const cached = labels.get(imageName);
+ const cached = labels.get(key);
if (cached !== undefined) {
return Promise.resolve(cached);
}
- const pending = inflight.get(imageName);
+ const pending = inflight.get(key);
if (pending) {
return pending;
@@ -76,12 +80,12 @@ export const getImageLabels = (imageName: string): Promise<ImageMapImageLabels |
}
const owner = captureAccountScope();
- const request = fetchImageMapImageLabels(imageName)
+ const request = fetchImageMapImageLabels(item)
.then((result): ImageMapImageLabels | null => {
// A resolution that raced an account switch must not seed the next
// account's cache.
if (isAccountScopeCurrent(owner)) {
- labels.set(imageName, result);
+ labels.set(key, result);
}
return result;
@@ -94,28 +98,28 @@ export const getImageLabels = (imageName: string): Promise<ImageMapImageLabels |
if (error instanceof ApiError && (error.status === 409 || error.status >= 500)) {
// Server-wide and possibly temporary: a 409 means the vocabulary may
// still be building, a 5xx that the backend is unwell. Back off rather
- // than cache anything per image — but back off, because this is driven
+ // than cache anything per item — but back off, because this is driven
// by pointer movement, and a deterministic failure would otherwise
// refire several times a second for the rest of the session.
unavailableUntil = Date.now() + UNAVAILABLE_COOLDOWN_MS;
} else if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {
- // The only definitive per-image answers: not indexed, or not visible
+ // The only definitive per-item answers: not indexed, or not visible
// to this account. Nothing about this session can change either.
- labels.set(imageName, null);
+ labels.set(key, null);
}
// Everything else (5xx, 429, a dropped connection) is transient and is
- // deliberately not cached: the next hover of this image retries.
+ // deliberately not cached: the next hover of this item retries.
return null;
})
.finally(() => {
// Release only this request's claim; an account switch already cleared
// the in-flight map.
- if (inflight.get(imageName) === request) {
- inflight.delete(imageName);
+ if (inflight.get(key) === request) {
+ inflight.delete(key);
}
});
- inflight.set(imageName, request);
+ inflight.set(key, request);
return request;
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
index 8b916878f8..3e238c80ad 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
@@ -19,6 +19,8 @@ vi.mock('@platform/transport/http', () => ({
getApiErrorMessage: (_error: unknown, fallback: string) => fallback,
}));
+import type { ImageMapPoint } from './api';
+
import { fetchImageMapPoints, fetchImageMapStatus, requestImageMapRefresh } from './api';
import { CLUSTER_PALETTE, getClusterColor, NOISE_COLOR } from './clusterPalette';
import {
@@ -38,10 +40,11 @@ import {
const BACKEND_RESPONSE = {
cluster_eps: 0.42,
- point_count: 2,
+ point_count: 3,
points: [
{ cluster: 0, image_name: 'a.png', x: 1.5, y: -2 },
{ cluster: -1, image_name: 'b.png', x: 0, y: 3 },
+ { cluster: 0, image_name: 'clip.mp4', kind: 'video', x: 2, y: -1 },
],
stale: false,
state: 'ready',
@@ -74,12 +77,23 @@ describe('image map api', () => {
const result = await fetchImageMapPoints();
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/points');
+ // include_videos is what opts this client into video points; without it the
+ // backend serves images only, however much of the gallery is indexed.
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/points?include_videos=true');
expect(result.state).toBe('ready');
- expect(result.pointCount).toBe(2);
+ expect(result.pointCount).toBe(3);
expect(result.clusterEps).toBe(0.42);
expect(result.visibleHash).toBe('hash-1');
- expect(result.points[0]).toEqual({ cluster: 0, imageName: 'a.png', x: 1.5, y: -2 });
+ expect(result.points[0]).toEqual({
+ cluster: 0,
+ item: { kind: 'image', name: 'a.png' },
+ key: 'image:a.png',
+ x: 1.5,
+ y: -2,
+ });
+ // A point without `kind` predates indexed videos and reads as an image.
+ expect(result.points[1]?.item).toEqual({ kind: 'image', name: 'b.png' });
+ expect(result.points[2]?.item).toEqual({ kind: 'video', name: 'clip.mp4' });
});
it('maps the model_missing state with the configured model name', async () => {
@@ -103,7 +117,9 @@ describe('image map api', () => {
await fetchImageMapPoints({ eps: 0.4, minSamples: 5 });
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/points?eps=0.4&min_samples=5');
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith(
+ '/api/v1/image_map/points?include_videos=true&eps=0.4&min_samples=5'
+ );
});
it('posts refresh requests', async () => {
@@ -141,7 +157,7 @@ describe('image map store', () => {
const snapshot = imageMapStore.getSnapshot();
expect(snapshot.loadState).toBe('loaded');
- expect(snapshot.data?.points).toHaveLength(2);
+ expect(snapshot.data?.points).toHaveLength(3);
expect(snapshot.error).toBeNull();
});
@@ -163,7 +179,11 @@ describe('image map store', () => {
// The labels endpoint must receive the exact eps the map was clustered
// with; the adaptive default could resolve differently on a drifted set.
await vi.waitFor(() => {
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/cluster_labels?eps=0.42');
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith(
+ // Must match /points: the client discards labels whose visible hash
+ // disagrees, which a different item set would guarantee.
+ '/api/v1/image_map/cluster_labels?include_videos=true&eps=0.42'
+ );
expect(imageMapStore.getSnapshot().clusterLabels).toEqual({
'0': { alternates: ['kittens', 'pets'], label: 'cats' },
});
@@ -222,7 +242,11 @@ describe('image map store', () => {
await refreshImageMapPoints();
await vi.waitFor(() => {
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/cluster_labels?eps=0.42');
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith(
+ // Must match /points: the client discards labels whose visible hash
+ // disagrees, which a different item set would guarantee.
+ '/api/v1/image_map/cluster_labels?include_videos=true&eps=0.42'
+ );
});
// Flush the response handler: cluster ids from a different visible set
// must not be applied to the rendered map.
@@ -246,7 +270,11 @@ describe('image map store', () => {
});
await refreshImageMapPoints();
await vi.waitFor(() => {
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/cluster_labels?eps=0.42');
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith(
+ // Must match /points: the client discards labels whose visible hash
+ // disagrees, which a different item set would guarantee.
+ '/api/v1/image_map/cluster_labels?include_videos=true&eps=0.42'
+ );
});
// L2: a newer refresh whose labels resolve first.
@@ -467,7 +495,7 @@ describe('image map store', () => {
const snapshot = imageMapStore.getSnapshot();
expect(snapshot.loadState).toBe('error');
expect(snapshot.error).toBe('Failed to load the image map');
- expect(snapshot.data?.points).toHaveLength(2);
+ expect(snapshot.data?.points).toHaveLength(3);
});
it('enters loading while retrying a failed points request', async () => {
@@ -580,19 +608,23 @@ describe('cluster palette', () => {
});
describe('trace builders', () => {
- const points = [
- { cluster: 0, imageName: 'a.png', x: 1, y: 2 },
- { cluster: -1, imageName: 'b.png', x: 3, y: 4 },
+ const points: ImageMapPoint[] = [
+ { cluster: 0, item: { kind: 'image', name: 'a.png' }, key: 'image:a.png', x: 1, y: 2 },
+ { cluster: -1, item: { kind: 'video', name: 'clip.mp4' }, key: 'video:clip.mp4', x: 3, y: 4 },
];
- it('builds the all-points scattergl trace with image names as customdata', () => {
+ it('builds the all-points scattergl trace with item keys as customdata', () => {
const trace = buildAllPointsTrace(points);
expect(trace.type).toBe('scattergl');
expect(trace.name).toBe(ALL_POINTS_TRACE);
expect(trace.x).toEqual([1, 3]);
expect(trace.y).toEqual([2, 4]);
- expect(trace.customdata).toEqual(['a.png', 'b.png']);
+ // Keys, not bare names: a click has to know which namespace to resolve in.
+ expect(trace.customdata).toEqual(['image:a.png', 'video:clip.mp4']);
+ // Kind gets the one channel colour and size do not already carry, so a
+ // clip is findable on the map without hovering every point.
+ expect(trace.marker.symbol).toEqual(['circle', 'diamond']);
expect((trace.marker.color as string[])[0]).toBe(getClusterColor(0));
// Noise points are dimmed relative to clustered points.
const opacities = trace.marker.opacity as number[];
@@ -716,7 +748,9 @@ describe('image map status', () => {
const status = await fetchImageMapStatus();
- expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/status');
+ // The same opt-in as /points: the projection counts in this response are
+ // filtered by it, so the two must agree about what the map contains.
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/status?include_videos=true');
// Failures are excluded, exactly as `ImageIndexStatus.pending` does it, so
// the queue can still drain to zero with images given up on.
expect(status.index).toEqual({ embedded: 30, failed: 2, pending: 68, total: 100 });
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
index a013d04128..9a3b222d5f 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
@@ -1,3 +1,4 @@
+import type { GalleryItemKey } from '@features/gallery/contracts';
import type { Layout } from 'plotly.js';
import type { ImageMapPoint } from './api';
@@ -33,18 +34,29 @@ export interface ScatterTrace {
color: string | string[];
opacity: number | number[];
size: number;
- symbol?: string;
+ symbol?: string | string[];
line?: { color: string; width: number };
};
}
+/** Marker shapes per media kind; see `buildAllPointsTrace`. */
+const IMAGE_SYMBOL = 'circle';
+const VIDEO_SYMBOL = 'diamond';
+
export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({
- customdata: points.map((point) => point.imageName),
+ // The gallery's item key, so a click or hover resolves back to the kind the
+ // point stands for — plotly carries strings, and a bare name would not say
+ // whether it names an image or a video.
+ customdata: points.map((point) => point.key),
hoverinfo: 'none',
marker: {
color: points.map((point) => getClusterColor(point.cluster)),
opacity: points.map((point) => (point.cluster < 0 ? NOISE_OPACITY : POINT_OPACITY)),
size: 5,
+ // Videos are diamonds. Color already carries the cluster, so kind needs
+ // the one remaining channel: without it a clip is pixel-identical to an
+ // image and can only be found by hovering points one at a time.
+ symbol: points.map((point) => (point.item.kind === 'video' ? VIDEO_SYMBOL : IMAGE_SYMBOL)),
},
mode: 'markers',
name: ALL_POINTS_TRACE,
@@ -55,17 +67,17 @@ export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({
/**
* The gallery's multi-selection (e.g. a cluster click), drawn larger with a
- * white outline over the base points. Empty when fewer than two images are
+ * white outline over the base points. Empty when fewer than two items are
* selected — a single selection is already marked by the gold target.
*/
export const buildHighlightedPointsTrace = (
points: ImageMapPoint[],
- selectedNames: ReadonlySet<string>
+ selectedKeys: ReadonlySet<GalleryItemKey>
): ScatterTrace => {
- const selected = selectedNames.size >= 2 ? points.filter((point) => selectedNames.has(point.imageName)) : [];
+ const selected = selectedKeys.size >= 2 ? points.filter((point) => selectedKeys.has(point.key)) : [];
return {
- customdata: selected.map((point) => point.imageName),
+ customdata: selected.map((point) => point.key),
// 'skip': highlighted points sit over their base points, which carry the
// same customdata — hit-testing should fall through to them.
hoverinfo: 'skip',
@@ -73,6 +85,9 @@ export const buildHighlightedPointsTrace = (
color: selected.map((point) => getClusterColor(point.cluster)),
line: { color: '#FFFFFF', width: 1 },
opacity: 1,
+ // The overlay sits on top of the base point, so it carries the kind's
+ // shape too — otherwise selecting a video turns its diamond into a circle.
+ symbol: selected.map((point) => (point.item.kind === 'video' ? VIDEO_SYMBOL : IMAGE_SYMBOL)),
size: 8,
},
mode: 'markers',
@@ -172,7 +187,7 @@ export interface ClusterAnnotation {
*
* Ordered by cluster size (largest first, cluster id as the tiebreak): array
* order is the keep-priority for declutterAnnotations, so when two labels
- * collide the one naming more images survives.
+ * collide the one naming more items survives.
*/
export const buildClusterAnnotations = (
points: ImageMapPoint[],
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts
index 27c3881b99..96a7099340 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts
@@ -12,7 +12,13 @@ import {
type AxisRanges,
} from './imageMapViewport';
-const point = (x: number, y: number): ImageMapPoint => ({ cluster: 0, imageName: `${x},${y}`, x, y });
+const point = (x: number, y: number): ImageMapPoint => ({
+ cluster: 0,
+ item: { kind: 'image', name: `${x},${y}` },
+ key: `image:${x},${y}`,
+ x,
+ y,
+});
describe('computePercentileRanges', () => {
it('returns null for no points and a non-degenerate box for one point', () => {
@@ -149,9 +155,10 @@ describe('fitRangesToAspect', () => {
it('keeps at least 90% of points in view for any container shape', () => {
// The user-facing contract for the first render: the fitted view must
// show (nearly) the whole map, however skewed the container.
- const points = Array.from({ length: 100 }, (_, index) => ({
+ const points: ImageMapPoint[] = Array.from({ length: 100 }, (_, index) => ({
cluster: 0,
- imageName: `p${index}.png`,
+ item: { kind: 'image', name: `p${index}.png` },
+ key: `image:p${index}.png` as const,
x: Math.sin(index * 2.399) * 13,
y: Math.cos(index * 1.618) * 7 + (index % 10),
}));
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.ts
index 2c1e7c16b2..458790360d 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.test.ts
@@ -1,53 +1,106 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
- resolveMany: vi.fn(),
+ resolve: vi.fn(),
}));
vi.mock('@features/gallery', () => ({
- galleryImages: { resolveMany: mocks.resolveMany },
+ galleryItems: { resolve: mocks.resolve },
}));
import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
import { getThumbnailUrl } from './thumbnailCache';
describe('image map thumbnail cache', () => {
beforeEach(() => {
- mocks.resolveMany.mockReset();
+ mocks.resolve.mockReset();
accountLifecycle.activate('user-a');
});
- it('caches resolved URLs per image name', async () => {
- mocks.resolveMany.mockResolvedValue([{ thumbnailUrl: '/thumbs/a.png' }]);
+ it('caches resolved URLs per item', async () => {
+ mocks.resolve.mockResolvedValue({ kind: 'image', thumbnailUrl: '/thumbs/a.png' });
- await expect(getThumbnailUrl('a.png')).resolves.toBe('/thumbs/a.png');
- await expect(getThumbnailUrl('a.png')).resolves.toBe('/thumbs/a.png');
- expect(mocks.resolveMany).toHaveBeenCalledTimes(1);
+ await expect(getThumbnailUrl({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ durationSeconds: null,
+ url: '/thumbs/a.png',
+ });
+ await expect(getThumbnailUrl({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ durationSeconds: null,
+ url: '/thumbs/a.png',
+ });
+ expect(mocks.resolve).toHaveBeenCalledTimes(1);
+ });
+
+ it('resolves a video through its own namespace rather than the image one', async () => {
+ // Same name in both namespaces: without the kind, the video's hover card
+ // would show the image's thumbnail.
+ mocks.resolve.mockImplementation((ref: { kind: string; name: string }) =>
+ Promise.resolve({ durationSeconds: 2.5, kind: ref.kind, thumbnailUrl: `/thumbs/${ref.kind}/${ref.name}` })
+ );
+
+ // The duration rides along for videos only: the hover card shows the same
+ // play badge the gallery tile does, and an image has none to show.
+ await expect(getThumbnailUrl({ kind: 'video', name: 'clip' })).resolves.toEqual({
+ durationSeconds: 2.5,
+ url: '/thumbs/video/clip',
+ });
+ await expect(getThumbnailUrl({ kind: 'image', name: 'clip' })).resolves.toEqual({
+ durationSeconds: null,
+ url: '/thumbs/image/clip',
+ });
+ expect(mocks.resolve).toHaveBeenCalledTimes(2);
+ });
+
+ it('remembers a definitive miss but retries a transient failure', async () => {
+ // Hovering is driven by pointer movement, so a deleted or hidden item has
+ // to be remembered — the by-names resolver this cache used to call
+ // returned an empty array for a miss, which was cached; the by-ref one
+ // throws, and the miss would otherwise be re-fetched on every dwell.
+ mocks.resolve.mockRejectedValue(new ApiError('gone', 404));
+
+ await expect(getThumbnailUrl({ kind: 'image', name: 'gone.png' })).resolves.toBeNull();
+ await expect(getThumbnailUrl({ kind: 'image', name: 'gone.png' })).resolves.toBeNull();
+ expect(mocks.resolve).toHaveBeenCalledTimes(1);
+
+ // A backend hiccup is not an answer about this item: caching it would
+ // blank that point's preview for the rest of the session.
+ mocks.resolve.mockRejectedValue(new ApiError('boom', 500));
+
+ await expect(getThumbnailUrl({ kind: 'image', name: 'flaky.png' })).resolves.toBeNull();
+ await expect(getThumbnailUrl({ kind: 'image', name: 'flaky.png' })).resolves.toBeNull();
+ expect(mocks.resolve).toHaveBeenCalledTimes(3);
});
it('clears settled entries and stale in-flight results on account invalidation', async () => {
- mocks.resolveMany.mockResolvedValue([{ thumbnailUrl: '/thumbs/user-a.png' }]);
- await getThumbnailUrl('a.png');
+ mocks.resolve.mockResolvedValue({ kind: 'image', thumbnailUrl: '/thumbs/user-a.png' });
+ await getThumbnailUrl({ kind: 'image', name: 'a.png' });
// A request still in flight when the account switches must not seed the
// next account's cache.
- let resolveLate: (images: { thumbnailUrl: string }[]) => void = () => {};
- mocks.resolveMany.mockImplementation(
+ let resolveLate: (item: { kind: string; thumbnailUrl: string }) => void = () => {};
+ mocks.resolve.mockImplementation(
() =>
new Promise((resolve) => {
resolveLate = resolve;
})
);
- const late = getThumbnailUrl('b.png');
+ const late = getThumbnailUrl({ kind: 'image', name: 'b.png' });
accountLifecycle.invalidate();
- resolveLate([{ thumbnailUrl: '/thumbs/stale-b.png' }]);
+ resolveLate({ kind: 'image', thumbnailUrl: '/thumbs/stale-b.png' });
await late;
accountLifecycle.activate('user-b');
- mocks.resolveMany.mockResolvedValue([{ thumbnailUrl: '/thumbs/user-b.png' }]);
- await expect(getThumbnailUrl('a.png')).resolves.toBe('/thumbs/user-b.png');
- await expect(getThumbnailUrl('b.png')).resolves.toBe('/thumbs/user-b.png');
+ mocks.resolve.mockResolvedValue({ kind: 'image', thumbnailUrl: '/thumbs/user-b.png' });
+ await expect(getThumbnailUrl({ kind: 'image', name: 'a.png' })).resolves.toEqual({
+ durationSeconds: null,
+ url: '/thumbs/user-b.png',
+ });
+ await expect(getThumbnailUrl({ kind: 'image', name: 'b.png' })).resolves.toEqual({
+ durationSeconds: null,
+ url: '/thumbs/user-b.png',
+ });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.ts b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.ts
index 628e98ab29..c33a34103b 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/thumbnailCache.ts
@@ -1,17 +1,29 @@
-import { galleryImages } from '@features/gallery';
+import type { GalleryItemRef } from '@features/gallery/contracts';
+
+import { galleryItems } from '@features/gallery';
+import { toGalleryItemKey } from '@features/gallery/contracts';
import {
captureAccountScope,
isAccountScopeCurrent,
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
/**
- * Image-name → thumbnail-URL cache for map hover previews. Thumbnail URLs are
- * derived from the immutable image name, so unlike full DTOs they never go
- * stale and can be cached for the session.
+ * What a hover card shows for one item: the thumbnail, plus the duration that
+ * makes a clip's card read like its gallery tile. Both derive from the
+ * immutable item name, so unlike full DTOs they never go stale.
*/
-const urls = new Map<string, string | null>();
-const inflight = new Map<string, Promise<string | null>>();
+export interface HoverThumbnail {
+ url: string;
+ /** Seconds, for videos only; images have no duration to show. */
+ durationSeconds: number | null;
+}
+
+// A video's thumbnail is the frame the index embedded it by, so the hover
+// preview shows exactly what the map placed.
+const urls = new Map<string, HoverThumbnail | null>();
+const inflight = new Map<string, Promise<HoverThumbnail | null>>();
// Thumbnail URLs are account-owned gallery data: drop them on login/logout so
// one account's map hovers can never serve another account's thumbnails.
@@ -23,42 +35,57 @@ registerAccountOwnedResource({
name: 'image-map-thumbnails',
});
-export const getThumbnailUrl = (imageName: string): Promise<string | null> => {
- const cached = urls.get(imageName);
+export const getThumbnailUrl = (item: GalleryItemRef): Promise<HoverThumbnail | null> => {
+ const key = toGalleryItemKey(item);
+ const cached = urls.get(key);
if (cached !== undefined) {
return Promise.resolve(cached);
}
- const pending = inflight.get(imageName);
+ const pending = inflight.get(key);
if (pending) {
return pending;
}
const owner = captureAccountScope();
- const request = galleryImages
- .resolveMany([imageName])
- .then((images) => {
- const url = images.at(0)?.thumbnailUrl ?? null;
+ const request = galleryItems
+ .resolve(item)
+ .then((resolved): HoverThumbnail => {
+ const thumbnail: HoverThumbnail = {
+ durationSeconds: resolved.kind === 'video' ? resolved.durationSeconds : null,
+ url: resolved.thumbnailUrl,
+ };
// A resolution that raced an account switch must not seed the next
// account's cache.
if (isAccountScopeCurrent(owner)) {
- urls.set(imageName, url);
+ urls.set(key, thumbnail);
+ }
+
+ return thumbnail;
+ })
+ .catch((error: unknown): null => {
+ // A deleted or no-longer-visible item answers definitively, and hovering
+ // is driven by pointer movement — so remember the miss, or every dwell
+ // over that point re-fetches the same 404 for the rest of the session.
+ // (The by-names resolver this replaced returned an empty array for a
+ // miss, which the `then` above cached; the by-ref one throws.)
+ if (error instanceof ApiError && (error.status === 403 || error.status === 404) && isAccountScopeCurrent(owner)) {
+ urls.set(key, null);
}
- return url;
+ return null;
})
- .catch(() => null)
.finally(() => {
// Release only this request's claim; an account switch already cleared
// the in-flight map.
- if (inflight.get(imageName) === request) {
- inflight.delete(imageName);
+ if (inflight.get(key) === request) {
+ inflight.delete(key);
}
});
- inflight.set(imageName, request);
+ inflight.set(key, request);
return request;
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx
index 8a8d669a38..aa2476936b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageIndexProgress.tsx
@@ -60,10 +60,10 @@ export const ImageIndexProgressPanel = ({
return (
<Stack align="center" gap="2" maxW="sm" textAlign="center" w="full">
- <Text fontWeight="semibold">Indexing images</Text>
+ <Text fontWeight="semibold">Indexing gallery</Text>
<Text color="fg.muted" fontSize="sm">
- Images are being embedded so they can be mapped. The map appears here on its own once enough of them are done —
- you can keep working in the meantime.
+ Images and videos are being embedded so they can be mapped. The map appears here on its own once enough of them
+ are done — you can keep working in the meantime.
</Text>
<Stack gap="1" mt="2" w="full">
<Progress.Root max={100} size="sm" value={progress.percent}>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx
index 0f58c87de7..452c091528 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx
@@ -38,9 +38,7 @@ export const ImageMapHeaderActions = (_props: WidgetViewProps) => {
icon={GroupIcon}
label="Toggle cluster selection mode"
tooltip={
- clickSelectsCluster
- ? 'Click shows the whole cluster in the gallery'
- : 'Click reveals one image in the gallery'
+ clickSelectsCluster ? 'Click shows the whole cluster in the gallery' : 'Click reveals one item in the gallery'
}
onCheckedChange={handleToggleClusterMode}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
index 608e43aff3..2c94ab70ad 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
@@ -1,20 +1,20 @@
-import type { ImageMapClusterLabelInfo, ImageMapImageLabels, ImageMapPoint } from '@workbench/image-map/api';
+import type { GalleryItemKey } from '@features/gallery/contracts';
+import type { ImageMapPoint } from '@workbench/image-map/api';
import type { ClusterAnnotation } from '@workbench/image-map/imageMapTraces';
import type { AxisRanges } from '@workbench/image-map/imageMapViewport';
+import type { HoverCluster, HoverPreview } from '@workbench/widgets/image-map/MapHoverCard';
import type { PlotlyHTMLElement } from 'plotly.js';
-import { Box, chakra, HStack, Stack, Text } from '@chakra-ui/react';
+import { Box } from '@chakra-ui/react';
import {
getImageCluster,
getPersistedSelectedGalleryItemKeys,
- getSelectedGalleryImageFromValues,
- parseGalleryItemKey,
+ getSelectedGalleryItemFromValues,
parseGallerySemanticReference,
+ toGalleryItemKey,
} from '@features/gallery/contracts';
import { attachWheelZoom } from '@workbench/image-map/attachWheelZoom';
-import { getClusterColor } from '@workbench/image-map/clusterPalette';
import { collectClusterSelection } from '@workbench/image-map/clusterSelection';
-import { getImageLabels } from '@workbench/image-map/imageLabelCache';
import { imageMapStore } from '@workbench/image-map/imageMapStore';
import {
buildAllPointsTrace,
@@ -33,9 +33,10 @@ import {
rangesToKeepMarkerInView,
} from '@workbench/image-map/imageMapViewport';
import { getThumbnailUrl } from '@workbench/image-map/thumbnailCache';
+import { MapHoverCard } from '@workbench/widgets/image-map/MapHoverCard';
import { shallowEqual, useWidgetValuesSelector } from '@workbench/WorkbenchContext';
import Plotly from 'plotly.js-gl2d-dist-min';
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useMapSelection } from './useSelectMapImage';
@@ -54,161 +55,6 @@ const swallow = (promise: Promise<unknown>): void => {
promise.catch(() => {});
};
-/** Bounds the hover card's thumbnail. */
-const HOVER_PREVIEW_MAX_PX = 160;
-const HOVER_PREVIEW_OFFSET_PX = 14;
-/** Keep the hover card at least this clear of the viewport edges. */
-const HOVER_PREVIEW_EDGE_PAD_PX = 10;
-
-interface HoverPreview {
- imageName: string;
- url: string;
- clientX: number;
- clientY: number;
-}
-
-/**
- * Cluster identity for the hovered image, resolved from the CURRENT points.
- * Deliberately not captured at hover time: a hover survives a live refresh
- * (see `hoverPreview` below), and a refresh re-runs DBSCAN, which can renumber
- * every cluster. A frozen id would then be paired with the new clustering's
- * labels and color — a card describing a cluster the image is not in.
- */
-interface HoverCluster {
- /** DBSCAN cluster of the hovered point; -1 means unclustered noise. */
- cluster: number;
- /** Points currently on the map in that cluster. */
- clusterSize: number;
-}
-
-/** "Label: a, b, c" with the first (primary) tag emphasized. */
-const HoverTagsRow = ({ prefix, tags }: { prefix: string; tags: string[] }) => (
- <Text color="fg.muted" fontSize="xs">
- <chakra.span color="fg.subtle">{prefix}</chakra.span>
- {tags.map((tag, index) => (
- <chakra.span key={tag} fontWeight={index === 0 ? '600' : undefined}>
- {index > 0 ? ', ' : ''}
- {tag}
- </chakra.span>
- ))}
- </Text>
-);
-
-/**
- * The hover card: thumbnail, filename, cluster identity/size, and the top
- * cluster and image tags — PhotoMapAI's popup on the app's dropdown chrome,
- * with the cluster's palette color confined to a swatch dot. Its size depends
- * on async content (the thumbnail and the lazily fetched image tags), so it
- * renders invisibly, is measured, and is then placed beside the cursor —
- * flipped to the other side when it would leave the viewport. Parents key
- * this by image name so a new hover starts clean.
- */
-const MapHoverCard = ({
- preview,
- hoverCluster,
- clusterLabel,
-}: {
- preview: HoverPreview;
- hoverCluster: HoverCluster;
- clusterLabel: ImageMapClusterLabelInfo | null;
-}) => {
- const cardRef = useRef<HTMLDivElement | null>(null);
- const [imageLabels, setImageLabels] = useState<ImageMapImageLabels | null>(null);
- const [imageLoaded, setImageLoaded] = useState(false);
- const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
-
- // Image tags are computed on demand (network round-trip on first hover of
- // an image; session-cached after). The card renders without the row until
- // they arrive.
- useEffect(() => {
- let cancelled = false;
-
- void getImageLabels(preview.imageName).then((labels) => {
- if (!cancelled) {
- setImageLabels(labels);
- }
- });
-
- return () => {
- cancelled = true;
- };
- }, [preview.imageName]);
-
- // Re-measure whenever content that changes the card's size lands.
- useLayoutEffect(() => {
- const card = cardRef.current;
-
- if (!card) {
- return;
- }
-
- const rect = card.getBoundingClientRect();
- let left = preview.clientX + HOVER_PREVIEW_OFFSET_PX;
- let top = preview.clientY + HOVER_PREVIEW_OFFSET_PX;
-
- if (left + rect.width > window.innerWidth - HOVER_PREVIEW_EDGE_PAD_PX) {
- left = Math.max(0, preview.clientX - rect.width - HOVER_PREVIEW_OFFSET_PX);
- }
-
- if (top + rect.height > window.innerHeight - HOVER_PREVIEW_EDGE_PAD_PX) {
- top = Math.max(0, preview.clientY - rect.height - HOVER_PREVIEW_OFFSET_PX);
- }
-
- setPosition({ left, top });
- }, [preview.clientX, preview.clientY, imageLabels, imageLoaded, clusterLabel, hoverCluster]);
-
- const handleImageSettled = useCallback(() => setImageLoaded(true), []);
- const clusterColor = getClusterColor(hoverCluster.cluster);
- const clusterTags = clusterLabel ? [clusterLabel.label, ...clusterLabel.alternates].slice(0, 3) : null;
- const imageTags = imageLabels ? [imageLabels.label, ...imageLabels.alternates].slice(0, 3) : null;
-
- return (
- <Stack
- bg="bg.muted"
- borderColor="border.emphasized"
- borderWidth="1px"
- color="fg"
- gap="1"
- left={`${position?.left ?? 0}px`}
- maxW="60"
- p="2"
- pointerEvents="none"
- position="fixed"
- ref={cardRef}
- rounded="md"
- shadow="lg"
- top={`${position?.top ?? 0}px`}
- visibility={position ? 'visible' : 'hidden'}
- zIndex="tooltip"
- >
- <chakra.img
- alt={preview.imageName}
- display="block"
- maxH={`${HOVER_PREVIEW_MAX_PX}px`}
- maxW={`${HOVER_PREVIEW_MAX_PX}px`}
- mx="auto"
- onError={handleImageSettled}
- onLoad={handleImageSettled}
- rounded="l2"
- src={preview.url}
- />
- <HStack gap="1.5">
- <Box bg={clusterColor} boxSize="2" flexShrink={0} rounded="full" />
- <Text fontSize="xs" fontWeight="600">
- {hoverCluster.cluster < 0
- ? 'Unclustered'
- : `Cluster ${hoverCluster.cluster} · ${hoverCluster.clusterSize} images`}
- </Text>
- </HStack>
- <Text color="fg.muted" fontSize="xs" wordBreak="break-all">
- {preview.imageName}
- </Text>
- {clusterTags ? <HoverTagsRow prefix="Cluster tags: " tags={clusterTags} /> : null}
- {imageTags ? <HoverTagsRow prefix="Image tags: " tags={imageTags} /> : null}
- </Stack>
- );
-};
-
interface PlotElement extends PlotlyHTMLElement {
_fullLayout?: {
xaxis?: { range?: [number, number] };
@@ -234,7 +80,7 @@ const readRanges = (plot: PlotElement): AxisRanges | null => {
*/
const computeInitialFit = (
points: ImageMapPoint[],
- selectedImageName: string | null,
+ selectedKey: GalleryItemKey | null,
width: number,
height: number
): AxisRanges | null => {
@@ -248,9 +94,7 @@ const computeInitialFit = (
return null;
}
- const selected = selectedImageName
- ? points.find((candidate) => candidate.imageName === selectedImageName)
- : undefined;
+ const selected = selectedKey ? points.find((candidate) => candidate.key === selectedKey) : undefined;
if (selected) {
box = expandRangesToInclude(box, selected);
@@ -286,37 +130,37 @@ const ImageMapPlot = ({
const clusterLabelsMatchPoints = imageMapStore.useSelector(
(snapshot) => snapshot.clusterLabelsHash !== null && snapshot.clusterLabelsHash === snapshot.data?.visibleHash
);
- const selectedImageName = useWidgetValuesSelector(
- 'gallery',
- (values) => getSelectedGalleryImageFromValues(values)?.imageName ?? null
- );
- // The persisted selection stores kind-tagged item keys; map points carry
- // bare image names, so parse the keys back down (videos never plot).
- const selectedImageNames = useWidgetValuesSelector(
+ // The primary selection as an item key: a selected video is marked on the
+ // map like any other item, and the key is a string so the refs and the
+ // recenter comparisons below stay plain equality checks.
+ const selectedKey = useWidgetValuesSelector('gallery', (values) => {
+ const item = getSelectedGalleryItemFromValues(values);
+
+ return item ? toGalleryItemKey({ kind: item.kind, name: item.name }) : null;
+ });
+ // Both the persisted selection and the map's points are kind-tagged, so the
+ // highlight compares item keys and a selected video marks its own point.
+ const selectedItemKeys = useWidgetValuesSelector(
'gallery',
- (values) =>
- getPersistedSelectedGalleryItemKeys(values)
- .map(parseGalleryItemKey)
- .filter((ref) => ref.kind === 'image')
- .map((ref) => ref.name),
+ (values) => getPersistedSelectedGalleryItemKeys(values),
shallowEqual
);
// With a cluster filter active in the gallery, the whole cluster stays
// highlighted on the map — the gallery is showing exactly these images.
- const clusterQueryImageNames = useWidgetValuesSelector(
+ const clusterQueryItemKeys = useWidgetValuesSelector(
'gallery',
(values) => {
const reference = parseGallerySemanticReference(values.semanticImageQuery);
- return reference?.kind === 'cluster' ? (getImageCluster(reference.clusterId)?.imageNames ?? null) : null;
+ return reference?.kind === 'cluster' ? (getImageCluster(reference.clusterId)?.itemKeys ?? null) : null;
},
shallowEqual
);
- const selectedNames = useMemo(
- () => new Set([...selectedImageNames, ...(clusterQueryImageNames ?? [])]),
- [clusterQueryImageNames, selectedImageNames]
+ const selectedKeys = useMemo(
+ () => new Set([...selectedItemKeys, ...(clusterQueryItemKeys ?? [])]),
+ [clusterQueryItemKeys, selectedItemKeys]
);
- const { selectCluster, selectImage } = useMapSelection();
+ const { selectCluster, selectItem: selectMapItem } = useMapSelection();
// Bumped after every scene rebuild so the overlay effects (marker,
// highlight) re-apply onto the fresh, empty overlay traces.
const [plotRevision, setPlotRevision] = useState(0);
@@ -325,7 +169,7 @@ const ImageMapPlot = ({
// The selection the marker effect last decluttered for. Seeded with the
// mounting selection so the initial scene, whose labels the effect below
// applies from scratch, does not also get a redundant pass here.
- const lastDeclutteredSelectionRef = useRef(selectedImageName);
+ const lastDeclutteredSelectionRef = useRef(selectedKey);
// The points array `fullAnnotationsRef` was built from, so the marker effect
// can tell whether those annotations describe the embedding now on screen.
const annotationsPointsRef = useRef<ImageMapPoint[] | null>(null);
@@ -334,17 +178,17 @@ const ImageMapPlot = ({
// scene effect and the resize observer coordinate without re-running.
const initialFitDoneRef = useRef(false);
const pointsRef = useRef(points);
- const selectedImageNameRef = useRef(selectedImageName);
+ const selectedKeyRef = useRef(selectedKey);
const clusterModeRef = useRef(clickSelectsCluster);
const clusterLabelsRef = useRef(clusterLabels);
// Declared before the effects below so the refs are fresh when they run.
useEffect(() => {
pointsRef.current = points;
- selectedImageNameRef.current = selectedImageName;
+ selectedKeyRef.current = selectedKey;
clusterModeRef.current = clickSelectsCluster;
clusterLabelsRef.current = clusterLabels;
- }, [clickSelectsCluster, clusterLabels, points, selectedImageName]);
+ }, [clickSelectsCluster, clusterLabels, points, selectedKey]);
// The full annotation set for the current data; which of them actually show
// is view-dependent (see applyDeclutteredAnnotations), so the source list
// lives in a ref the relayout listener can re-filter without re-rendering.
@@ -364,9 +208,9 @@ const ImageMapPlot = ({
// is what keeps the current position findable in a dense field.
const applyDeclutteredAnnotations = useCallback((container: PlotElement) => {
const ranges = readRanges(container);
- const selectedName = selectedImageNameRef.current;
+ const selectedItemKey = selectedKeyRef.current;
const markerPoint =
- (selectedName ? pointsRef.current?.find((candidate) => candidate.imageName === selectedName) : null) ?? null;
+ (selectedItemKey ? pointsRef.current?.find((candidate) => candidate.key === selectedItemKey) : null) ?? null;
const annotations =
ranges && container.offsetWidth > 0 && container.offsetHeight > 0
? declutterAnnotations(
@@ -425,12 +269,7 @@ const ImageMapPlot = ({
let initialRanges = readRanges(container as unknown as PlotElement) ?? computePercentileRanges(points);
if (!initialFitDoneRef.current) {
- const fitted = computeInitialFit(
- points,
- selectedImageNameRef.current,
- container.offsetWidth,
- container.offsetHeight
- );
+ const fitted = computeInitialFit(points, selectedKeyRef.current, container.offsetWidth, container.offsetHeight);
if (fitted) {
initialRanges = fitted;
@@ -463,9 +302,13 @@ const ImageMapPlot = ({
return;
}
- const imageName = event.points?.[0]?.customdata;
+ const customdata = event.points?.[0]?.customdata;
+ // Resolved against the points this scene was built from rather than
+ // parsed: customdata is this component's own key, so one that names
+ // no point is a stale event, not an item to go and fetch.
+ const clicked = typeof customdata === 'string' ? points.find((point) => point.key === customdata) : undefined;
- if (typeof imageName !== 'string') {
+ if (!clicked) {
return;
}
@@ -473,33 +316,31 @@ const ImageMapPlot = ({
// under the user's cursor; the marker effect checks this. The
// stamp expires so a stale entry (failed hydrate, re-click of the
// current point) cannot suppress a legitimate future recenter.
- lastMapSelectionRef.current = { at: Date.now(), name: imageName };
+ lastMapSelectionRef.current = { at: Date.now(), name: clicked.key };
- const clusterNames = clusterModeRef.current ? collectClusterSelection(points, imageName) : null;
+ const clusterKeys = clusterModeRef.current ? collectClusterSelection(points, clicked.key) : null;
- if (clusterNames) {
- const clicked = points.find((point) => point.imageName === imageName);
+ if (clusterKeys) {
// The backend's cluster label names the filter chip when one has
// arrived; the member count is the fallback (labels can be off,
// still loading, or missing for this cluster). Only the primary
// phrase is used — the alternates belong to the hover card, which
// has room to show them.
- const label =
- (clicked ? clusterLabelsRef.current?.[String(clicked.cluster)]?.label : undefined) ??
- `${clusterNames.length} images`;
+ const label = clusterLabelsRef.current?.[String(clicked.cluster)]?.label ?? `${clusterKeys.length} items`;
- selectCluster(imageName, clusterNames, label);
+ selectCluster(clicked.item, clusterKeys, label);
} else {
// Also the cluster-mode fallback for noise points (cluster -1).
- selectImage(imageName);
+ selectMapItem(clicked.item);
}
});
plot.removeAllListeners?.('plotly_hover');
plot.on('plotly_hover', (event) => {
- const imageName = event.points?.[0]?.customdata;
+ const customdata = event.points?.[0]?.customdata;
const mouse = (event as { event?: MouseEvent }).event;
+ const hovered = typeof customdata === 'string' ? points.find((point) => point.key === customdata) : undefined;
- if (typeof imageName !== 'string' || !mouse) {
+ if (!hovered || !mouse) {
return;
}
@@ -507,14 +348,14 @@ const ImageMapPlot = ({
const session = hoverSessionRef.current;
const { clientX, clientY } = mouse;
hoverTimerRef.current = setTimeout(() => {
- void getThumbnailUrl(imageName).then((url) => {
+ void getThumbnailUrl(hovered.item).then((thumbnail) => {
// Deliberately not gated on `disposed`: that belongs to this
// effect, which re-runs on every socket-driven refresh, so a
// refresh landing mid-dwell would drop the thumbnail — and no
// new `plotly_hover` fires while the pointer sits still.
// Unmount is covered by the session bump in the cleanup below.
- if (url && hoverSessionRef.current === session) {
- setHoverPreview({ clientX, clientY, imageName, url });
+ if (thumbnail && hoverSessionRef.current === session) {
+ setHoverPreview({ clientX, clientY, key: hovered.key, thumbnail });
}
});
}, HOVER_DELAY_MS);
@@ -557,7 +398,7 @@ const ImageMapPlot = ({
return () => {
disposed = true;
};
- }, [applyDeclutteredAnnotations, points, selectCluster, selectImage]);
+ }, [applyDeclutteredAnnotations, points, selectCluster, selectMapItem]);
// Highlight overlay: the gallery's multi-selection, restyled in place.
useEffect(() => {
@@ -573,7 +414,7 @@ const ImageMapPlot = ({
return;
}
- const trace = buildHighlightedPointsTrace(points, selectedNames);
+ const trace = buildHighlightedPointsTrace(points, selectedKeys);
swallow(
Plotly.restyle(
container,
@@ -586,7 +427,7 @@ const ImageMapPlot = ({
[highlightIndex]
)
);
- }, [plotRevision, points, selectedNames]);
+ }, [plotRevision, points, selectedKeys]);
// The timer must not outlive the component; the scene effect used to do
// this, but it reruns on every `points` change.
@@ -620,13 +461,13 @@ const ImageMapPlot = ({
// into one commit (a finished generation does exactly that): the selection
// did change, but these annotations are not for these points yet.
const selectionChanged =
- lastDeclutteredSelectionRef.current !== selectedImageName && annotationsPointsRef.current === points;
- lastDeclutteredSelectionRef.current = selectedImageName;
+ lastDeclutteredSelectionRef.current !== selectedKey && annotationsPointsRef.current === points;
+ lastDeclutteredSelectionRef.current = selectedKey;
- const point = selectedImageName ? points.find((candidate) => candidate.imageName === selectedImageName) : undefined;
+ const point = selectedKey ? points.find((candidate) => candidate.key === selectedKey) : undefined;
const suppression = lastMapSelectionRef.current;
const isSuppressionFresh = suppression !== null && Date.now() - suppression.at < MAP_CLICK_SUPPRESS_MS;
- const cameFromMapClick = isSuppressionFresh && suppression.name === selectedImageName;
+ const cameFromMapClick = isSuppressionFresh && suppression.name === selectedKey;
// Consume a matching entry; an interleaved external selection keeps a
// pending map click's suppression intact for when it lands. Expired
@@ -670,7 +511,7 @@ const ImageMapPlot = ({
if (recentered) {
swallow(Plotly.relayout(container, { 'xaxis.range': recentered.x, 'yaxis.range': recentered.y }));
}
- }, [applyDeclutteredAnnotations, plotRevision, points, selectedImageName]);
+ }, [applyDeclutteredAnnotations, plotRevision, points, selectedKey]);
// Labels arrive about a second after the points they annotate. Applying them
// with `relayout` rather than through the scene effect keeps that from
@@ -738,7 +579,7 @@ const ImageMapPlot = ({
const fitted = computeInitialFit(
pointsRef.current ?? [],
- selectedImageNameRef.current,
+ selectedKeyRef.current,
container.offsetWidth,
container.offsetHeight
);
@@ -778,20 +619,18 @@ const ImageMapPlot = ({
// must go with it rather than keep the previous account's thumbnail on
// screen — with a cluster identity that resolves to the noise sentinel.
const hoverPreview =
- pendingHoverPreview && points?.some((point) => point.imageName === pendingHoverPreview.imageName)
- ? pendingHoverPreview
- : null;
+ pendingHoverPreview && points?.some((point) => point.key === pendingHoverPreview.key) ? pendingHoverPreview : null;
// Resolved from the live points, so the id, the size and the tint describe
// the clustering currently drawn even after a refresh has renumbered it
// under a stationary pointer. `hoverPreview` non-null already implies the
- // image is in `points`, so there is no missing-point fallback to take.
+ // item is in `points`, so there is no missing-point fallback to take.
const hoverCluster = useMemo((): HoverCluster => {
if (!hoverPreview || !points) {
return { cluster: -1, clusterSize: 0 };
}
- const cluster = points.find((point) => point.imageName === hoverPreview.imageName)?.cluster ?? -1;
+ const cluster = points.find((point) => point.key === hoverPreview.key)?.cluster ?? -1;
return {
cluster,
@@ -806,7 +645,7 @@ const ImageMapPlot = ({
<MapHoverCard
clusterLabel={(clusterLabelsMatchPoints ? clusterLabels?.[String(hoverCluster.cluster)] : null) ?? null}
hoverCluster={hoverCluster}
- key={hoverPreview.imageName}
+ key={hoverPreview.key}
preview={hoverPreview}
/>
) : null}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
index ebbc0c76a0..08972677e0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetFooter.tsx
@@ -50,7 +50,7 @@ export const ImageMapWidgetFooter = (_props: WidgetViewProps) => {
</>
) : null}
{skipped ? (
- <Tooltip content="These images repeatedly failed to embed and were given up on.">
+ <Tooltip content="These items repeatedly failed to embed and were given up on.">
<Text truncate>· {indexCounts.failed} skipped</Text>
</Tooltip>
) : null}
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 14a5e9feec..f3f7253153 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
@@ -313,8 +313,8 @@ describe('Image Map indexing activity', () => {
modelName: null,
pointCount: 2,
points: [
- { cluster: 0, imageName: 'a.png', x: 0, y: 0 },
- { cluster: 0, imageName: 'b.png', x: 1, y: 1 },
+ { cluster: 0, item: { kind: 'image', name: 'a.png' }, key: 'image:a.png', x: 0, y: 0 },
+ { cluster: 0, item: { kind: 'image', name: 'b.png' }, key: 'image:b.png', x: 1, y: 1 },
],
stale: false,
state: 'ready',
@@ -358,7 +358,7 @@ describe('Image Map indexing activity', () => {
expect(host?.querySelector('[data-testid="plot"]')).not.toBeNull();
expect(host?.textContent).toContain('indexing 1,204/18,050');
// The map stays: the badge must not replace it.
- expect(host?.textContent).not.toContain('Indexing images');
+ expect(host?.textContent).not.toContain('Indexing gallery');
});
it('names the labels in the badge, since they vanish while the vocabulary rebuilds', async () => {
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 4023e5814e..3f85e35d11 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
@@ -228,7 +228,7 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {
return (
<CenteredMessage
- detail="Generate or import images and they will appear here, clustered by visual similarity."
+ detail="Generate or import images and videos and they will appear here, clustered by visual similarity."
title="Nothing to map yet"
/>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx
new file mode 100644
index 0000000000..c64b5a7327
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.browser.test.tsx
@@ -0,0 +1,96 @@
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ getImageLabels: vi.fn() }));
+
+vi.mock('@workbench/image-map/imageLabelCache', () => ({ getImageLabels: mocks.getImageLabels }));
+
+import { MapHoverCard } from './MapHoverCard';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+const HOVER_CLUSTER = { cluster: 0, clusterSize: 4 } as const;
+
+const render = async (preview: Parameters<typeof MapHoverCard>[0]['preview']) => {
+ await act(async () => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <MapHoverCard clusterLabel={null} hoverCluster={HOVER_CLUSTER} preview={preview} />
+ </ChakraProvider>
+ );
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ });
+
+ return host?.textContent ?? '';
+};
+
+beforeEach(() => {
+ mocks.getImageLabels.mockReset();
+ mocks.getImageLabels.mockResolvedValue(null);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(async () => {
+ root?.unmount();
+ await Promise.resolve();
+ });
+ host?.remove();
+ root = null;
+ host = null;
+});
+
+describe('MapHoverCard', () => {
+ it('marks a video with the gallery’s play badge and its duration', async () => {
+ // A video's thumbnail is a still frame, so without this the card is
+ // indistinguishable from an image's — and the badge matches the gallery
+ // tile the click will land on.
+ const text = await render({
+ clientX: 10,
+ clientY: 10,
+ key: 'video:clip.mp4',
+ thumbnail: { durationSeconds: 75, url: '/thumb.webp' },
+ });
+
+ expect(text).toContain('1:15');
+ expect(text).toContain('clip.mp4');
+ expect(host?.querySelector('img')?.getAttribute('alt')).toBe('Video: clip.mp4');
+ });
+
+ it('leaves an image unmarked and names it plainly', async () => {
+ const text = await render({
+ clientX: 10,
+ clientY: 10,
+ key: 'image:a.png',
+ thumbnail: { durationSeconds: null, url: '/thumb.webp' },
+ });
+
+ expect(text).toContain('a.png');
+ expect(text).not.toContain(':');
+ expect(host?.querySelector('img')?.getAttribute('alt')).toBe('a.png');
+ });
+
+ it('asks for the hovered item’s tags in its own namespace', async () => {
+ mocks.getImageLabels.mockResolvedValue({ alternates: ['surf'], label: 'clip' });
+
+ const text = await render({
+ clientX: 10,
+ clientY: 10,
+ key: 'video:clip.mp4',
+ thumbnail: { durationSeconds: 2, url: '/thumb.webp' },
+ });
+
+ expect(mocks.getImageLabels).toHaveBeenCalledWith({ kind: 'video', name: 'clip.mp4' });
+ expect(text).toContain('clip');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx
new file mode 100644
index 0000000000..6741eb6a60
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/MapHoverCard.tsx
@@ -0,0 +1,184 @@
+import type { GalleryItemKey } from '@features/gallery/contracts';
+import type { ImageMapClusterLabelInfo, ImageMapImageLabels } from '@workbench/image-map/api';
+import type { HoverThumbnail } from '@workbench/image-map/thumbnailCache';
+
+import { Badge, Box, chakra, HStack, Stack, Text } from '@chakra-ui/react';
+import { formatGalleryVideoDuration, parseGalleryItemKey } from '@features/gallery/contracts';
+import { getClusterColor } from '@workbench/image-map/clusterPalette';
+import { getImageLabels } from '@workbench/image-map/imageLabelCache';
+import { PlayIcon } from 'lucide-react';
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+
+/** Bounds the hover card's thumbnail. */
+const HOVER_PREVIEW_MAX_PX = 160;
+const HOVER_PREVIEW_OFFSET_PX = 14;
+/** Keep the hover card at least this clear of the viewport edges. */
+const HOVER_PREVIEW_EDGE_PAD_PX = 10;
+
+export interface HoverPreview {
+ /** The hovered point's gallery key; the card parses it for the name and kind. */
+ key: GalleryItemKey;
+ thumbnail: HoverThumbnail;
+ clientX: number;
+ clientY: number;
+}
+
+/**
+ * Cluster identity for the hovered image, resolved from the CURRENT points.
+ * Deliberately not captured at hover time: a hover survives a live refresh
+ * (see `hoverPreview` below), and a refresh re-runs DBSCAN, which can renumber
+ * every cluster. A frozen id would then be paired with the new clustering's
+ * labels and color — a card describing a cluster the image is not in.
+ */
+export interface HoverCluster {
+ /** DBSCAN cluster of the hovered point; -1 means unclustered noise. */
+ cluster: number;
+ /** Points currently on the map in that cluster. */
+ clusterSize: number;
+}
+
+/** "Label: a, b, c" with the first (primary) tag emphasized. */
+const HoverTagsRow = ({ prefix, tags }: { prefix: string; tags: string[] }) => (
+ <Text color="fg.muted" fontSize="xs">
+ <chakra.span color="fg.subtle">{prefix}</chakra.span>
+ {tags.map((tag, index) => (
+ <chakra.span key={tag} fontWeight={index === 0 ? '600' : undefined}>
+ {index > 0 ? ', ' : ''}
+ {tag}
+ </chakra.span>
+ ))}
+ </Text>
+);
+
+/**
+ * The hover card: thumbnail, filename, cluster identity/size, and the top
+ * cluster and item tags — PhotoMapAI's popup on the app's dropdown chrome,
+ * with the cluster's palette color confined to a swatch dot. Its size depends
+ * on async content (the thumbnail and the lazily fetched item tags), so it
+ * renders invisibly, is measured, and is then placed beside the cursor —
+ * flipped to the other side when it would leave the viewport. Parents key
+ * this by item key so a new hover starts clean.
+ *
+ * A video's thumbnail is a still frame, so the card says which it is: without
+ * the badge a clip is indistinguishable from an image until it is opened.
+ */
+export const MapHoverCard = ({
+ preview,
+ hoverCluster,
+ clusterLabel,
+}: {
+ preview: HoverPreview;
+ hoverCluster: HoverCluster;
+ clusterLabel: ImageMapClusterLabelInfo | null;
+}) => {
+ const cardRef = useRef<HTMLDivElement | null>(null);
+ const [imageLabels, setImageLabels] = useState<ImageMapImageLabels | null>(null);
+ const [imageLoaded, setImageLoaded] = useState(false);
+ const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
+
+ // Item tags are computed on demand (network round-trip on first hover of
+ // an item; session-cached after). The card renders without the row until
+ // they arrive. Keyed by the item's key rather than by an item object, which
+ // a refresh re-creates identical and would refetch.
+ const item = parseGalleryItemKey(preview.key);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ void getImageLabels(parseGalleryItemKey(preview.key)).then((labels) => {
+ if (!cancelled) {
+ setImageLabels(labels);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [preview.key]);
+
+ // Re-measure whenever content that changes the card's size lands.
+ useLayoutEffect(() => {
+ const card = cardRef.current;
+
+ if (!card) {
+ return;
+ }
+
+ const rect = card.getBoundingClientRect();
+ let left = preview.clientX + HOVER_PREVIEW_OFFSET_PX;
+ let top = preview.clientY + HOVER_PREVIEW_OFFSET_PX;
+
+ if (left + rect.width > window.innerWidth - HOVER_PREVIEW_EDGE_PAD_PX) {
+ left = Math.max(0, preview.clientX - rect.width - HOVER_PREVIEW_OFFSET_PX);
+ }
+
+ if (top + rect.height > window.innerHeight - HOVER_PREVIEW_EDGE_PAD_PX) {
+ top = Math.max(0, preview.clientY - rect.height - HOVER_PREVIEW_OFFSET_PX);
+ }
+
+ setPosition({ left, top });
+ }, [preview.clientX, preview.clientY, imageLabels, imageLoaded, clusterLabel, hoverCluster]);
+
+ const handleImageSettled = useCallback(() => setImageLoaded(true), []);
+ const videoDuration =
+ preview.thumbnail.durationSeconds === null ? null : formatGalleryVideoDuration(preview.thumbnail.durationSeconds);
+ const clusterColor = getClusterColor(hoverCluster.cluster);
+ const clusterTags = clusterLabel ? [clusterLabel.label, ...clusterLabel.alternates].slice(0, 3) : null;
+ const imageTags = imageLabels ? [imageLabels.label, ...imageLabels.alternates].slice(0, 3) : null;
+
+ return (
+ <Stack
+ bg="bg.muted"
+ borderColor="border.emphasized"
+ borderWidth="1px"
+ color="fg"
+ gap="1"
+ left={`${position?.left ?? 0}px`}
+ maxW="60"
+ p="2"
+ pointerEvents="none"
+ position="fixed"
+ ref={cardRef}
+ rounded="md"
+ shadow="lg"
+ top={`${position?.top ?? 0}px`}
+ visibility={position ? 'visible' : 'hidden'}
+ zIndex="tooltip"
+ >
+ <chakra.img
+ alt={item.kind === 'video' ? `Video: ${item.name}` : item.name}
+ display="block"
+ maxH={`${HOVER_PREVIEW_MAX_PX}px`}
+ maxW={`${HOVER_PREVIEW_MAX_PX}px`}
+ mx="auto"
+ onError={handleImageSettled}
+ onLoad={handleImageSettled}
+ rounded="l2"
+ src={preview.thumbnail.url}
+ />
+ <HStack gap="1.5">
+ <Box bg={clusterColor} boxSize="2" flexShrink={0} rounded="full" />
+ <Text fontSize="xs" fontWeight="600">
+ {hoverCluster.cluster < 0
+ ? 'Unclustered'
+ : `Cluster ${hoverCluster.cluster} · ${hoverCluster.clusterSize} items`}
+ </Text>
+ </HStack>
+ <HStack alignItems="flex-start" gap="1.5">
+ {videoDuration !== null ? (
+ // The gallery's own video mark, so a clip reads the same on the map
+ // as it does in the grid this click will land on.
+ <Badge display="flex" flexShrink={0} fontVariantNumeric="tabular-nums" gap="1" size="xs" variant="solid">
+ <PlayIcon aria-hidden="true" fill="currentColor" />
+ {videoDuration}
+ </Badge>
+ ) : null}
+ <Text color="fg.muted" fontSize="xs" wordBreak="break-all">
+ {item.name}
+ </Text>
+ </HStack>
+ {clusterTags ? <HoverTagsRow prefix="Cluster tags: " tags={clusterTags} /> : null}
+ {imageTags ? <HoverTagsRow prefix="Tags: " tags={imageTags} /> : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
index 502b740940..c6d998f49c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx
@@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({
patchValues: vi.fn(),
registerImageCluster: vi.fn(),
requestReveal: vi.fn(),
- resolveMany: vi.fn(),
+ resolve: vi.fn(),
selectBoard: vi.fn(),
selectItem: vi.fn(),
setPage: vi.fn(),
@@ -21,8 +21,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('@features/gallery', () => ({
- galleryImages: { resolveMany: mocks.resolveMany },
- legacyGeneratedImageToGalleryItem: (image: { image_name: string }) => image,
+ galleryItems: { resolve: mocks.resolve },
toGalleryItemKey: (ref: { kind: string; name: string }) => `${ref.kind}:${ref.name}`,
}));
@@ -81,17 +80,23 @@ let root: Root | null = null;
/** Published from an effect, not during render, so the probe stays render-pure. */
const handle: {
- click: ((imageName: string) => void) | null;
- clickCluster: ((primaryImageName: string, imageNames: string[], label: string) => void) | null;
+ click: ((item: { kind: 'image' | 'video'; name: string }) => void) | null;
+ clickCluster:
+ | ((
+ primaryItem: { kind: 'image' | 'video'; name: string },
+ itemKeys: `image:${string}`[] | `video:${string}`[] | (`image:${string}` | `video:${string}`)[],
+ label: string
+ ) => void)
+ | null;
} = { click: null, clickCluster: null };
const Probe = () => {
- const { selectCluster, selectImage } = useMapSelection();
+ const { selectCluster, selectItem } = useMapSelection();
useEffect(() => {
- handle.click = selectImage;
+ handle.click = selectItem;
handle.clickCluster = selectCluster;
- }, [selectCluster, selectImage]);
+ }, [selectCluster, selectItem]);
return null;
};
@@ -167,7 +172,7 @@ afterEach(async () => {
mocks.patchValues.mockReset();
mocks.registerImageCluster.mockReset();
mocks.requestReveal.mockReset();
- mocks.resolveMany.mockReset();
+ mocks.resolve.mockReset();
mocks.selectBoard.mockReset();
mocks.selectItem.mockReset();
mocks.setPage.mockReset();
@@ -175,36 +180,89 @@ afterEach(async () => {
});
describe('useMapSelection', () => {
- describe('selectImage', () => {
+ describe('selectItem', () => {
it('dispatches the selection and a reveal for a click', async () => {
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({
boardId: 'board-a',
- image_name: 'a.png',
- imageCategory: 'general',
+ category: 'general',
+ kind: 'image',
+ name: 'a.png',
});
// The reveal channel is what scrolls the grid; the selection alone must
// not (auto-selected generation results would yank the scroll).
expect(mocks.requestReveal).toHaveBeenCalledWith('image:a.png');
});
+ it('reveals a clicked video through its own namespace', async () => {
+ // Resolved as a video, revealed under a video key: hydrating a clip
+ // through the images endpoint 404s, and an `image:` reveal key never
+ // matches the grid cell holding it.
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'video', name: 'clip.mp4' });
+ mocks.fetchNames.mockResolvedValue({
+ items: [
+ { kind: 'image', name: 'a.png' },
+ { kind: 'video', name: 'clip.mp4' },
+ ],
+ total_count: 2,
+ });
+ await mount();
+
+ await flush(() => handle.click?.({ kind: 'video', name: 'clip.mp4' }));
+
+ expect(mocks.resolve).toHaveBeenCalledWith({ kind: 'video', name: 'clip.mp4' });
+ expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({
+ boardId: 'board-a',
+ category: 'general',
+ kind: 'video',
+ name: 'clip.mp4',
+ });
+ expect(mocks.requestReveal).toHaveBeenCalledWith('video:clip.mp4');
+ });
+
+ it('finds a video at its own position in a mixed listing', async () => {
+ // The position lookup matches on kind as well as name. The two entries
+ // are two pages apart, so matching on name alone lands the gallery on
+ // the image's page and the clip is nowhere on screen.
+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'video', name: 'shared' });
+ mocks.fetchNames.mockResolvedValue({
+ items: [
+ { kind: 'image', name: 'shared' },
+ ...Array.from({ length: 119 }, (_, index) => ({ kind: 'image', name: `img-${String(index)}.png` })),
+ { kind: 'video', name: 'shared' },
+ ],
+ total_count: 121,
+ });
+ await mount();
+
+ await flush(() => handle.click?.({ kind: 'video', name: 'shared' }));
+
+ // Index 120 of a 60-per-page listing is page 2; the image's index 0 is page 0.
+ expect(mocks.setPage).toHaveBeenCalledWith(2);
+ expect(mocks.requestReveal).toHaveBeenCalledWith('video:shared');
+ });
+
it("selects the image's board before the image itself", async () => {
// The map spans every accessible board, but selectGalleryItem stamps the
// navigation query from whatever list the gallery is currently showing. A
// cross-board click without this left that query describing a list the
// image was never in, and Preview's next/prev found no cursor and went
// dead until the user re-selected from the grid.
- mocks.resolveMany.mockResolvedValue([
- { boardId: 'board-portraits', image_name: 'a.png', imageCategory: 'general' },
- ]);
+ mocks.resolve.mockResolvedValue({
+ boardId: 'board-portraits',
+ category: 'general',
+ kind: 'image',
+ name: 'a.png',
+ });
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.selectBoard).toHaveBeenCalledWith('board-portraits');
expect(mocks.selectBoard.mock.invocationCallOrder[0]).toBeLessThan(mocks.selectItem.mock.invocationCallOrder[0]);
@@ -212,11 +270,11 @@ describe('useMapSelection', () => {
it('lands the gallery on the page holding the image in paginated mode', async () => {
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'deep.png' });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
await mount();
- await flush(() => handle.click?.('deep.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'deep.png' }));
expect(mocks.setPage).toHaveBeenCalledWith(2);
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
@@ -227,11 +285,11 @@ describe('useMapSelection', () => {
it("resolves the image's position against the listing the reveal lands on", async () => {
mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated' };
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('a.png', 0));
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.fetchNames.mock.calls[0]?.[0].filter).toEqual({
boardId: 'board-a',
@@ -247,11 +305,11 @@ describe('useMapSelection', () => {
// fresh, and a fresh cache short-circuits the fetch WITHOUT honoring
// the `pages` option — the window would never grow.
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite' };
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'deep.png' });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
await mount();
- await flush(() => handle.click?.('deep.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'deep.png' }));
expect(mocks.setPage).not.toHaveBeenCalled();
expect(mocks.fetchInfiniteQuery).toHaveBeenCalledTimes(1);
@@ -262,11 +320,11 @@ describe('useMapSelection', () => {
it('skips the fetch when the window already covers the image', async () => {
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite' };
mocks.cachedPageCount = 5;
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'deep.png' });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
await mount();
- await flush(() => handle.click?.('deep.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'deep.png' }));
expect(mocks.fetchInfiniteQuery).not.toHaveBeenCalled();
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
@@ -277,11 +335,11 @@ describe('useMapSelection', () => {
// deeper image is revealed by anchoring the window at its page instead
// of loading toward it; the mounted gallery query fetches on its own.
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite' };
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'deep.png' });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 700));
await mount();
- await flush(() => handle.click?.('deep.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'deep.png' }));
expect(mocks.fetchInfiniteQuery).not.toHaveBeenCalled();
expect(mocks.setPage).toHaveBeenCalledWith(11);
@@ -296,11 +354,11 @@ describe('useMapSelection', () => {
const names = deferred<ReturnType<typeof namesWithImageAt>>();
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'deep.png' });
mocks.fetchNames.mockReturnValue(names.promise);
await mount();
- await flush(() => handle.click?.('deep.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'deep.png' }));
mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated' };
await flush(() => names.resolve(namesWithImageAt('deep.png', 130)));
@@ -315,13 +373,16 @@ describe('useMapSelection', () => {
// hidden board's page number there would jump to an unrelated page.
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };
mocks.fetchBoards.mockResolvedValue([{ id: 'board-other' }]);
- mocks.resolveMany.mockResolvedValue([
- { boardId: 'board-archived', image_name: 'deep.png', imageCategory: 'general' },
- ]);
+ mocks.resolve.mockResolvedValue({
+ boardId: 'board-archived',
+ category: 'general',
+ kind: 'image',
+ name: 'deep.png',
+ });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
await mount();
- await flush(() => handle.click?.('deep.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'deep.png' }));
expect(mocks.setPage).not.toHaveBeenCalled();
expect(mocks.selectBoard).toHaveBeenCalledWith('board-archived');
@@ -331,11 +392,11 @@ describe('useMapSelection', () => {
it('keeps the page landing when the boards lookup fails', async () => {
mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };
mocks.fetchBoards.mockRejectedValue(new Error('boards endpoint down'));
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'deep.png' });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));
await mount();
- await flush(() => handle.click?.('deep.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'deep.png' }));
expect(mocks.setPage).toHaveBeenCalledWith(2);
});
@@ -344,10 +405,10 @@ describe('useMapSelection', () => {
// The image was located in the plain board listing; an active filter
// would show some other list entirely.
mocks.galleryValues = { searchTerm: 'sunset', semanticImageQuery: { kind: 'text', query: 'sunset' } };
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {
searchTerm: '',
@@ -357,13 +418,17 @@ describe('useMapSelection', () => {
});
it('reveals a starred image in the starred listing it belongs to', async () => {
- mocks.resolveMany.mockResolvedValue([
- { boardId: 'board-a', image_name: 'a.png', imageCategory: 'general', starred: true },
- ]);
+ mocks.resolve.mockResolvedValue({
+ boardId: 'board-a',
+ category: 'general',
+ kind: 'image',
+ name: 'a.png',
+ starred: true,
+ });
mocks.fetchNames.mockResolvedValue(namesWithImageAt('a.png', 0));
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.fetchNames.mock.calls[0]?.[0].filter).toMatchObject({ boardId: 'board-a', starred: true });
expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {
@@ -374,38 +439,38 @@ describe('useMapSelection', () => {
});
it('leaves the filters alone when none are active', async () => {
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.patchValues).not.toHaveBeenCalled();
});
it('switches the gallery to the assets tab for a non-general image', async () => {
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'user' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'user', kind: 'image', name: 'a.png' });
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.setView).toHaveBeenCalledWith('assets');
});
it('does not touch the view when it already matches', async () => {
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.setView).not.toHaveBeenCalled();
});
it('still selects when the position lookup fails', async () => {
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });
mocks.fetchNames.mockRejectedValue(new Error('names endpoint down'));
await mount();
- await flush(() => handle.click?.('a.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));
expect(mocks.setPage).not.toHaveBeenCalled();
expect(mocks.selectBoard).toHaveBeenCalledWith('board-a');
@@ -415,10 +480,10 @@ describe('useMapSelection', () => {
});
it('does not touch the board for a click that never resolves an image', async () => {
- mocks.resolveMany.mockResolvedValue([]);
+ mocks.resolve.mockRejectedValue(new Error('not found'));
await mount();
- await flush(() => handle.click?.('gone.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'gone.png' }));
expect(mocks.selectBoard).not.toHaveBeenCalled();
expect(mocks.selectItem).not.toHaveBeenCalled();
@@ -427,13 +492,34 @@ describe('useMapSelection', () => {
});
describe('selectCluster', () => {
+ it('registers a cluster around a clicked video and reveals the clip', async () => {
+ // Cluster mode has its own resolve and its own reveal key; a clip clicked
+ // here must not be hydrated or revealed as an image.
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'video', name: 'clip.mp4' });
+ await mount();
+
+ await flush(() =>
+ handle.clickCluster?.({ kind: 'video', name: 'clip.mp4' }, ['video:clip.mp4', 'image:a.png'], 'beaches')
+ );
+
+ expect(mocks.resolve).toHaveBeenCalledWith({ kind: 'video', name: 'clip.mp4' });
+ expect(mocks.registerImageCluster).toHaveBeenCalledWith(['video:clip.mp4', 'image:a.png'], 'beaches');
+ expect(mocks.requestReveal).toHaveBeenCalledWith('video:clip.mp4');
+ });
+
it('shows the cluster as a gallery filter with the clicked image selected and revealed', async () => {
- mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);
+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });
await mount();
- await flush(() => handle.clickCluster?.('a.png', ['a.png', 'b.png', 'c.png'], 'beaches'));
+ await flush(() =>
+ handle.clickCluster?.(
+ { kind: 'image', name: 'a.png' },
+ ['image:a.png', 'image:b.png', 'image:c.png'],
+ 'beaches'
+ )
+ );
- expect(mocks.registerImageCluster).toHaveBeenCalledWith(['a.png', 'b.png', 'c.png'], 'beaches');
+ expect(mocks.registerImageCluster).toHaveBeenCalledWith(['image:a.png', 'image:b.png', 'image:c.png'], 'beaches');
expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {
galleryPage: 0,
searchTerm: '',
@@ -442,8 +528,9 @@ describe('useMapSelection', () => {
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({
boardId: 'board-a',
- image_name: 'a.png',
- imageCategory: 'general',
+ category: 'general',
+ kind: 'image',
+ name: 'a.png',
});
// Re-clicking the same cluster point after scrolling away must return
// the grid to the top; the reveal channel carries that even when the
@@ -455,22 +542,29 @@ describe('useMapSelection', () => {
// The selection stamps the navigation query from the list the gallery
// is currently showing, so the primary image's board must be current
// before the selection lands.
- mocks.resolveMany.mockResolvedValue([
- { boardId: 'board-landscapes', image_name: 'a.png', imageCategory: 'general' },
- ]);
+ mocks.resolve.mockResolvedValue({
+ boardId: 'board-landscapes',
+ category: 'general',
+ kind: 'image',
+ name: 'a.png',
+ });
await mount();
- await flush(() => handle.clickCluster?.('a.png', ['a.png', 'b.png'], 'label'));
+ await flush(() =>
+ handle.clickCluster?.({ kind: 'image', name: 'a.png' }, ['image:a.png', 'image:b.png'], 'label')
+ );
expect(mocks.selectBoard).toHaveBeenCalledWith('board-landscapes');
expect(mocks.selectBoard.mock.invocationCallOrder[0]).toBeLessThan(mocks.selectItem.mock.invocationCallOrder[0]);
});
it('leaves the gallery alone when the primary image cannot be resolved', async () => {
- mocks.resolveMany.mockResolvedValue([]);
+ mocks.resolve.mockRejectedValue(new Error('not found'));
await mount();
- await flush(() => handle.clickCluster?.('gone.png', ['gone.png', 'b.png'], 'label'));
+ await flush(() =>
+ handle.clickCluster?.({ kind: 'image', name: 'gone.png' }, ['image:gone.png', 'image:b.png'], 'label')
+ );
expect(mocks.registerImageCluster).not.toHaveBeenCalled();
expect(mocks.patchValues).not.toHaveBeenCalled();
@@ -483,45 +577,45 @@ describe('useMapSelection', () => {
// The two entry points must not race each other: switching cluster mode
// mid-flight would otherwise let a stale resolution overwrite a newer
// selection.
- const slow = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();
- const fast = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();
+ const slow = deferred<{ boardId: string; category: string; kind: string; name: string }>();
+ const fast = deferred<{ boardId: string; category: string; kind: string; name: string }>();
- mocks.resolveMany.mockReturnValueOnce(slow.promise).mockReturnValueOnce(fast.promise);
+ mocks.resolve.mockReturnValueOnce(slow.promise).mockReturnValueOnce(fast.promise);
await mount();
await flush(() => {
- handle.clickCluster?.('slow.png', ['slow.png'], 'label');
- handle.click?.('fast.png');
+ handle.clickCluster?.({ kind: 'image', name: 'slow.png' }, ['image:slow.png'], 'label');
+ handle.click?.({ kind: 'image', name: 'fast.png' });
});
await flush(() => {
- fast.resolve([{ boardId: 'board-a', image_name: 'fast.png', imageCategory: 'general' }]);
- slow.resolve([{ boardId: 'board-a', image_name: 'slow.png', imageCategory: 'general' }]);
+ fast.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'fast.png' });
+ slow.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'slow.png' });
});
expect(mocks.patchValues).not.toHaveBeenCalled();
expect(mocks.selectItem).toHaveBeenCalledTimes(1);
- expect(mocks.selectItem.mock.calls[0]?.[0].image_name).toBe('fast.png');
+ expect(mocks.selectItem.mock.calls[0]?.[0].name).toBe('fast.png');
});
it('ignores a slow click that resolves after a newer one', async () => {
- const slow = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();
- const fast = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();
+ const slow = deferred<{ boardId: string; category: string; kind: string; name: string }>();
+ const fast = deferred<{ boardId: string; category: string; kind: string; name: string }>();
- mocks.resolveMany.mockReturnValueOnce(slow.promise).mockReturnValueOnce(fast.promise);
+ mocks.resolve.mockReturnValueOnce(slow.promise).mockReturnValueOnce(fast.promise);
await mount();
await flush(() => {
- handle.click?.('slow.png');
- handle.click?.('fast.png');
+ handle.click?.({ kind: 'image', name: 'slow.png' });
+ handle.click?.({ kind: 'image', name: 'fast.png' });
});
await flush(() => {
- fast.resolve([{ boardId: 'board-a', image_name: 'fast.png', imageCategory: 'general' }]);
- slow.resolve([{ boardId: 'board-a', image_name: 'slow.png', imageCategory: 'general' }]);
+ fast.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'fast.png' });
+ slow.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'slow.png' });
});
// Only the most recent click may win, regardless of resolution order.
- expect(mocks.selectItem.mock.calls.map((call) => call[0].image_name)).toEqual(['fast.png']);
+ expect(mocks.selectItem.mock.calls.map((call) => call[0].name)).toEqual(['fast.png']);
});
it('ignores a click whose position lookup lands after a newer click', async () => {
@@ -530,18 +624,18 @@ describe('useMapSelection', () => {
// gallery after a newer click has already landed it elsewhere.
const slowNames = deferred<ReturnType<typeof namesWithImageAt>>();
- mocks.resolveMany
- .mockResolvedValueOnce([{ boardId: 'board-a', image_name: 'slow.png', imageCategory: 'general' }])
- .mockResolvedValueOnce([{ boardId: 'board-b', image_name: 'fast.png', imageCategory: 'general' }]);
+ mocks.resolve
+ .mockResolvedValueOnce({ boardId: 'board-a', category: 'general', kind: 'image', name: 'slow.png' })
+ .mockResolvedValueOnce({ boardId: 'board-b', category: 'general', kind: 'image', name: 'fast.png' });
mocks.fetchNames.mockReturnValueOnce(slowNames.promise).mockResolvedValueOnce(namesWithImageAt('fast.png', 0));
await mount();
- await flush(() => handle.click?.('slow.png'));
- await flush(() => handle.click?.('fast.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'slow.png' }));
+ await flush(() => handle.click?.({ kind: 'image', name: 'fast.png' }));
await flush(() => slowNames.resolve(namesWithImageAt('slow.png', 0)));
expect(mocks.selectBoard.mock.calls).toEqual([['board-b']]);
- expect(mocks.selectItem.mock.calls.map((call) => call[0].image_name)).toEqual(['fast.png']);
+ expect(mocks.selectItem.mock.calls.map((call) => call[0].name)).toEqual(['fast.png']);
});
it('ignores a click left in flight across an unmount/remount', async () => {
@@ -549,32 +643,32 @@ describe('useMapSelection', () => {
// so the abandoned click compares against a dead counter, passes, and
// overwrites the newer mount's selection. Reachable by switching the right
// panel away from the map and back while a hydrate is in flight.
- const stale = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();
- const fresh = deferred<{ boardId: string; image_name: string; imageCategory: string }[]>();
+ const stale = deferred<{ boardId: string; category: string; kind: string; name: string }>();
+ const fresh = deferred<{ boardId: string; category: string; kind: string; name: string }>();
- mocks.resolveMany.mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise);
+ mocks.resolve.mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise);
await mount();
- await flush(() => handle.click?.('stale.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'stale.png' }));
await unmount();
await mount();
- await flush(() => handle.click?.('fresh.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'fresh.png' }));
await flush(() => {
- fresh.resolve([{ boardId: 'board-a', image_name: 'fresh.png', imageCategory: 'general' }]);
- stale.resolve([{ boardId: 'board-a', image_name: 'stale.png', imageCategory: 'general' }]);
+ fresh.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'fresh.png' });
+ stale.resolve({ boardId: 'board-a', category: 'general', kind: 'image', name: 'stale.png' });
});
- expect(mocks.selectItem.mock.calls.map((call) => call[0].image_name)).toEqual(['fresh.png']);
+ expect(mocks.selectItem.mock.calls.map((call) => call[0].name)).toEqual(['fresh.png']);
});
- it('leaves the selection alone when hydrate fails or the image is gone', async () => {
- mocks.resolveMany.mockRejectedValueOnce(new Error('deleted')).mockResolvedValueOnce([]);
+ it('leaves the selection alone when hydrate fails or the item is gone', async () => {
+ mocks.resolve.mockRejectedValueOnce(new Error('deleted')).mockRejectedValueOnce(new Error('missing'));
await mount();
- await flush(() => handle.click?.('gone.png'));
- await flush(() => handle.click?.('missing.png'));
+ await flush(() => handle.click?.({ kind: 'image', name: 'gone.png' }));
+ await flush(() => handle.click?.({ kind: 'image', name: 'missing.png' }));
expect(mocks.selectItem).not.toHaveBeenCalled();
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
index 777bdfefd8..8f033f2f0c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts
@@ -1,8 +1,9 @@
import type { GalleryView } from '@features/gallery';
+import type { GalleryItemKey, GalleryItemRef } from '@features/gallery/contracts';
import type { GalleryItemsFilter } from '@features/gallery/queries';
import type { QueryClient } from '@tanstack/react-query';
-import { galleryImages, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery';
+import { galleryItems, toGalleryItemKey } from '@features/gallery';
import { getGallerySettings, registerImageCluster, requestGalleryItemReveal } from '@features/gallery/contracts';
import {
GALLERY_MAX_ROWS,
@@ -17,10 +18,10 @@ import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchC
import { useCallback, useMemo } from 'react';
export interface MapSelectionActions {
- /** Reveal one image: land the gallery on its board, page, and grid cell. */
- selectImage: (imageName: string) => void;
- /** Show the whole cluster in the gallery, the clicked image selected. */
- selectCluster: (primaryImageName: string, imageNames: string[], label: string) => void;
+ /** Reveal one item: land the gallery on its board, page, and grid cell. */
+ selectItem: (item: GalleryItemRef) => void;
+ /** Show the whole cluster in the gallery, the clicked item selected. */
+ selectCluster: (primaryItem: GalleryItemRef, itemKeys: GalleryItemKey[], label: string) => void;
}
/**
@@ -59,24 +60,25 @@ const ensureGalleryPagesLoaded = async (
};
/**
- * Turns map clicks into gallery navigation. The map only knows names; the
- * selection contract wants a full gallery item, so names are hydrated through
- * the bulk by-names resolver — always fresh, since a cached DTO's star/board
- * state can drift. ONE monotonic sequence spans both selection kinds, so
- * rapid clicks always resolve to the latest click regardless of which mode
- * each went through; a slow fetch can never overwrite a newer selection.
- * Preview follows the gallery selection on its own.
+ * Turns map clicks into gallery navigation. The map knows an item's kind and
+ * name; the selection contract wants a full gallery item, so each is hydrated
+ * through the by-ref resolver — always fresh, since a cached DTO's star/board
+ * state can drift, and kind-aware, since a point can be a video. ONE monotonic
+ * sequence spans both selection kinds, so rapid clicks always resolve to the
+ * latest click regardless of which mode each went through; a slow fetch can
+ * never overwrite a newer selection. Preview follows the gallery selection on
+ * its own.
*
- * A single-image click is a full reveal: the gallery lands on the image's
- * board and view, any search or similarity filter is cleared (the image may
- * not match it), and the image's position in the board's ordering is looked
- * up so the grid can reach it — the page is selected in paginated mode, and
- * in infinite mode the pages down to it are loaded. The grid scrolls to the
- * newly selected item on its own once it is in the loaded window.
+ * A single click is a full reveal: the gallery lands on the item's board and
+ * view, any search or similarity filter is cleared (the item may not match
+ * it), and the item's position in the board's ordering is looked up so the
+ * grid can reach it — the page is selected in paginated mode, and in infinite
+ * mode the pages down to it are loaded. The grid scrolls to the newly selected
+ * item on its own once it is in the loaded window.
*
* A cluster click instead behaves like a search: the cluster's members (in
* proximity order from the clicked point) become the gallery's list via a
- * `cluster` semantic reference, with the clicked image — the list's first
+ * `cluster` semantic reference, with the clicked item — the list's first
* entry — as the selection.
*/
export const useMapSelection = (): MapSelectionActions => {
@@ -84,22 +86,20 @@ export const useMapSelection = (): MapSelectionActions => {
const queries = useWorkbenchQueries();
const queryClient = useQueryClient();
- const selectImage = useCallback(
- (imageName: string) => {
+ const selectItem = useCallback(
+ (ref: GalleryItemRef) => {
const sequence = ++selectionSequence;
- galleryImages
- .resolveMany([imageName])
- .then(async (images) => {
- const image = images.at(0);
-
- if (!image || sequence !== selectionSequence) {
+ galleryItems
+ .resolve(ref)
+ .then(async (image) => {
+ if (sequence !== selectionSequence) {
return;
}
const getGalleryValues = () => getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery');
const settings = getGallerySettings(getGalleryValues());
- const targetView: GalleryView = image.imageCategory === 'general' ? 'images' : 'assets';
+ const targetView: GalleryView = image.category === 'general' ? 'images' : 'assets';
// The board listing the gallery will show once the reveal below has
// cleared any search: identical filter shape, so the name list (and
// the prefetched pages) land in the cache the gallery reads.
@@ -137,7 +137,7 @@ export const useMapSelection = (): MapSelectionActions => {
.catch(() => null);
const names = await queryClient.fetchQuery(galleryItemNamesOptions(listingFilter));
const boards = await boardsPromise;
- const index = names.items.findIndex((ref) => ref.kind === 'image' && ref.name === imageName);
+ const index = names.items.findIndex((item) => item.kind === ref.kind && item.name === ref.name);
const isBoardListable =
image.boardId === 'none' ||
boards === null ||
@@ -214,11 +214,11 @@ export const useMapSelection = (): MapSelectionActions => {
}
}
- commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image), undefined, page ?? undefined);
- requestGalleryItemReveal(toGalleryItemKey({ kind: 'image', name: imageName }));
+ commands.gallery.selectItem(image, undefined, page ?? undefined);
+ requestGalleryItemReveal(toGalleryItemKey(ref));
})
.catch(() => {
- // A click on a just-deleted image, or a blip mid-backend-restart,
+ // A click on a just-deleted item, or a blip mid-backend-restart,
// simply leaves the selection unchanged.
});
},
@@ -226,39 +226,37 @@ export const useMapSelection = (): MapSelectionActions => {
);
const selectCluster = useCallback(
- (primaryImageName: string, imageNames: string[], label: string) => {
+ (primaryItem: GalleryItemRef, itemKeys: GalleryItemKey[], label: string) => {
const sequence = ++selectionSequence;
- galleryImages
- .resolveMany([primaryImageName])
- .then((images) => {
- const image = images.at(0);
-
- if (!image || sequence !== selectionSequence) {
+ galleryItems
+ .resolve(primaryItem)
+ .then((image) => {
+ if (sequence !== selectionSequence) {
return;
}
- // Same reason as `selectImage` above: the selection stamps the
+ // Same reason as `selectItem` above: the selection stamps the
// navigation query from the board the gallery is showing, so land
- // on the primary image's board first to keep that query coherent.
+ // on the primary item's board first to keep that query coherent.
commands.gallery.selectBoard(image.boardId);
// The member list lives in an in-memory registry (it can run to
- // thousands of names); the persisted value keeps only the key. The
+ // thousands of items); the persisted value keeps only the key. The
// page reset and search-term clear mirror setSemanticImageQuery in
// the gallery's own actions.
- const clusterId = registerImageCluster(imageNames, label);
+ const clusterId = registerImageCluster(itemKeys, label);
commands.widgets.patchValues('gallery', {
galleryPage: 0,
searchTerm: '',
semanticImageQuery: { clusterId, kind: 'cluster', label },
});
- // The clicked image is the proximity ordering's first entry, so it
+ // The clicked item is the proximity ordering's first entry, so it
// is selected at the top of the cluster view; Preview follows. The
// reveal brings the grid back to it even when this exact selection
// is already current (re-clicking the cluster after scrolling away).
- commands.gallery.selectItem(legacyGeneratedImageToGalleryItem(image));
- requestGalleryItemReveal(toGalleryItemKey({ kind: 'image', name: primaryImageName }));
+ commands.gallery.selectItem(image);
+ requestGalleryItemReveal(toGalleryItemKey(primaryItem));
})
.catch(() => {
// Selection is simply left unchanged on hydrate failure.
@@ -267,5 +265,5 @@ export const useMapSelection = (): MapSelectionActions => {
[commands]
);
- return useMemo(() => ({ selectCluster, selectImage }), [selectCluster, selectImage]);
+ return useMemo(() => ({ selectCluster, selectItem }), [selectCluster, selectItem]);
};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 86e35f06a0..c97622181b 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -1039,7 +1039,7 @@ describe('adopting a project from another realm', () => {
// a project runs it, and so does the conflict fork that rescues the LIVE
// copy. The registry entry is still here, the ranking is still on screen,
// and deleting it would take the user's search with it.
- const clusterId = registerImageCluster(['a.png', 'b.png'], 'beaches');
+ const clusterId = registerImageCluster(['image:a.png', 'image:b.png'], 'beaches');
const values = galleryValuesOf(
galleryProject({
galleryPage: 3,
@@ -1077,7 +1077,7 @@ describe('adopting a project from another realm', () => {
});
it('retargets a project without disturbing its live session state', () => {
- const clusterId = registerImageCluster(['a.png', 'b.png'], 'beaches');
+ const clusterId = registerImageCluster(['image:a.png', 'image:b.png'], 'beaches');
let state = createInitialWorkbenchState();
const project = getActiveProject(state);
const staleCopy = project;