From c79157e570874e24b5f97df7321159893bccb20e Mon Sep 17 00:00:00 2001
From: Yunfan Bai <bcy603@gmail.com>
Date: Mon, 23 Oct 2023 06:51:29 -0700
Subject: [PATCH] Fixing a bug in compareExistingImages

Fixes an uncaught exception in compareExistingImages.
App.Art.GenAI.imageDB.getImage may returns a undefined and causes an
error in compareExistingImages if the db is purged. Fixes #4847.
---
 src/art/genAI/imageDB.js         | 10 +++++++++-
 src/art/genAI/stableDiffusion.js | 12 ++++++++----
 2 files changed, 17 insertions(+), 5 deletions(-)

diff --git a/src/art/genAI/imageDB.js b/src/art/genAI/imageDB.js
index 3c6e5973d0d..612ee621154 100644
--- a/src/art/genAI/imageDB.js
+++ b/src/art/genAI/imageDB.js
@@ -68,7 +68,15 @@ App.Art.GenAI.imageDB = (function() {
 			const request = objectStore.get(id);
 
 			request.onsuccess = function() {
-				resolve(request.result);
+				if (request.result === undefined) {
+					reject(new Error(`Image with ID ${id} not found in the database.`));
+				} else {
+					resolve(request.result);
+				}
+			};
+
+			request.onerror = function() {
+				reject(new Error(`Error fetching image with ID ${id}`));
 			};
 		});
 	}
diff --git a/src/art/genAI/stableDiffusion.js b/src/art/genAI/stableDiffusion.js
index 17f21fd98dc..70a48f888c2 100644
--- a/src/art/genAI/stableDiffusion.js
+++ b/src/art/genAI/stableDiffusion.js
@@ -271,10 +271,14 @@ App.Art.GenAI.StableDiffusionClient = class {
  * @returns {Promise<number>} index of the image in aiImageIds or -1
  */
 async function compareExistingImages(slave, newImageData) {
-	const aiImages = await Promise.all(slave.custom.aiImageIds.map(id => {
-		return App.Art.GenAI.imageDB.getImage(id);
-	}));
-	return aiImages.findIndex(img => img.data === newImageData);
+	const aiImages = await Promise.all(
+		slave.custom.aiImageIds.map(id =>
+			App.Art.GenAI.imageDB.getImage(id)
+				.catch(() => null)  // Return null if the image is not found or there's an error
+		)
+	);
+
+	return aiImages.findIndex(img => img && img.data === newImageData);
 }
 
 /**
-- 
GitLab