Merge pull request #2445 from Risenafis/fix-initvoicemap Prevent concurrent execution of initVoiceMap

cee304fe29e8b599230970c8001719802b19c555

Cohee <18619528+Cohee1207@users.noreply.github.com>

Signed
1 files changed, +32 -1Showing whitespace changes
public/scripts/extensions/tts/index.js+32 -1
@@ -1,4 +1,4 @@
11import { cancelTtsPlay, eventSource, event_types, getCurrentChatId, isStreamingEnabled, name2, saveSettingsDebounced, substituteParams } from '../../../script.js';
22import { ModuleWorkerWrapper, doExtrasFetch, extension_settings, getApiUrl, getContext, modules, renderExtensionTemplateAsync } from '../../extensions.js';
33import { delay, escapeRegex, getBase64Async, getStringHash, onlyUnique } from '../../utils.js';
44import { EdgeTtsProvider } from './edge.js';
@@ -35,6 +35,7 @@ let lastMessage = null;
3535let lastMessageHash = null;
3636let periodicMessageGenerationTimer = null;
3737let lastPositionOfParagraphEnd = -1;
38+let currentInitVoiceMapPromise = null;
3839
3940const DEFAULT_VOICE_MARKER = '[Default Voice]';
4041const DISABLED_VOICE_MARKER = 'disabled';
@@ -1010,9 +1011,39 @@ class VoiceMapEntry {
10101011
10111012/**
10121013 * Init voiceMapEntries for character select list.
1014+ * If an initialization is already in progress, it returns the existing Promise instead of starting a new one.
10131015 * @param {boolean} unrestricted - If true, will include all characters in voiceMapEntries, even if they are not in the current chat.
1016+ * @returns {Promise} A promise that resolves when the initialization is complete.
10141017 */
10151018export async function initVoiceMap(unrestricted = false) {
1019+ // Preventing parallel execution
1020+ if (currentInitVoiceMapPromise) {
1021+ return currentInitVoiceMapPromise;
1022+ }
1023+
1024+ currentInitVoiceMapPromise = (async () => {
1025+ const initialChatId = getCurrentChatId();
1026+ try {
1027+ await initVoiceMapInternal(unrestricted);
1028+ } finally {
1029+ currentInitVoiceMapPromise = null;
1030+ }
1031+ const currentChatId = getCurrentChatId();
1032+
1033+ if (initialChatId !== currentChatId) {
1034+ // Chat changed during initialization, reinitialize
1035+ await initVoiceMap(unrestricted);
1036+ }
1037+ })();
1038+
1039+ return currentInitVoiceMapPromise;
1040+}
1041+
1042+/**
1043+ * Init voiceMapEntries for character select list.
1044+ * @param {boolean} unrestricted - If true, will include all characters in voiceMapEntries, even if they are not in the current chat.
1045+ */
1046+async function initVoiceMapInternal(unrestricted) {
10161047 // Gate initialization if not enabled or TTS Provider not ready. Prevents error popups.
10171048 const enabled = $('#tts_enabled').is(':checked');
10181049 if (!enabled) {