From 2f830029e17305d3ba60badc6ab78e23a5456770 Mon Sep 17 00:00:00 2001
From: Noah Khomer <108771853+noahkhomer18@users.noreply.github.com>
Date: Fri, 27 Nov 2026 17:14:20 -0600
Subject: [PATCH] fix(images): identify image results by the image, not its
page
Image results were deduplicated, reranked, merged into history and keyed on screen by their page URL, so several images from one gallery page collapsed into the first. Identify an image by its full-size source, then its thumbnail, then its page, through one shared helper, everywhere those steps happen. Text results still deduplicate by URL.
Three existing refreshImageSearchResults tests gave every row the same placeholder image ("thumb", "source"), which under the new identity made different pages one image; they now give each row its own image.
Fixes #3294
Signed-off-by: Noah Khomer <108771853+noahkhomer18@users.noreply.github.com>
---
.../Graphical/ImageResultsList.test.tsx | 43 +++++
.../Results/Graphical/ImageResultsList.tsx | 162 ++++++++++--------
client/modules/chatHelpers.test.ts | 129 ++++++++++++--
client/modules/chatHelpers.ts | 9 +-
client/modules/history.test.ts | 73 ++++++++
client/modules/history.ts | 16 +-
client/modules/imageResults.ts | 22 +++
.../textGeneration.degradation.test.ts | 25 +++
client/modules/textGeneration.ts | 4 +-
server/searchEndpointServerHook.test.ts | 43 +++++
server/searchEndpointServerHook.ts | 14 +-
server/webSearchService.test.ts | 105 ++++++++++++
server/webSearchService.ts | 48 ++++--
shared/imageIdentity.ts | 12 ++
14 files changed, 587 insertions(+), 118 deletions(-)
create mode 100644 client/modules/imageResults.ts
create mode 100644 shared/imageIdentity.ts
diff --git a/client/components/Search/Results/Graphical/ImageResultsList.test.tsx b/client/components/Search/Results/Graphical/ImageResultsList.test.tsx
index 0d761b833..831db0983 100644
--- a/client/components/Search/Results/Graphical/ImageResultsList.test.tsx
+++ b/client/components/Search/Results/Graphical/ImageResultsList.test.tsx
@@ -100,6 +100,49 @@ describe("ImageResultsList", () => {
);
});
+ it("keys tiles by image identity when images share a page URL", async () => {
+ const gallery = "https://example.com/gallery";
+ render(
+
+
+ ,
+ );
+
+ const [first, second] = await waitFor(() => {
+ const images = screen.getAllByRole("img");
+ expect(images).toHaveLength(2);
+ return images;
+ });
+
+ expect(getThumbnailSrc).toHaveBeenCalledWith(
+ "https://cdn.example.com/first-thumb.gif",
+ );
+ expect(getThumbnailSrc).toHaveBeenCalledWith(
+ "https://cdn.example.com/second-thumb.gif",
+ );
+ expect(first.getAttribute("src")).toBe(
+ thumbnailSrcFor("https://cdn.example.com/first-thumb.gif"),
+ );
+ expect(second.getAttribute("src")).toBe(
+ thumbnailSrcFor("https://cdn.example.com/second-thumb.gif"),
+ );
+ });
+
it("shows the host name for a result without a thumbnail", async () => {
render(
diff --git a/client/components/Search/Results/Graphical/ImageResultsList.tsx b/client/components/Search/Results/Graphical/ImageResultsList.tsx
index bbbc030dc..2162e0dc4 100644
--- a/client/components/Search/Results/Graphical/ImageResultsList.tsx
+++ b/client/components/Search/Results/Graphical/ImageResultsList.tsx
@@ -19,6 +19,7 @@ import Captions from "yet-another-react-lightbox/plugins/captions";
import classes from "./ImageResultsList.module.css";
import "yet-another-react-lightbox/styles.css";
import "yet-another-react-lightbox/plugins/captions.css";
+import { getImageIdentity } from "@shared/imageIdentity";
import { addLogEntry } from "@/modules/logEntries";
import { getHostname } from "@/modules/stringFormatters";
import { getThumbnailSrc } from "@/modules/thumbnailUrls";
@@ -90,11 +91,12 @@ export default function ImageResultsList({
void (async () => {
const entries = await Promise.all(
- imageResults.map(async ([, url, thumbnailUrl]) => {
+ imageResults.map(async ([, url, thumbnailUrl, sourceUrl]) => {
+ const identity = getImageIdentity(sourceUrl, thumbnailUrl, url);
try {
- return [url, await getThumbnailSrc(thumbnailUrl)] as const;
+ return [identity, await getThumbnailSrc(thumbnailUrl)] as const;
} catch {
- return [url, null] as const;
+ return [identity, null] as const;
}
}),
);
@@ -118,12 +120,12 @@ export default function ImageResultsList({
}));
};
- const markThumbnailFailed = (url: string) => {
- setFailedThumbnails((prev) => ({ ...prev, [url]: true }));
+ const markThumbnailFailed = (identity: string) => {
+ setFailedThumbnails((prev) => ({ ...prev, [identity]: true }));
};
- const renderTile = (title: string, url: string) => {
- const tileSrc = failedThumbnails[url] ? null : thumbnailSrcs[url];
+ const renderTile = (title: string, url: string, identity: string) => {
+ const tileSrc = failedThumbnails[identity] ? null : thumbnailSrcs[identity];
if (tileSrc) {
return (
@@ -132,7 +134,7 @@ export default function ImageResultsList({
src={tileSrc}
loading="lazy"
style={imageStyle}
- onError={() => markThumbnailFailed(url)}
+ onError={() => markThumbnailFailed(identity)}
/>
);
}
@@ -140,7 +142,7 @@ export default function ImageResultsList({
// `null` means the result has no thumbnail, or the load failed: the host
// name is the most that can be shown. `undefined` means the src is still
// being resolved, so the tile keeps a skeleton in the meantime.
- if (thumbnailSrcs[url] === undefined) {
+ if (thumbnailSrcs[identity] === undefined) {
return (
@@ -176,89 +178,97 @@ export default function ImageResultsList({
loop: true,
}}
>
- {imageResults.map(([title, url], index) => (
-
- {(styles) => (
-
- handleImageClick(index)}
- >
- {renderTile(title, url)}
-
-
- )}
-
- ))}
+ {imageResults.map(([title, url, thumbnailUrl, sourceUrl], index) => {
+ const identity = getImageIdentity(sourceUrl, thumbnailUrl, url);
+ return (
+
+ {(styles) => (
+
+ handleImageClick(index)}
+ >
+ {renderTile(title, url, identity)}
+
+
+ )}
+
+ );
+ })}
setState((prev) => ({ ...prev, isLightboxOpen: false }))}
plugins={[Captions]}
index={state.lightboxIndex}
- slides={imageResults.map(([title, url, , sourceUrl]) => ({
- // The grid's thumbnail when it loaded; when it did not, the same
- // host-name placeholder the tile shows.
- src:
- thumbnailSrcs[url] && !failedThumbnails[url]
- ? thumbnailSrcs[url]
- : hostNamePlaceholder(getHostname(url)),
- alt: title,
- description: (
-
- {title && (
-
- {title}
-
- )}
- {sourceUrl && (
-
- Source: {getHostname(sourceUrl)}
-
- )}
-
+ slides={imageResults.map(([title, url, thumbnailUrl, sourceUrl]) => {
+ const identity = getImageIdentity(sourceUrl, thumbnailUrl, url);
+ return {
+ // The grid's thumbnail when it loaded; when it did not, the same
+ // host-name placeholder the tile shows.
+ src:
+ thumbnailSrcs[identity] && !failedThumbnails[identity]
+ ? thumbnailSrcs[identity]
+ : hostNamePlaceholder(getHostname(url)),
+ alt: title,
+ description: (
+
+ {title && (
+
+ {title}
+
+ )}
{sourceUrl && (
+
+ Source: {getHostname(sourceUrl)}
+
+ )}
+
+ {sourceUrl && (
+
+ )}
- )}
-
-
-
- ),
- }))}
+
+
+ ),
+ };
+ })}
/>
>
);
diff --git a/client/modules/chatHelpers.test.ts b/client/modules/chatHelpers.test.ts
index 79b85457d..6d684d053 100644
--- a/client/modules/chatHelpers.test.ts
+++ b/client/modules/chatHelpers.test.ts
@@ -151,11 +151,26 @@ describe("refreshTextSearchResults", () => {
describe("refreshImageSearchResults", () => {
it("deduplicates by URL and prepends fresh results", async () => {
const existing: ImageSearchResults = [
- ["Existing", "https://existing.com", "thumb", "source"],
+ [
+ "Existing",
+ "https://existing.com",
+ "https://existing.com/thumb.jpg",
+ "https://existing.com/full.jpg",
+ ],
];
const fresh: ImageSearchResults = [
- ["New", "https://new.com", "thumb", "source"],
- ["Duplicate", "https://existing.com", "thumb", "source"],
+ [
+ "New",
+ "https://new.com",
+ "https://new.com/thumb.jpg",
+ "https://new.com/full.jpg",
+ ],
+ [
+ "Duplicate",
+ "https://existing.com",
+ "https://existing.com/thumb.jpg",
+ "https://existing.com/full.jpg",
+ ],
];
mockSearchImages.mockResolvedValueOnce({ results: fresh, stale: false });
@@ -163,17 +178,81 @@ describe("refreshImageSearchResults", () => {
await refreshImageSearchResults("query", 10, existing);
expect(mockUpdateImage).toHaveBeenCalledWith([
- ["New", "https://new.com", "thumb", "source"],
- ["Existing", "https://existing.com", "thumb", "source"],
+ [
+ "New",
+ "https://new.com",
+ "https://new.com/thumb.jpg",
+ "https://new.com/full.jpg",
+ ],
+ [
+ "Existing",
+ "https://existing.com",
+ "https://existing.com/thumb.jpg",
+ "https://existing.com/full.jpg",
+ ],
]);
});
+ it("deduplicates by image identity rather than page URL", async () => {
+ const gallery = "https://example.com/gallery";
+ const existing: ImageSearchResults = [
+ [
+ "Existing",
+ gallery,
+ "https://cdn.example.com/existing-thumb.gif",
+ "https://cdn.example.com/existing.gif",
+ ],
+ [
+ "Existing fallback",
+ gallery,
+ "https://cdn.example.com/existing-fallback-thumb.gif",
+ "",
+ ],
+ ];
+ const fresh: ImageSearchResults = [
+ [
+ "Same gallery, new image",
+ gallery,
+ "https://cdn.example.com/fresh-thumb.gif",
+ "https://cdn.example.com/fresh.gif",
+ ],
+ [
+ "Same image",
+ "https://example.com/other-page",
+ "https://cdn.example.com/other-thumb.gif",
+ "https://cdn.example.com/existing.gif",
+ ],
+ [
+ "Same fallback thumbnail",
+ "https://example.com/other-page",
+ "https://cdn.example.com/existing-fallback-thumb.gif",
+ "",
+ ],
+ ];
+
+ mockSearchImages.mockResolvedValueOnce({ results: fresh, stale: false });
+
+ await refreshImageSearchResults("query", 10, existing);
+
+ expect(mockUpdateImage).toHaveBeenCalledWith([fresh[0], ...existing]);
+ });
+
it("keeps the first search's images that landed after the follow-up started", async () => {
const firstImages: ImageSearchResults = [
- ["First", "https://first.com", "thumb", "source"],
+ [
+ "First",
+ "https://first.com",
+ "https://first.com/thumb.jpg",
+ "https://first.com/full.jpg",
+ ],
];
const fresh: ImageSearchResults = [
- ["New", "https://new.com", "thumb", "source"],
+ [
+ "New",
+ "https://new.com",
+ "https://new.com/thumb.jpg",
+ "https://new.com/full.jpg",
+ ],
];
mockSearchImages.mockResolvedValueOnce({ results: fresh, stale: false });
// The follow-up was handed an empty list; the first images arrived since.
@@ -188,14 +267,14 @@ describe("refreshImageSearchResults", () => {
{
title: "New",
url: "https://new.com",
- thumbnail: "thumb",
- sourceUrl: "source",
+ thumbnail: "https://new.com/thumb.jpg",
+ sourceUrl: "https://new.com/full.jpg",
},
{
title: "First",
url: "https://first.com",
- thumbnail: "thumb",
- sourceUrl: "source",
+ thumbnail: "https://first.com/thumb.jpg",
+ sourceUrl: "https://first.com/full.jpg",
},
],
});
@@ -203,12 +282,27 @@ describe("refreshImageSearchResults", () => {
it("shows an image found by both searches once", async () => {
const firstImages: ImageSearchResults = [
- ["First", "https://first.com", "thumb", "source"],
+ [
+ "First",
+ "https://first.com",
+ "https://first.com/thumb.jpg",
+ "https://first.com/full.jpg",
+ ],
];
mockSearchImages.mockResolvedValueOnce({
results: [
- ["New", "https://new.com", "thumb", "source"],
- ["First again", "https://first.com", "thumb", "source"],
+ [
+ "New",
+ "https://new.com",
+ "https://new.com/thumb.jpg",
+ "https://new.com/full.jpg",
+ ],
+ [
+ "First again",
+ "https://first.com",
+ "https://first.com/thumb.jpg",
+ "https://first.com/full.jpg",
+ ],
],
stale: false,
});
@@ -217,7 +311,12 @@ describe("refreshImageSearchResults", () => {
await refreshImageSearchResults("query", 10, []);
expect(mockUpdateImage).toHaveBeenCalledWith([
- ["New", "https://new.com", "thumb", "source"],
+ [
+ "New",
+ "https://new.com",
+ "https://new.com/thumb.jpg",
+ "https://new.com/full.jpg",
+ ],
...firstImages,
]);
});
diff --git a/client/modules/chatHelpers.ts b/client/modules/chatHelpers.ts
index bbfe5621b..2d5c4b5fd 100644
--- a/client/modules/chatHelpers.ts
+++ b/client/modules/chatHelpers.ts
@@ -7,6 +7,7 @@ import {
type TextResults,
updateSearchResults,
} from "./history";
+import { imagesNotIn } from "./imageResults";
import { addLogEntry } from "./logEntries";
import { fetchPageContents } from "./pageContent";
import {
@@ -136,15 +137,11 @@ export async function refreshImageSearchResults(
// The first search's images can land after this refresh started, so it adds
// to the list on screen now as well as the one it was handed then.
const shown = isCurrent() ? getImageSearchResults() : [];
- const shownUrls = new Set(shown.map(([, url]) => url));
const baseResults: ImageSearchResults = [
...shown,
- ...existingResults.filter(([, url]) => !shownUrls.has(url)),
+ ...imagesNotIn(shown, existingResults),
];
- const existingUrls = new Set(baseResults.map(([, url]) => url));
- const uniqueFreshResults = imageResults.filter(
- ([, url]) => !existingUrls.has(url),
- );
+ const uniqueFreshResults = imagesNotIn(baseResults, imageResults);
if (uniqueFreshResults.length > 0) {
const updatedImageResults: ImageSearchResults = [
diff --git a/client/modules/history.test.ts b/client/modules/history.test.ts
index bb54c99cc..223302bf4 100644
--- a/client/modules/history.test.ts
+++ b/client/modules/history.test.ts
@@ -427,6 +427,79 @@ describe("History Module - Dexie CRUD", () => {
]);
});
+ it("merges images by image source, falling back to the thumbnail", async () => {
+ const {
+ addSearchToHistory,
+ mergeSearchImageResults,
+ getRecentSearches,
+ getCurrentSearchRunId,
+ } = await import("./history");
+ const gallery = "https://example.com/gallery";
+ const storedFirst = {
+ title: "Stored first",
+ url: gallery,
+ thumbnail: "https://cdn.example.com/first-thumb.gif",
+ sourceUrl: "https://cdn.example.com/first.gif",
+ };
+ const storedDuplicate = {
+ title: "Stored duplicate",
+ url: "https://example.com/other-page",
+ thumbnail: "https://cdn.example.com/duplicate-thumb.gif",
+ sourceUrl: "https://cdn.example.com/first.gif",
+ };
+ const storedFallback = {
+ title: "Stored fallback",
+ url: gallery,
+ thumbnail: "https://cdn.example.com/fallback-thumb.gif",
+ };
+ const storedKept = {
+ title: "Stored kept",
+ url: "https://example.com/kept",
+ thumbnail: "https://cdn.example.com/kept-thumb.gif",
+ sourceUrl: "https://cdn.example.com/kept.gif",
+ };
+ await addSearchToHistory("identity merge", {
+ type: "image",
+ items: [storedFirst, storedDuplicate, storedFallback, storedKept],
+ });
+
+ const freshSameSource = {
+ title: "Fresh first",
+ url: gallery,
+ thumbnail: "https://cdn.example.com/fresh-first-thumb.gif",
+ sourceUrl: storedFirst.sourceUrl,
+ };
+ const freshSecond = {
+ title: "Fresh second",
+ url: gallery,
+ thumbnail: "https://cdn.example.com/fresh-second-thumb.gif",
+ sourceUrl: "https://cdn.example.com/fresh-second.gif",
+ };
+ const freshFallback = {
+ title: "Fresh fallback",
+ url: gallery,
+ thumbnail: storedFallback.thumbnail,
+ };
+ const freshNewFallback = {
+ title: "Fresh new fallback",
+ url: gallery,
+ thumbnail: "https://cdn.example.com/fresh-new-fallback-thumb.gif",
+ };
+ await mergeSearchImageResults(getCurrentSearchRunId(), {
+ type: "image",
+ items: [freshSameSource, freshSecond, freshFallback, freshNewFallback],
+ });
+
+ const [entry] = await getRecentSearches();
+ expect(entry.imageResults?.items).toEqual([
+ freshSameSource,
+ freshSecond,
+ freshFallback,
+ freshNewFallback,
+ storedKept,
+ ]);
+ });
+
it("keeps both sets whichever image search lands first, and a retry starts over", async () => {
const {
addSearchToHistory,
diff --git a/client/modules/history.ts b/client/modules/history.ts
index 9bb1abc8a..991531b6e 100644
--- a/client/modules/history.ts
+++ b/client/modules/history.ts
@@ -1,3 +1,4 @@
+import { getImageIdentity } from "@shared/imageIdentity";
import Dexie, { type Table, type Transaction } from "dexie";
import { addLogEntry } from "./logEntries";
import { getSettings } from "./pubSub";
@@ -358,7 +359,7 @@ export async function updateSearchResults(
* Adds `results` to the images stored for the search instead of replacing them.
* Every image write goes through here: the screen can lack images the stored
* list has (a late first search merged after the user left and came back), so
- * replacing it with the screen's list would drop them. A URL is stored once.
+ * replacing it with the screen's list would drop them. An image is stored once.
* With `newFirst`, the new images go ahead of the stored ones; otherwise after.
*/
export async function mergeSearchImageResults(
@@ -381,8 +382,17 @@ export async function mergeSearchImageResults(
latest.imageResults ??
(latest.results?.type === "image" ? latest.results : undefined)
)?.items ?? [];
- const newUrls = new Set(results.items.map((item) => item.url));
- const keptItems = storedItems.filter((item) => !newUrls.has(item.url));
+ const newIdentities = new Set(
+ results.items.map((item) =>
+ getImageIdentity(item.sourceUrl, item.thumbnail, item.url),
+ ),
+ );
+ const keptItems = storedItems.filter(
+ (item) =>
+ !newIdentities.has(
+ getImageIdentity(item.sourceUrl, item.thumbnail, item.url),
+ ),
+ );
await historyDatabase.searches.update(latest.id, {
imageResults: {
type: "image",
diff --git a/client/modules/imageResults.ts b/client/modules/imageResults.ts
new file mode 100644
index 000000000..3c91f599c
--- /dev/null
+++ b/client/modules/imageResults.ts
@@ -0,0 +1,22 @@
+import { getImageIdentity } from "@shared/imageIdentity";
+import type { ImageSearchResults } from "./types";
+
+function imageResultIdentity([
+ ,
+ url,
+ thumbnailUrl,
+ sourceUrl,
+]: ImageSearchResults[number]): string {
+ return getImageIdentity(sourceUrl, thumbnailUrl, url);
+}
+
+/** The `candidates` whose image is not already in `listed`. */
+export function imagesNotIn(
+ listed: ImageSearchResults,
+ candidates: ImageSearchResults,
+): ImageSearchResults {
+ const listedIdentities = new Set(listed.map(imageResultIdentity));
+ return candidates.filter(
+ (result) => !listedIdentities.has(imageResultIdentity(result)),
+ );
+}
diff --git a/client/modules/textGeneration.degradation.test.ts b/client/modules/textGeneration.degradation.test.ts
index dec03ea70..d456472bf 100644
--- a/client/modules/textGeneration.degradation.test.ts
+++ b/client/modules/textGeneration.degradation.test.ts
@@ -699,6 +699,31 @@ describe("search supersession ownership", () => {
);
});
+ it("keeps a gallery image that shares its page URL with a follow-up image", async () => {
+ const { finishImages } = await searchWithFollowUpImagesFirst();
+
+ const gallery = "https://gallery.example/page";
+ const followUp: ImageSearchResults[number] = [
+ "Follow-up",
+ gallery,
+ "thumb-follow",
+ "https://cdn.example/follow-up.gif",
+ ];
+ harness.state.imageSearchResults = [followUp];
+ const first: ImageSearchResults[number] = [
+ "First",
+ gallery,
+ "thumb-first",
+ "https://cdn.example/first.gif",
+ ];
+ await finishImages([first]);
+
+ expect(vi.mocked(updateImageSearchResults)).toHaveBeenLastCalledWith([
+ followUp,
+ first,
+ ]);
+ });
+
it("keeps a follow-up's images when the first image search finds none", async () => {
const { finishImages } = await searchWithFollowUpImagesFirst();
await finishImages([]);
diff --git a/client/modules/textGeneration.ts b/client/modules/textGeneration.ts
index a83b4a5a4..b40fab9ec 100644
--- a/client/modules/textGeneration.ts
+++ b/client/modules/textGeneration.ts
@@ -8,6 +8,7 @@ import {
saveLlmResponseForQuery,
updateSearchResults,
} from "./history";
+import { imagesNotIn } from "./imageResults";
import { addLogEntry } from "./logEntries";
import { showAiCompleteNotification } from "./notifications";
import { fetchPageContents } from "./pageContent";
@@ -861,10 +862,9 @@ async function startImageSearch(
// A follow-up can add images while this search is still running; they
// stay, ahead of this search's own.
const shown = isCurrent() ? getImageSearchResults() : [];
- const shownUrls = new Set(shown.map(([, url]) => url));
const mergedResults: ImageSearchResults = [
...shown,
- ...imageResults.filter(([, url]) => !shownUrls.has(url)),
+ ...imagesNotIn(shown, imageResults),
];
if (isCurrent()) {
diff --git a/server/searchEndpointServerHook.test.ts b/server/searchEndpointServerHook.test.ts
index 9bd29c3d9..d5992f953 100644
--- a/server/searchEndpointServerHook.test.ts
+++ b/server/searchEndpointServerHook.test.ts
@@ -389,6 +389,49 @@ describe("searchEndpointServerHook", () => {
fetchSpy.mockRestore();
});
+ it("reranks image results by image identity when they share a page URL", async () => {
+ const gallery = "https://example.com/gallery";
+ const first: [string, string, string, string] = [
+ "First image",
+ gallery,
+ "https://cdn.example.com/first-thumb.gif",
+ "https://cdn.example.com/first.gif",
+ ];
+ const second: [string, string, string, string] = [
+ "Second image",
+ gallery,
+ "https://cdn.example.com/second-thumb.gif",
+ "https://cdn.example.com/second.gif",
+ ];
+ const fallback: [string, string, string, string] = [
+ "Image without a source",
+ gallery,
+ "https://cdn.example.com/fallback-thumb.gif",
+ "",
+ ];
+ vi.mocked(fetchSearXNG).mockResolvedValue([first, second, fallback]);
+ vi.mocked(getRerankerStatus).mockResolvedValue(true);
+ vi.mocked(rankSearchResults).mockResolvedValue([
+ [second[0], "", second[3], 0.9],
+ [fallback[0], "", fallback[2], 0.8],
+ [first[0], "", first[3], 0.7],
+ ]);
+
+ const response = await sendSearch("/search/images?q=cats&token=abc");
+
+ expect(rankSearchResults).toHaveBeenCalledWith(
+ "cats",
+ "images",
+ [
+ [first[0], "", first[3]],
+ [second[0], "", second[3]],
+ [fallback[0], "", fallback[2]],
+ ],
+ false,
+ );
+ expect(endBody(response)).toEqual([second, fallback, first]);
+ });
+
describe("graceful degradation", () => {
const searxngResults: [string, string, string][] = [
["A", "snippet a", "https://a.com"],
diff --git a/server/searchEndpointServerHook.ts b/server/searchEndpointServerHook.ts
index 4e986ce56..9cade4b6b 100644
--- a/server/searchEndpointServerHook.ts
+++ b/server/searchEndpointServerHook.ts
@@ -1,5 +1,6 @@
import type { PreviewServer, ViteDevServer } from "vite";
import { z } from "zod";
+import { getImageIdentity } from "../shared/imageIdentity.ts";
import {
assertSearchFallbackConfiguration,
fetchFallbackTextResults,
@@ -335,7 +336,12 @@ export function searchEndpointServerHook<
} else {
const results = searchResults as ImageResult[];
const resultsText = results.map(
- ([title, url]) => [title?.slice(0, 100) || "", "", url] as TextResult,
+ ([title, url, thumbnailSource, sourceUrl]) =>
+ [
+ title?.slice(0, 100) || "",
+ "",
+ getImageIdentity(sourceUrl, thumbnailSource, url),
+ ] as TextResult,
);
const rankedResults = await handleRanking(
query,
@@ -344,9 +350,11 @@ export function searchEndpointServerHook<
);
const processedResults = rankedResults
- .map(([title, , rankedResultUrl]) => {
+ .map(([title, , rankedResultIdentity]) => {
const result = results.find(
- ([, resultUrl]) => resultUrl === rankedResultUrl,
+ ([, url, thumbnailSource, sourceUrl]) =>
+ getImageIdentity(sourceUrl, thumbnailSource, url) ===
+ rankedResultIdentity,
);
if (!result) return null;
const [, url, thumbnailSource, sourceUrl] = result;
diff --git a/server/webSearchService.test.ts b/server/webSearchService.test.ts
index 6f45174cb..e55f7e44d 100644
--- a/server/webSearchService.test.ts
+++ b/server/webSearchService.test.ts
@@ -675,6 +675,111 @@ describe("graceful degradation", () => {
]),
);
});
+
+ it("identifies image results by image source, falling back to the thumbnail", async () => {
+ const gallery = "https://example.com/gallery";
+ fetchMock.mockResolvedValue(
+ createMockResponse(
+ JSON.stringify({
+ results: [
+ {
+ title: "First image",
+ url: gallery,
+ category: "images",
+ img_src: "https://cdn.example.com/first.gif",
+ thumbnail_src: "https://cdn.example.com/first-thumb.gif",
+ },
+ {
+ title: "Second image",
+ url: gallery,
+ category: "images",
+ img_src: "https://cdn.example.com/second.gif",
+ thumbnail_src: "https://cdn.example.com/second-thumb.gif",
+ },
+ {
+ title: "Duplicate image",
+ url: "https://example.com/other-page",
+ category: "images",
+ img_src: "https://cdn.example.com/second.gif",
+ thumbnail_src: "https://cdn.example.com/duplicate-thumb.gif",
+ },
+ {
+ title: "Image without a source",
+ url: "https://example.com/no-source",
+ category: "images",
+ thumbnail_src: "https://cdn.example.com/fallback-thumb.gif",
+ },
+ {
+ title: "Same fallback thumbnail",
+ url: "https://example.com/another-page",
+ category: "images",
+ thumbnail_src: "https://cdn.example.com/fallback-thumb.gif",
+ },
+ ],
+ }),
+ ),
+ );
+
+ const results = await fetchSearXNG(
+ "failure injection",
+ "images",
+ 5,
+ new CircuitBreaker(breakerOptions),
+ );
+
+ expect(results).toEqual([
+ [
+ "First image",
+ gallery,
+ "https://cdn.example.com/first-thumb.gif",
+ "https://cdn.example.com/first.gif",
+ ],
+ [
+ "Second image",
+ gallery,
+ "https://cdn.example.com/second-thumb.gif",
+ "https://cdn.example.com/second.gif",
+ ],
+ [
+ "Image without a source",
+ "https://example.com/no-source",
+ "https://cdn.example.com/fallback-thumb.gif",
+ "",
+ ],
+ ]);
+ });
+
+ it("still deduplicates text results by page URL", async () => {
+ fetchMock.mockResolvedValue(
+ createMockResponse(
+ JSON.stringify({
+ results: [
+ {
+ title: "First page",
+ url: "https://example.com/page",
+ content: "first snippet",
+ },
+ {
+ title: "Second page",
+ url: "https://example.com/page",
+ content: "second snippet",
+ },
+ ],
+ }),
+ ),
+ );
+
+ const results = await fetchSearXNG(
+ "failure injection",
+ "text",
+ 5,
+ new CircuitBreaker(breakerOptions),
+ );
+
+ expect(results).toEqual([
+ ["First page", "first snippet", "https://example.com/page"],
+ ]);
+ });
});
describe("query privacy", () => {
diff --git a/server/webSearchService.ts b/server/webSearchService.ts
index 160e8b3ff..ad1081812 100644
--- a/server/webSearchService.ts
+++ b/server/webSearchService.ts
@@ -2,6 +2,7 @@ import { basename } from "node:path";
import debug from "debug";
import { convert as convertHtmlToPlainText } from "html-to-text";
import { strip as stripEmojis } from "node-emoji";
+import { getImageIdentity } from "../shared/imageIdentity.ts";
import {
type EngineFailure,
getDegradedSearchTypes,
@@ -376,7 +377,7 @@ async function processSearchResults(
const results = await breaker.execute(circuitKey(searchType), () =>
performSearch(query, searchType, signal),
);
- const openableResults = openableUniqueResults(results);
+ const openableResults = openableUniqueResults(results, searchType);
if (searchType === "text") {
const consideredResults = openableResults.slice(0, limit);
@@ -478,26 +479,36 @@ export async function fetchSupplementarySearXNG(
const data = (await response.json()) as SearxngSearchResponse;
const results = Array.isArray(data.results) ? data.results : [];
const textualResults = await Promise.all(
- openableUniqueResults(results).slice(0, limit).map(processTextualResult),
+ openableUniqueResults(results, "text")
+ .slice(0, limit)
+ .map(processTextualResult),
);
return filterNullResults(textualResults);
}
+function graphicalThumbnailSource(result: SearxngSearchResult) {
+ return result.category === "videos" ? result.thumbnail : result.thumbnail_src;
+}
+
+function graphicalSourceUrl(result: SearxngSearchResult) {
+ // Empty string, not undefined: the client reads the tuple positionally and
+ // treats an empty source as "no link to the full image".
+ return (
+ (result.category === "videos"
+ ? result.iframe_src || result.url
+ : result.img_src) ?? ""
+ );
+}
+
async function processGraphicalResult(result: SearxngSearchResult) {
- const thumbnailSource =
- result.category === "videos" ? result.thumbnail : result.thumbnail_src;
+ const thumbnailSource = graphicalThumbnailSource(result);
// A grid tile is the thumbnail: without one there is nothing to show but the
// host name, and SearXNG leaves the field out often enough (video engines
// especially) that keeping these fills the carousel with text placeholders.
if (!thumbnailSource) return null;
- // Empty string, not undefined: the client reads the tuple positionally and
- // treats an empty source as "no link to the full image".
- const sourceUrl =
- (result.category === "videos"
- ? result.iframe_src || result.url
- : result.img_src) ?? "";
+ const sourceUrl = graphicalSourceUrl(result);
return [result.title, result.url, thumbnailSource, sourceUrl] as [
title: string,
@@ -548,16 +559,27 @@ async function processTextualResult(result: SearxngSearchResult) {
// of a result that would have made the cut.
function openableUniqueResults(
results: SearxngSearchResult[],
+ searchType: SearchType,
): SearxngSearchResult[] {
- const urls = new Set();
+ const identities = new Set();
const unopenableEngines: string[] = [];
const kept = results.filter((result) => {
if (!isOpenableUrl(result.url)) {
unopenableEngines.push(result.engine ?? "unknown");
return false;
}
- if (urls.has(result.url)) return false;
- urls.add(result.url);
+ // Text results are pages, so their URL names them. Image results are
+ // identified by the image itself: one gallery page can hold many results.
+ const identity =
+ searchType === "images"
+ ? getImageIdentity(
+ graphicalSourceUrl(result),
+ graphicalThumbnailSource(result),
+ result.url,
+ )
+ : result.url;
+ if (identities.has(identity)) return false;
+ identities.add(identity);
return true;
});
// Engine names only: the url is downstream of the query, which never reaches
diff --git a/shared/imageIdentity.ts b/shared/imageIdentity.ts
new file mode 100644
index 000000000..f8d659520
--- /dev/null
+++ b/shared/imageIdentity.ts
@@ -0,0 +1,12 @@
+/**
+ * Identity of an image result: its full-size image when the result carries
+ * one, otherwise its thumbnail, otherwise its page. The page URL alone cannot
+ * tell images apart, since one gallery page can hold many different images.
+ */
+export function getImageIdentity(
+ sourceUrl: string | undefined,
+ thumbnailUrl: string | undefined,
+ pageUrl: string,
+): string {
+ return sourceUrl || thumbnailUrl || pageUrl;
+}