Chore: enable brace-style eslint check (#5159) * eslint: enable brace-style check * Fix jsdoc and color * fix: correct CSS color syntax in CreateZenSliders function

4d1619ba478804074a0894313e7ea710f713441d

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

Signed
62 files changed, +344 -676Ignore whitespace
.eslintrc.cjs+1 -1
@@ -102,8 +102,8 @@ module.exports = {
102102 // These rules should eventually be enabled.
103103 'no-async-promise-executor': 'off',
104104 'no-inner-declarations': 'off',
105- 'brace-style': 'off',
106105 // Additional formatting rules based on codebase conventions
106+ 'brace-style': ['error', '1tbs', { allowSingleLine: true }],
107107 'array-bracket-spacing': ['error', 'never'],
108108 'computed-property-spacing': ['error', 'never'],
109109 'block-spacing': ['error', 'always'],
plugins.js+1 -2
@@ -89,8 +89,7 @@ async function installPlugin(pluginName) {
8989
9090 await git().clone(pluginName, pluginPath, { '--depth': 1 });
9191 console.log(`Plugin ${color.green(pluginName)} installed to ${color.cyan(pluginPath)}`);
92- }
92+ } catch (error) {
93- catch (error) {
9493 console.error(color.red(`Failed to install plugin ${pluginName}`), error);
9594 }
9695}
public/script.js+57 -121
@@ -512,8 +512,7 @@ export function reloadMarkdownProcessor() {
512512export function getCurrentChatId() {
513513 if (selected_group) {
514514 return groups.find(x => x.id == selected_group)?.chat_id;
515- }
515+ } else if (this_chid !== undefined) {
516- else if (this_chid !== undefined) {
517516 return characters[this_chid]?.chat;
518517 }
519518}
@@ -910,8 +909,7 @@ function getCharacterBlock(item, id) {
910909 const description = item.data?.creator_notes || '';
911910 if (description) {
912911 template.find('.ch_description').text(description);
913912 } else {
914- else {
915913 template.find('.ch_description').hide();
916914 }
917915
@@ -919,8 +917,7 @@ function getCharacterBlock(item, id) {
919917 const auxFieldValue = (item.data && item.data[auxFieldName]) || '';
920918 if (auxFieldValue) {
921919 template.find('.character_version').text(auxFieldValue);
922920 } else {
923- else {
924921 template.find('.character_version').hide();
925922 }
926923
@@ -1364,16 +1361,14 @@ export async function replaceCurrentChat() {
13641361 const chats = Object.values(await chatsResponse.json());
13651362 chats.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes)));
13661363
1367- // pick existing chat
13681364 if (chats.length && typeof chats[0] === 'object') {
1365+ // pick existing chat
13691366 characters[this_chid].chat = chats[0].file_name.replace('.jsonl', '');
13701367 $('#selected_chat_pole').val(characters[this_chid].chat);
13711368 saveCharacterDebounced();
13721369 await getChat();
13731370 } else {
1374-
1371+ // start new chat
1375- // start new chat
1376- else {
13771372 characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
13781373 $('#selected_chat_pole').val(characters[this_chid].chat);
13791374 saveCharacterDebounced();
@@ -1640,11 +1635,9 @@ export async function reloadCurrentChatUnsafe() {
16401635
16411636 if (selected_group) {
16421637 await getGroupChat(selected_group, true);
1643- }
1638+ } else if (this_chid !== undefined) {
1644- else if (this_chid !== undefined) {
16451639 await getChat();
16461640 } else {
1647- else {
16481641 resetChatState();
16491642 restoreNeutralChat();
16501643 await getCharacters();
@@ -1870,32 +1863,16 @@ export function messageFormatting(mes, ch_name, isSystem, isUser, messageId, san
18701863/**
18711864 * Inserts or replaces an SVG icon adjacent to the provided message's timestamp.
18721865 *
1873- * If the `extra.api` is "openai" and `extra.model` contains the substring "claude",
1874- * the function fetches the "claude.svg". Otherwise, it fetches the SVG named after
1875- * the value in `extra.api`.
1876- *
18771866 * @param {JQuery<HTMLElement>} mes - The message element containing the timestamp where the icon should be inserted or replaced.
18781867 * @param {ChatMessageExtra} extra - Contains the API and model details.
18791868 */
18801869function insertSVGIcon(mes, extra) {
18811870 // Determine the SVG filename
1882- let modelName;
1871+ let modelName = extra?.api || '';
18831872
1884- // Claude on OpenRouter or Anthropic
1873+ // If there's no API information, we can't determine which SVG to use
1885- if (extra.api === 'openai' && extra.model?.toLowerCase().includes('claude')) {
1874+ if (!modelName) {
1886- modelName = 'claude';
1875+ return;
1887- }
1888- // OpenAI on OpenRouter
1889- else if (extra.api === 'openai' && extra.model?.toLowerCase().includes('openai')) {
1890- modelName = 'openai';
1891- }
1892- // OpenRouter website model or other models
1893- else if (extra.api === 'openai' && (extra.model === null || extra.model?.toLowerCase().includes('/'))) {
1894- modelName = 'openrouter';
1895- }
1896- // Everything else
1897- else {
1898- modelName = extra.api;
18991876 }
19001877
19011878 const insertOrReplaceSVG = (image, className, targetSelector, insertBefore) => {
@@ -3755,8 +3732,7 @@ class StreamingProcessor {
37553732 }
37563733 const seconds = (timestamps[timestamps.length - 1] - timestamps[0]) / 1000;
37573734 console.warn(`Stream stats: ${timestamps.length} tokens, ${seconds.toFixed(2)} seconds, rate: ${Number(timestamps.length / seconds).toFixed(2)} TPS`);
3758- }
3735+ } catch (err) {
3759- catch (err) {
37603736 // in the case of a self-inflicted abort, we have already cleaned up
37613737 if (!this.isFinished) {
37623738 console.error(err);
@@ -4236,8 +4212,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
42364212 textareaText = '';
42374213 if (chat.length && lastMessage.is_user) {
42384214 //do nothing? why does this check exist?
4239- }
4215+ } else if (type !== 'quiet' && type !== 'swipe' && !isImpersonate && !dryRun && !depth && chat.length) {
4240- else if (type !== 'quiet' && type !== 'swipe' && !isImpersonate && !dryRun && !depth && chat.length) {
42414216 deleteItemizedPromptForMessage(chat.length - 1);
42424217 chat.length = chat.length - 1;
42434218 await removeLastMessage();
@@ -4282,12 +4257,10 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
42824257 // If user message contains no text other than bias - send as a system message
42834258 if (messageBias && !removeMacros(textareaText)) {
42844259 sendSystemMessage(system_message_types.GENERIC, ' ', { bias: messageBias });
42854260 } else {
4286- else {
42874261 await sendMessageAsUser(textareaText, messageBias);
42884262 }
4289- }
4263+ } else if (textareaText == '' && !automatic_trigger && !dryRun && [undefined, 'normal'].includes(type) && main_api == 'openai' && oai_settings.send_if_empty.trim().length > 0 && !depth) {
4290- else if (textareaText == '' && !automatic_trigger && !dryRun && [undefined, 'normal'].includes(type) && main_api == 'openai' && oai_settings.send_if_empty.trim().length > 0 && !depth) {
42914264 // Use send_if_empty if set and the user message is empty. Only when sending messages normally
42924265 await sendMessageAsUser(oai_settings.send_if_empty.trim(), messageBias);
42934266 }
@@ -4406,8 +4379,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
44064379 if (main_api == 'koboldhorde' && (horde_settings.auto_adjust_context_length || horde_settings.auto_adjust_response_length)) {
44074380 try {
44084381 adjustedParams = await adjustHordeGenerationParams(max_context, amount_gen);
44094382 } catch {
4410- catch {
44114383 unblockGeneration(type);
44124384 return Promise.resolve();
44134385 }
@@ -4585,8 +4557,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
45854557 // When continuing generation of previous output, last user message precedes the message to continue
45864558 if (isContinue) {
45874559 coreChat.splice(coreChat.length - 1, 0, { mes: jailbreak, is_user: true });
45884560 } else {
4589- else {
45904561 // This operation will result in the injectedIndices indexes being off by one
45914562 coreChat.push({ mes: jailbreak, is_user: true });
45924563 // Add +1 to the elements to correct for the new PHI/Jailbreak message.
@@ -5207,8 +5178,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
52075178
52085179 if (itemizedIndex !== -1) {
52095180 itemizedPrompts[itemizedIndex] = additionalPromptStuff;
52105181 } else {
5211- else {
52125182 itemizedPrompts.push(additionalPromptStuff);
52135183 }
52145184
@@ -5350,17 +5320,14 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
53505320 if (isImpersonate) {
53515321 $('#send_textarea').val(getMessage)[0].dispatchEvent(new Event('input', { bubbles: true }));
53525322 await eventSource.emit(event_types.IMPERSONATE_READY, getMessage);
5353- }
5323+ } else if (type == 'quiet') {
5354- else if (type == 'quiet') {
53555324 unblockGeneration(type);
53565325 return getMessage;
53575326 } else {
5358- else {
53595327 // Without streaming we'll be having a full message on continuation. Treat it as a last chunk.
53605328 if (originalType !== 'continue') {
53615329 ({ type, getMessage } = await saveReply({ type, getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));
53625330 } else {
5363- else {
53645331 ({ type, getMessage } = await saveReply({ type: 'appendFinal', getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));
53655332 }
53665333
@@ -5829,9 +5796,7 @@ function addChatsPreamble(mesSendString) {
58295796function addChatsSeparator(mesSendString) {
58305797 if (power_user.context.chat_start) {
58315798 return substituteParams(power_user.context.chat_start + '\n') + mesSendString;
58325799 } else {
5833-
5834- else {
58355800 return mesSendString;
58365801 }
58375802}
@@ -7055,16 +7020,13 @@ export async function renameCharacter(name = null, { silent = false, renameChats
70557020 } else {
70567021 toastr.success(t`Character renamed!`, t`Rename Character`);
70577022 }
70587023 } else {
7059- else {
70607024 throw new Error('Newly renamed character was lost?');
70617025 }
70627026 } else {
7063- else {
70647027 throw new Error('Could not rename the character');
70657028 }
7066- }
7029+ } catch (error) {
7067- catch (error) {
70687030 // Reloading to prevent data corruption
70697031 if (!silent) await Popup.show.text(t`Rename Character`, t`Something went wrong. The page will be reloaded.`);
70707032 else toastr.error(t`Something went wrong. The page will be reloaded.`, t`Rename Character`);
@@ -7356,8 +7318,7 @@ export function buildAvatarList(block, entities, { templateId = 'inline_avatar_t
73567318 avatarTemplate.append(grpTemplate.children());
73577319 avatarTemplate.attr({ 'data-grid': id, 'data-chid': null });
73587320 avatarTemplate.attr('title', `[Group] ${entity.item.name}`);
7359- }
7321+ } else if (entity.type === 'persona') {
7360- else if (entity.type === 'persona') {
73617322 avatarTemplate.attr({ 'data-pid': id, 'data-chid': null });
73627323 avatarTemplate.find('img').attr('src', getThumbnailUrl('persona', entity.item.avatar));
73637324 avatarTemplate.attr('title', `[Persona] ${entity.item.name}\nFile: ${entity.item.avatar}`);
@@ -8099,8 +8060,7 @@ async function messageEditCancel(messageId = this_edit_mes_id) {
80998060 await eventSource.emit(event_types.MESSAGE_UPDATED, messageId);
81008061 if (messageId == this_edit_mes_id) {
81018062 this_edit_mes_id = undefined;
81028063 } else {
8103- else {
81048064 console.warn(`The message editor was closed on message #${messageId} while #${this_edit_mes_id} is being edited.`);
81058065 }
81068066
@@ -8134,8 +8094,7 @@ async function messageEditMove(sourceId, targetId) {
81348094
81358095 if (sourceId <= targetId) {
81368096 sourceMessageDiv.insertAfter(targetMessageDiv);
81378097 } else {
8138- else {
81398098 sourceMessageDiv.insertBefore(targetMessageDiv);
81408099 }
81418100
@@ -8951,11 +8910,13 @@ export function isMessageSwipeable(messageId, message = undefined) {
89518910 //User messages are not swipeable.
89528911 !message.is_user
89538912 )
89548913 ) {
89558914 // The message is swipeable.
89568915 { return true; }
8957- //The message is not swipeable.
8916+ } else {
8958- else { return false; }
8917+ // The message is not swipeable.
8918+ return false;
8919+ }
89598920}
89608921
89618922/**
@@ -9145,8 +9106,7 @@ export async function saveChatConditional() {
91459106
91469107 if (selected_group) {
91479108 await saveGroupChat(selected_group, true);
91489109 } else {
9149- else {
91509110 await saveChat();
91519111 }
91529112
@@ -9252,8 +9212,7 @@ export function closeMessageEditor(what = 'all') {
92529212export function setGenerationProgress(progress) {
92539213 if (!progress) {
92549214 $('#send_textarea').css({ 'background': '', 'transition': '' });
92559215 } else {
9256- else {
92579216 $('#send_textarea').css({
92589217 'background': `linear-gradient(90deg, #008000d6 ${progress}%, transparent ${progress}%)`,
92599218 'transition': '0.25s ease-in-out',
@@ -9767,8 +9726,7 @@ export async function swipe(event, direction, { source, repeated, message = chat
97679726 document.body.dataset.swiping = 'true';
97689727 await generation;
97699728 }
9770- }
9729+ } catch (error) {
9771- catch (error) {
97729730 console.warn(`Swipe failed, Swiping back. ${error}`);
97739731 }
97749732
@@ -9804,8 +9762,7 @@ export async function swipe(event, direction, { source, repeated, message = chat
98049762 //Update the chat.
98059763 await loadFromSwipeId(mesId, chat[mesId].swipe_id);
98069764 await redisplayChat({ startIndex: mesId });
98079765 } else {
9808- else {
98099766 await Popup.show.confirm(
98109767 t`ERROR: <code>syncSwipeToMes</code> has failed to revert the failed ${direction} swipe on message #${mesId}.`,
98119768 t`<p>After you click OK, the chat will be reloaded to prevent data corruption.</p>`,
@@ -10104,9 +10061,8 @@ export async function swipe(event, direction, { source, repeated, message = chat
1010410061 }
1010510062 await standardSwipe(newSwipeId);
1010610063 return;
10107- }
10064+ } else if (direction === SWIPE_DIRECTION.RIGHT) {
1010810065 //If swiping right.
10109- else if (direction === SWIPE_DIRECTION.RIGHT) {
1011010066 // make new slot in array
1011110067 if (forceSwipeId == null) newSwipeId++;
1011210068
@@ -10133,18 +10089,16 @@ export async function swipe(event, direction, { source, repeated, message = chat
1013310089 chat[mesId].swipe_id = originalSwipeId;
1013410090 await endSwipe();
1013510091 return;
10136- }
10092+ } else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
1013710093 //Regenerate the message
10138- else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
1013910094 clearMessageData(chat[mesId]);
1014010095 let run_generate = true;
1014110096 //Generate.
1014210097 await animateSwipe(run_generate);
1014310098 await endSwipe();
1014410099 return;
10145- }
10100+ } else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
1014610101 // Loop to the first swipe.
10147- else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
1014810102 newSwipeId = 0;
1014910103 }
1015010104 }
@@ -10363,8 +10317,7 @@ export async function doNewChat({ deleteCurrentChat = false } = {}) {
1036310317 if (selected_group) {
1036410318 await createNewGroupChat(selected_group);
1036510319 if (deleteCurrentChat) await deleteGroupChat(selected_group, chat_file_for_del, { jumpToNewChat: false }); // don't jump, new chat was already created and jumped to above
1036610320 } else {
10367- else {
1036810321 //RossAscends: added character name to new chat filenames and replaced Date.now() with humanizedDateTime;
1036910322 chat_metadata = {};
1037010323 characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
@@ -10427,8 +10380,7 @@ export async function renameGroupOrCharacterChat({ characterId, groupId, oldFile
1042710380
1042810381 if (groupId) {
1042910382 await renameGroupChat(groupId, oldFileName, newFileName);
10430- }
10383+ } else if (characterId !== undefined && String(characterId) === String(this_chid) && characters[characterId]?.chat === oldFileName) {
10431- else if (characterId !== undefined && String(characterId) === String(this_chid) && characters[characterId]?.chat === oldFileName) {
1043210384 characters[characterId].chat = newFileName;
1043310385 $('#selected_chat_pole').val(characters[characterId].chat);
1043410386 await createOrEditCharacter();
@@ -11080,8 +11032,7 @@ jQuery(async function () {
1108011032 if (popup_type == 'input') {
1108111033 dialogueResolve($('#dialogue_popup_input').val());
1108211034 $('#dialogue_popup_input').val('');
1108311035 } else {
11084- else {
1108511036 dialogueResolve(true);
1108611037 }
1108711038
@@ -11316,9 +11267,7 @@ jQuery(async function () {
1131611267 });
1131711268 }
1131811269 }
11319- }
11270+ } else if (id == 'option_start_new_chat') {
11320-
11321- else if (id == 'option_start_new_chat') {
1132211271 if ((selected_group || this_chid !== undefined) && !is_send_press) {
1132311272 let deleteCurrentChat = false;
1132411273 const result = await Popup.show.confirm(t`Start new chat?`, await renderTemplateAsync('newChatConfirm'), {
@@ -11334,9 +11283,7 @@ jQuery(async function () {
1133411283 const alreadyInTempChat = this_chid === undefined && name2 === neutralCharacterName;
1133511284 await newAssistantChat({ temporary: alreadyInTempChat });
1133611285 }
11337- }
11286+ } else if (id == 'option_regenerate') {
11338-
11339- else if (id == 'option_regenerate') {
1134011287 //Attempting to regenerate a user message will instead generate a new message.
1134111288 if (chat.length && chat.length - 1 === this_edit_mes_id && chat[this_edit_mes_id]?.is_user == false) {
1134211289 toastr.warning(t`Finish the edit before starting a generation.`, t`You cannot regenerate the message you are editing.`);
@@ -11345,22 +11292,17 @@ jQuery(async function () {
1134511292 if (is_send_press == false) {
1134611293 if (selected_group) {
1134711294 regenerateGroup();
1134811295 } else {
11349- else {
1135011296 is_send_press = true;
1135111297 Generate('regenerate', buildOrFillAdditionalArgs());
1135211298 }
1135311299 }
11354- }
11300+ } else if (id == 'option_impersonate') {
11355-
11356- else if (id == 'option_impersonate') {
1135711301 if (is_send_press == false || fromSlashCommand) {
1135811302 is_send_press = true;
1135911303 Generate('impersonate', buildOrFillAdditionalArgs());
1136011304 }
11361- }
11305+ } else if (id == 'option_continue') {
11362-
11363- else if (id == 'option_continue') {
1136411306 if (swipeState == SWIPE_STATE.EDITING) {
1136511307 toastr.warning(t`Confirm the edit to start a generation.`, t`You cannot send a message during a swipe-edit.`);
1136611308 return;
@@ -11374,17 +11316,11 @@ jQuery(async function () {
1137411316 is_send_press = true;
1137511317 Generate('continue', buildOrFillAdditionalArgs());
1137611318 }
11377- }
11319+ } else if (id == 'option_delete_mes') {
11378-
11379- else if (id == 'option_delete_mes') {
1138011320 setTimeout(() => openMessageDelete(fromSlashCommand), animation_duration);
11381- }
11321+ } else if (id == 'option_close_chat') {
11382-
11383- else if (id == 'option_close_chat') {
1138411322 await closeCurrentChat();
11385- }
11323+ } else if (id === 'option_settings') {
11386-
11387- else if (id === 'option_settings') {
1138811324 //var checkBox = document.getElementById("waifuMode");
1138911325 var topBar = document.getElementById('top-bar');
1139011326 var topSettingsHolder = document.getElementById('top-settings-holder');
public/scripts/RossAscends-mods.js+2 -4
@@ -379,8 +379,7 @@ function RA_autoconnect(PrevApi) {
379379 || (textgen_settings.type === textgen_types.FEATHERLESS && secret_state[SECRET_KEYS.FEATHERLESS])
380380 ) {
381381 $('#api_button_textgenerationwebui').trigger('click');
382- }
382+ } else if (isValidUrl(getTextGenServer())) {
383- else if (isValidUrl(getTextGenServer())) {
384383 $('#api_button_textgenerationwebui').trigger('click');
385384 }
386385 break;
@@ -1053,8 +1052,7 @@ export function initRossMods() {
10531052 $('#send_textarea').trigger('focus');
10541053 reasoningMesDone.trigger('click');
10551054 return;
1056- }
1055+ } else if (is_send_press == false) {
1057- else if (is_send_press == false) {
10581056 const skipConfirmKey = 'RegenerateWithCtrlEnter';
10591057 const skipConfirm = accountStorage.getItem(skipConfirmKey) === 'true';
10601058 function doRegenerate() {
public/scripts/authors-note.js+2 -4
@@ -231,11 +231,9 @@ function onExtensionFloatingCharaPromptInput() {
231231 !existingCharaNote.useChara
232232 ) {
233233 extension_settings.note.chara.splice(existingCharaNoteIndex, 1);
234- }
234+ } else if (extension_settings.note.chara && existingCharaNote) {
235- else if (extension_settings.note.chara && existingCharaNote) {
236235 Object.assign(existingCharaNote, tempCharaNote);
237- }
236+ } else if (avatarName && tempPrompt.length > 0) {
238- else if (avatarName && tempPrompt.length > 0) {
239237 if (!extension_settings.note.chara) {
240238 extension_settings.note.chara = [];
241239 }
public/scripts/bookmarks.js+4 -7
@@ -111,12 +111,10 @@ function getMainChatName() {
111111 if (chat_metadata) {
112112 if (chat_metadata.main_chat) {
113113 return chat_metadata.main_chat;
114- }
114+ } else if (selected_group) {
115115 // groups didn't support bookmarks before chat metadata was introduced
116- else if (selected_group) {
117116 return null;
118- }
117+ } else if (characters[this_chid].chat && characters[this_chid].chat.includes(bookmarkNameToken)) {
119- else if (characters[this_chid].chat && characters[this_chid].chat.includes(bookmarkNameToken)) {
120118 const tokenIndex = characters[this_chid].chat.lastIndexOf(bookmarkNameToken);
121119 chat_metadata.main_chat = characters[this_chid].chat.substring(0, tokenIndex).trim();
122120 return chat_metadata.main_chat;
@@ -146,8 +144,7 @@ export function showBookmarksButtons() {
146144 $('#option_back_to_main').hide();
147145 $('#option_new_bookmark').show();
148146 }
149147 } catch {
150- catch {
151148 $('#option_back_to_main').hide();
152149 $('#option_new_bookmark').hide();
153150 $('#option_convert_to_group').hide();
public/scripts/chats.js+3 -6
@@ -832,11 +832,9 @@ async function openExternalMediaOverridesDialog() {
832832
833833 if (power_user.external_media_allowed_overrides.includes(entityId)) {
834834 template.find('#forbid_media_override_allowed').prop('checked', true);
835- }
835+ } else if (power_user.external_media_forbidden_overrides.includes(entityId)) {
836- else if (power_user.external_media_forbidden_overrides.includes(entityId)) {
837836 template.find('#forbid_media_override_forbidden').prop('checked', true);
838837 } else {
839- else {
840838 template.find('#forbid_media_override_global').prop('checked', true);
841839 }
842840
@@ -1678,8 +1676,7 @@ async function runScraper(scraperId, target, callback) {
16781676
16791677 toastr.success(t`Scraped ${files.length} files from ${scraperId} to ${target}.`, t`Data Bank`);
16801678 callback();
1681- }
1679+ } catch (error) {
1682- catch (error) {
16831680 console.error('Scraping failed', error);
16841681 toastr.error(t`Check browser console for details.`, t`Scraping failed`);
16851682 }
public/scripts/dynamic-styles.js+1 -2
@@ -73,8 +73,7 @@ function applyDynamicFocusStyles(styleSheet, { fromExtension = false } = {}) {
7373 const isHover = selector.includes(':hover'), isFocus = selector.includes(':focus');
7474 if (isHover && isFocus) {
7575 // We currently do nothing here. Rules containing both hover and focus are very specific and should never be automatically touched
76- }
76+ } else if (isHover) {
77- else if (isHover) {
7877 const baseSelector = selector.replace(/:hover/g, PLACEHOLDER).trim();
7978 hoverRules.push({ baseSelector, rule, wrappers: [...wrappers] });
8079 } else if (isFocus) {
public/scripts/extensions.js+3 -6
@@ -278,12 +278,10 @@ async function discoverExtensions() {
278278 if (response.ok) {
279279 const extensions = await response.json();
280280 return extensions;
281281 } else {
282- else {
283282 return [];
284283 }
285- }
284+ } catch (err) {
286- catch (err) {
287285 console.error(err);
288286 return [];
289287 }
@@ -627,8 +625,7 @@ async function connectToApi(baseUrl) {
627625 }
628626
629627 updateStatus(getExtensionsResult.ok);
630628 } catch {
631- catch {
632629 updateStatus(false);
633630 }
634631}
public/scripts/extensions/assets/index.js+6 -12
@@ -82,8 +82,7 @@ function getAuthorFromUrl(url) {
8282 result.name = pathSegments[0];
8383 result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`;
8484 }
85- }
85+ } catch (error) {
86- catch (error) {
8786 console.debug(DEBUG_PREFIX, 'Error parsing URL:', error);
8887 }
8988
@@ -199,8 +198,7 @@ async function downloadAssetsList(url) {
199198 label.removeClass('fa-trash');
200199 label.removeClass('redOverlayGlow');
201200 });
202201 } else {
203- else {
204202 console.debug(DEBUG_PREFIX, 'not installed, unchecked');
205203 element.prop('checked', false);
206204 element.on('click', assetInstall);
@@ -346,8 +344,7 @@ async function installAsset(url, assetType, filename) {
346344 console.debug(DEBUG_PREFIX, 'Character downloaded.');
347345 }
348346 }
349- }
347+ } catch (err) {
350- catch (err) {
351348 console.log(err);
352349 return [];
353350 }
@@ -373,8 +370,7 @@ async function deleteAsset(assetType, filename) {
373370 if (result.ok) {
374371 console.debug(DEBUG_PREFIX, 'Deletion success.');
375372 }
376- }
373+ } catch (err) {
377- catch (err) {
378374 console.log(err);
379375 return [];
380376 }
@@ -427,8 +423,7 @@ async function updateCurrentAssets() {
427423 headers: getRequestHeaders({ omitContentType: true }),
428424 });
429425 currentAssets = result.ok ? (await result.json()) : {};
430- }
426+ } catch (err) {
431- catch (err) {
432427 console.log(err);
433428 }
434429 console.debug(DEBUG_PREFIX, 'Current assets found:', currentAssets);
@@ -490,8 +485,7 @@ jQuery(async () => {
490485 connectButton.addClass('fa-plug-circle-exclamation');
491486 connectButton.removeClass('redOverlayGlow');
492487 }
493488 } else {
494- else {
495489 console.debug(DEBUG_PREFIX, 'Connection refused by user');
496490 }
497491 });
public/scripts/extensions/caption/index.js+4 -8
@@ -68,8 +68,7 @@ async function setImageIcon() {
6868 const sendButton = $('#send_picture .extensionsMenuExtensionButton');
6969 sendButton.addClass('fa-image');
7070 sendButton.removeClass('fa-hourglass-half');
71- }
71+ } catch (error) {
72- catch (error) {
7372 console.log(error);
7473 }
7574}
@@ -82,8 +81,7 @@ async function setSpinnerIcon() {
8281 const sendButton = $('#send_picture .extensionsMenuExtensionButton');
8382 sendButton.removeClass('fa-image');
8483 sendButton.addClass('fa-hourglass-half');
85- }
84+ } catch (error) {
86- catch (error) {
8785 console.log(error);
8886 }
8987}
@@ -376,14 +374,12 @@ async function getCaptionForFile(file, prompt, quiet) {
376374 await sendCaptionedMessage(caption, imagePath, file.type);
377375 }
378376 return caption;
379- }
377+ } catch (error) {
380- catch (error) {
381378 const errorMessage = error.message || 'Unknown error';
382379 toastr.error(errorMessage, 'Failed to caption');
383380 console.error(error);
384381 return '';
385382 } finally {
386- finally {
387383 setImageIcon();
388384 }
389385}
public/scripts/extensions/expressions/index.js+15 -26
@@ -363,8 +363,7 @@ export async function visualNovelUpdateLayers(container) {
363363 if (power_user.reduced_motion) {
364364 element.css('left', currentPosition + 'px');
365365 requestAnimationFrame(() => resolve());
366366 } else {
367- else {
368367 element.animate({ left: currentPosition + 'px' }, 500, () => {
369368 resolve();
370369 });
@@ -525,8 +524,7 @@ async function moduleWorker({ newChat = false } = {}) {
525524 }
526525
527526 return;
528527 } else {
529- else {
530528 // force reload expressions list on connect to API
531529 if (offlineMode.is(':visible')) {
532530 expressionsList = null;
@@ -599,11 +597,9 @@ async function moduleWorker({ newChat = false } = {}) {
599597 }
600598
601599 await sendExpressionCall(spriteFolderName, expression, { force: force, vnMode: vnMode });
602- }
600+ } catch (error) {
603- catch (error) {
604601 console.log(error);
605602 } finally {
606- finally {
607603 inApiCall = false;
608604 lastCharacter = context.groupId || context.characterId;
609605 lastMessage = currentLastMessage.mes;
@@ -631,8 +627,7 @@ function getFolderNameByMessage(message) {
631627
632628 if (context.groupId) {
633629 avatarPath = message.original_avatar || context.characters.find(x => message.force_avatar && message.force_avatar.includes(encodeURIComponent(x.avatar)))?.avatar;
634- }
630+ } else if (context.characterId !== undefined) {
635- else if (context.characterId !== undefined) {
636631 avatarPath = getCharaFilename();
637632 }
638633
@@ -1303,8 +1298,7 @@ async function getSpritesList(name) {
13031298 }
13041299
13051300 return grouped;
1306- }
1301+ } catch (err) {
1307- catch (err) {
13081302 console.log(err);
13091303 return [];
13101304 }
@@ -1476,9 +1470,8 @@ function chooseSpriteForExpression(spriteFolderName, expression, { prevExpressio
14761470 const searched = sprite.files.find(x => x.fileName === overrideSpriteFile);
14771471 if (searched) spriteFile = searched;
14781472 else toastr.warning(t`Couldn't find sprite file ${overrideSpriteFile} for expression ${expression}.`, t`Sprite Not Found`);
1479- }
1473+ } else if (extension_settings.expressions.allowMultiple && sprite.files.length > 1) {
14801474 // Else calculate next expression, if multiple are allowed
1481- else if (extension_settings.expressions.allowMultiple && sprite.files.length > 1) {
14821475 let possibleFiles = sprite.files;
14831476 if (extension_settings.expressions.rerollIfSame) {
14841477 possibleFiles = possibleFiles.filter(x => !prevExpressionSrc || x.imageSrc !== prevExpressionSrc);
@@ -1593,8 +1586,7 @@ async function setExpression(spriteFolderName, expression, { force = false, over
15931586 }
15941587
15951588 console.info('Expression set', { expression: spriteFile.expression, file: spriteFile.fileName });
15961589 } else {
1597- else {
15981590 img.attr('data-sprite-folder-name', spriteFolderName);
15991591
16001592 img.off('error');
@@ -1844,19 +1836,16 @@ async function onClickExpressionUpload(event) {
18441836 const fileNameWithoutExtension = withoutExtension(file.name);
18451837 const validFileName = validateExpressionSpriteName(expression, fileNameWithoutExtension);
18461838
1847- // If there is no expression yet and it's a valid expression, we just take it
18481839 if (!clickedFileName && validFileName) {
1840+ // If there is no expression yet and it's a valid expression, we just take it
18491841 spriteName = fileNameWithoutExtension;
1850- }
1842+ } else if (clickedFileName === file.name) {
18511843 // If the filename matches the one that was clicked, we just take it and replace it
1852- else if (clickedFileName === file.name) {
18531844 spriteName = fileNameWithoutExtension;
1854- }
1845+ } else if (!matchesExisting && validFileName) {
18551846 // If it's a valid filename and there's no existing file with the same name, we just take it
1856- else if (!matchesExisting && validFileName) {
18571847 spriteName = fileNameWithoutExtension;
18581848 } else {
1859- else {
18601849 /** @type {import('../../popup.js').CustomPopupButton[]} */
18611850 const customButtons = [];
18621851 if (clickedFileName) {
public/scripts/extensions/memory/index.js+2 -4
@@ -881,11 +881,9 @@ async function summarizeChatExtras(context) {
881881 }
882882
883883 setMemoryContext(summary, true);
884- }
884+ } catch (error) {
885- catch (error) {
886885 console.log(error);
887886 } finally {
888- finally {
889887 inApiCall = false;
890888 }
891889}
public/scripts/extensions/quick-reply/src/QuickReply.js+1 -2
@@ -398,8 +398,7 @@ export class QuickReply {
398398 if (this.icon) {
399399 icon.classList.add('fa-solid');
400400 icon.classList.add(this.icon);
401401 } else {
402- else {
403402 icon.textContent = '…';
404403 }
405404 icon.addEventListener('click', async () => {
public/scripts/extensions/stable-diffusion/index.js+1 -2
@@ -3021,8 +3021,7 @@ async function generatePicture(initiator, args, trigger, message, callback) {
30213021 const errorText = 'SD prompt text generation failed. ' + reason;
30223022 toastr.error(errorText, 'Image Generation');
30233023 throw new Error(errorText);
30243024 } finally {
3025- finally {
30263025 $(stopButton).hide();
30273026 restoreOriginalDimensions(dimensions);
30283027 eventSource.removeListener(CUSTOM_STOP_EVENT, stopListener);
public/scripts/extensions/tts/coqui.js+4 -8
@@ -497,8 +497,7 @@ class CoquiTtsProvider {
497497 const language_label = JSON.stringify(model_settings.languages[i]).replaceAll('"', '');
498498 $('#coqui_api_model_settings_language').append(new Option(language_label, i));
499499 }
500500 } else {
501- else {
502501 $('#coqui_api_model_settings_language').hide();
503502 }
504503
@@ -516,8 +515,7 @@ class CoquiTtsProvider {
516515 const speaker_label = JSON.stringify(model_settings.speakers[i]).replaceAll('"', '');
517516 $('#coqui_api_model_settings_speaker').append(new Option(speaker_label, i));
518517 }
519518 } else {
520- else {
521519 $('#coqui_api_model_settings_speaker').hide();
522520 }
523521
@@ -536,15 +534,13 @@ class CoquiTtsProvider {
536534 if (model_state == 'installed') {
537535 $('#coqui_api_model_install_status').text('Model already installed on extras server');
538536 $('#coqui_api_model_install_button').hide();
539537 } else {
540- else {
541538 let action = 'download';
542539 if (model_state == 'corrupted') {
543540 action = 'repare';
544541 //toastr.error("Click install button to reinstall the model "+$("#coqui_api_model_name").find(":selected").text(), DEBUG_PREFIX+" corrupted model install", { timeOut: 10000, extendedTimeOut: 20000, preventDuplicates: true });
545542 $('#coqui_api_model_install_status').text('Model found but incomplete try install again (maybe still downloading)'); // (remove and download again)
546543 } else {
547- else {
548544 toastr.info('Click download button to install the model ' + $('#coqui_api_model_name').find(':selected').text(), DEBUG_PREFIX + ' model not installed', { timeOut: 10000, extendedTimeOut: 20000, preventDuplicates: true });
549545 $('#coqui_api_model_install_status').text('Model not found on extras server');
550546 }
public/scripts/extensions/tts/index.js+2 -4
@@ -346,8 +346,7 @@ globalThis.tts_preview = function (id) {
346346
347347 if (audio instanceof HTMLAudioElement && !$(audio).data('disabled')) {
348348 audio.play();
349349 } else {
350- else {
351350 ttsProvider.previewTtsVoice(id);
352351 }
353352};
@@ -1452,8 +1451,7 @@ async function initVoiceMapInternal(unrestricted) {
14521451 let voiceIdsFromProvider;
14531452 try {
14541453 voiceIdsFromProvider = await ttsProvider.fetchTtsVoiceObjects();
14551454 } catch {
1456- catch {
14571455 toastr.error('TTS Provider failed to return voice ids.');
14581456 }
14591457
public/scripts/extensions/tts/system.js+1 -2
@@ -29,8 +29,7 @@ var speechUtteranceChunker = function (utt, settings, callback) {
2929 callback();
3030 }
3131 });
3232 } else {
33- else {
3433 var chunkLength = (settings && settings.chunkLength) || 160;
3534 var pattRegex = new RegExp('^[\\s\\S]{' + Math.floor(chunkLength / 2) + ',' + chunkLength + '}[.!?,]{1}|^[\\s\\S]{1,' + chunkLength + '}$|^[\\s\\S]{1,' + chunkLength + '} ');
3635 var chunkArr = txt.match(pattRegex);
public/scripts/extensions/tts/vits.js+2 -4
@@ -325,8 +325,7 @@ class VITSTtsProvider {
325325 if (streaming) {
326326 params.append('streaming', streaming);
327327 // Streaming response only supports MP3
328328 } else {
329- else {
330329 params.append('format', this.settings.format);
331330 }
332331 params.append('lang', lang ?? this.settings.lang);
@@ -337,8 +336,7 @@ class VITSTtsProvider {
337336
338337 if (model_type == this.modelTypes.W2V2_VITS) {
339338 params.append('emotion', this.settings.dim_emotion);
340- }
339+ } else if (model_type == this.modelTypes.BERT_VITS2) {
341- else if (model_type == this.modelTypes.BERT_VITS2) {
342340 params.append('sdp_ratio', this.settings.sdp_ratio);
343341 params.append('emotion', this.settings.emotion);
344342 if (this.settings.text_prompt) {
public/scripts/extensions/vectors/index.js+2 -4
@@ -251,8 +251,7 @@ async function summarizeExtra(element) {
251251 const data = await apiResult.json();
252252 element.text = data.summary;
253253 }
254- }
254+ } catch (error) {
255- catch (error) {
256255 console.log(error);
257256 return false;
258257 }
@@ -938,8 +937,7 @@ function throwIfSourceInvalid() {
938937 if (!settings.alt_endpoint_url) {
939938 throw new Error('Vectors: API URL missing', { cause: 'api_url_missing' });
940939 }
941940 } else {
942- else {
943941 if (settings.source === 'ollama' && !textgenerationwebui_settings.server_urls[textgen_types.OLLAMA] ||
944942 settings.source === 'vllm' && !textgenerationwebui_settings.server_urls[textgen_types.VLLM] ||
945943 settings.source === 'koboldcpp' && !textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP] ||
public/scripts/filters.js+1 -2
@@ -328,8 +328,7 @@ export class FilterHelper {
328328 // We can filter easily by checking if we have saved a score
329329 const score = _this.getScore(FILTER_TYPES.SEARCH, `${entity.type}.${entity.id}`);
330330 return score !== undefined;
331331 } else {
332- else {
333332 // Compare insensitive and without accents
334333 return includesIgnoreCaseAndAccents(entity.item?.name, searchValue);
335334 }
public/scripts/group-chats.js+13 -25
@@ -173,9 +173,8 @@ async function regenerateGroup() {
173173 // for new generations after the update
174174 if ((generationId && this_generationId) && generationId !== this_generationId) {
175175 break;
176- }
176+ } else if (lastMes.is_user || lastMes.is_system) {
177177 // legacy for generations before the update
178- else if (lastMes.is_user || lastMes.is_system) {
179178 break;
180179 }
181180
@@ -392,8 +391,7 @@ export function findGroupMemberId(arg, full = false) {
392391 console.log(`Targeting group member ${chid} (${arg}) from search result`, result[0]);
393392
394393 return !full ? chid : { ...{ id: chid }, ...result[0].item };
395394 } else {
396- else {
397395 const memberAvatar = group.members[index];
398396
399397 if (memberAvatar === undefined) {
@@ -744,8 +742,7 @@ export async function renameGroupMember(oldAvatar, newAvatar, newName) {
744742 }
745743 }
746744 }
747- }
745+ } catch (error) {
748- catch (error) {
749746 console.log(`An error during renaming the character ${newName} in group: ${group.name}`);
750747 console.error(error);
751748 }
@@ -1011,28 +1008,22 @@ async function generateGroupWrapper(byAutoMode, type = null, params = {}) {
10111008 if (activatedMembers.length === 0) {
10121009 activatedMembers = activateListOrder(group.members.slice(0, 1));
10131010 }
1014- }
1011+ } else if (type === 'swipe' || type === 'continue') {
1015- else if (type === 'swipe' || type === 'continue') {
10161012 activatedMembers = activateSwipe(group.members, { allowSystem: false });
10171013
10181014 if (activatedMembers.length === 0) {
10191015 toastr.warning(t`Deleted group member swiped. To get a reply, add them back to the group.`);
10201016 throw new Error('Deleted group member swiped');
10211017 }
1022- }
1018+ } else if (type === 'impersonate') {
1023- else if (type === 'impersonate') {
10241019 activatedMembers = activateImpersonate(group.members);
1025- }
1020+ } else if (activationStrategy === group_activation_strategy.NATURAL) {
1026- else if (activationStrategy === group_activation_strategy.NATURAL) {
10271021 activatedMembers = activateNaturalOrder(enabledMembers, activationText, lastMessage, group.allow_self_responses, isUserInput);
1028- }
1022+ } else if (activationStrategy === group_activation_strategy.LIST) {
1029- else if (activationStrategy === group_activation_strategy.LIST) {
10301023 activatedMembers = activateListOrder(enabledMembers);
1031- }
1024+ } else if (activationStrategy === group_activation_strategy.POOLED) {
1032- else if (activationStrategy === group_activation_strategy.POOLED) {
10331025 activatedMembers = activatePooledOrder(enabledMembers, lastMessage, isUserInput);
1034- }
1026+ } else if (activationStrategy === group_activation_strategy.MANUAL && !isUserInput) {
1035- else if (activationStrategy === group_activation_strategy.MANUAL && !isUserInput) {
10361027 activatedMembers = shuffle(enabledMembers).slice(0, 1).map(x => characters.findIndex(y => y.avatar === x)).filter(x => x !== -1);
10371028 }
10381029
@@ -1168,8 +1159,7 @@ function activateSwipe(members, { allowSystem = false } = {}) {
11681159 break;
11691160 }
11701161 }
11711162 } else {
1172- else {
11731163 activatedNames.push(lastMessage.original_avatar);
11741164 }
11751165
@@ -1704,8 +1694,7 @@ function getGroupCharacterBlock(character) {
17041694 const auxFieldValue = (character.data && character.data[auxFieldName]) || '';
17051695 if (auxFieldValue) {
17061696 template.find('.character_version').text(auxFieldValue);
17071697 } else {
1708- else {
17091698 template.find('.character_version').hide();
17101699 }
17111700
@@ -1875,8 +1864,7 @@ function select_group_chats(groupId, skipAnimation) {
18751864 if (group) {
18761865 $('#rm_group_automode_label').show();
18771866 $('#rm_button_selected_ch').children('h2').text(groupName);
18781867 } else {
1879- else {
18801868 $('#rm_group_automode_label').hide();
18811869 }
18821870
public/scripts/horde.js+1 -2
@@ -126,8 +126,7 @@ export async function getStatusHorde() {
126126 try {
127127 const hordeStatus = await checkHordeStatus();
128128 setOnlineStatus(hordeStatus ? t`Connected` : 'no_connection');
129129 } catch {
130- catch {
131130 setOnlineStatus('no_connection');
132131 }
133132
public/scripts/kai-settings.js+1 -2
@@ -220,8 +220,7 @@ function tryParseStreamingError(response, decoded) {
220220 toastr.error(data.error.message || response.statusText, 'KoboldAI API');
221221 throw new Error(data);
222222 }
223223 } catch {
224- catch {
225224 // No JSON. Do nothing.
226225 }
227226}
public/scripts/logit-bias.js+4 -10
@@ -117,11 +117,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
117117 if (text.startsWith('{') && text.endsWith('}')) {
118118 const tokens = getTextTokens(tokenizerType, text.slice(1, -1));
119119 result.push(getBiasObject(entry.value, tokens));
120- }
120+ } else if (text.startsWith('[') && text.endsWith(']')) {
121-
121+ // Raw token ids, JSON serialized
122-
123- // Raw token ids, JSON serialized
124- else if (text.startsWith('[') && text.endsWith(']')) {
125122 try {
126123 const tokens = JSON.parse(text);
127124
@@ -133,11 +130,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
133130 } catch (err) {
134131 console.log(`Failed to parse logit bias token list: ${text}`, err);
135132 }
136133 } else {
137-
134+ // Text with a leading space
138-
139- // Text with a leading space
140- else {
141135 const biasText = ` ${text}`;
142136 const tokens = getTextTokens(tokenizerType, biasText);
143137 result.push(getBiasObject(entry.value, tokens));
public/scripts/macros/engine/MacroCstWalker.js+2 -3
@@ -1001,9 +1001,8 @@ class MacroCstWalker {
10011001 endOffset: element.endOffset ?? element.startOffset,
10021002 token: element,
10031003 });
1004- }
1004+ } else if ('children' in element) {
10051005 // Handle nested CstNode (macro or argument)
1006- else if ('children' in element) {
10071006 const nestedChildren = element.children || {};
10081007 const nestedEnd = /** @type {IToken?} */ ((nestedChildren['Macro.End'] || [])[0]);
10091008 const nestedStart = /** @type {IToken?} */ ((nestedChildren['Macro.Start'] || [])[0]);
public/scripts/nai-settings.js+6 -12
@@ -180,8 +180,7 @@ export function loadNovelPreset(preset) {
180180 $('#amount_gen').val(preset.max_length).trigger('input');
181181 $('#max_context_unlocked').prop('checked', needsUnlock).trigger('change');
182182 $('#max_context').val(preset.max_context).trigger('input');
183183 } else {
184- else {
185184 setGenerationParamsFromPreset(preset);
186185 }
187186
@@ -459,10 +458,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
459458 if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
460459 const tokens = getTextTokens(tokenizerType, trimmed.slice(1, -1));
461460 result.push(tokens);
462- }
461+ } else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
463-
462+ // Raw token ids, JSON serialized
464- // Raw token ids, JSON serialized
465- else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
466463 try {
467464 const tokens = JSON.parse(trimmed);
468465
@@ -474,10 +471,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
474471 } catch (err) {
475472 console.log(`Failed to parse bad word token list: ${trimmed}`, err);
476473 }
477474 } else {
478-
475+ // Apply permutations
479- // Apply permutations
480- else {
481476 const permutations = getBadWordPermutations(trimmed).map(t => getTextTokens(tokenizerType, t));
482477 result.push(...permutations);
483478 }
@@ -738,8 +733,7 @@ function tryParseStreamingError(response, decoded) {
738733 toastr.error(data.message || data.error?.message || response.statusText, 'NovelAI API');
739734 throw new Error(data);
740735 }
741736 } catch {
742- catch {
743737 // No JSON. Do nothing.
744738 }
745739}
public/scripts/openai.js+61 -122
@@ -495,8 +495,7 @@ async function validateReverseProxy() {
495495
496496 try {
497497 new URL(oai_settings.reverse_proxy);
498- }
498+ } catch (err) {
499- catch (err) {
500499 toastr.error(t`Entered reverse proxy address is not a valid URL`);
501500 setOnlineStatus('no_connection');
502501 resultCheckStatus();
@@ -1551,8 +1550,7 @@ export function tryParseStreamingError(response, decoded, { quiet = false } = {}
15511550 !quiet && toastr.error(data.detail?.error?.message || response.statusText, 'Chat Completion API');
15521551 throw new Error(data);
15531552 }
15541553 } catch {
1555- catch {
15561554 // No JSON. Do nothing.
15571555 }
15581556}
@@ -2868,8 +2866,7 @@ async function sendOpenAIRequest(type, messages, signal, { jsonSchema = null } =
28682866 yield { text, swipes: swipes, logprobs: parseChatCompletionLogprobs(parsed), toolCalls: toolCalls, state: state };
28692867 }
28702868 };
28712869 } else {
2872- else {
28732870 const data = await response.json();
28742871
28752872 checkQuotaError(data);
@@ -3081,8 +3078,7 @@ async function calculateLogitBias() {
30813078 });
30823079
30833080 result = await reply.json();
3084- }
3081+ } catch (err) {
3085- catch (err) {
30863082 result = {};
30873083 console.error(err);
30883084 }
@@ -3602,13 +3598,11 @@ export class ChatCompletion {
36023598 if (lastMessage && shouldSquash(lastMessage)) {
36033599 lastMessage.content += '\n' + message.content;
36043600 lastMessage.tokens = await tokenHandler.countAsync({ role: lastMessage.role, content: lastMessage.content });
36053601 } else {
3606- else {
36073602 squashedMessages.push(message);
36083603 lastMessage = message;
36093604 }
36103605 } else {
3611- else {
36123606 squashedMessages.push(message);
36133607 lastMessage = message;
36143608 }
@@ -4242,8 +4236,7 @@ async function saveOpenAIPreset(name, settings, triggerUi = true) {
42424236 Object.assign(openai_settings[value], presetBody);
42434237 $(`#settings_preset_openai option[value="${value}"]`).prop('selected', true);
42444238 if (triggerUi) $('#settings_preset_openai').trigger('change');
42454239 } else {
4246- else {
42474240 openai_settings.push(presetBody);
42484241 openai_setting_names[data.name] = openai_settings.length - 1;
42494242 const option = document.createElement('option');
@@ -4692,47 +4685,33 @@ function onSettingsPresetChange() {
46924685function getMaxContextOpenAI(value) {
46934686 if (oai_settings.max_context_unlocked) {
46944687 return unlocked_max;
4695- }
4688+ } else if (value.startsWith('gpt-5')) {
4696- else if (value.startsWith('gpt-5')) {
46974689 return max_400k;
4698- }
4690+ } else if (value.includes('gpt-4.1')) {
4699- else if (value.includes('gpt-4.1')) {
47004691 return max_1mil;
4701- }
4692+ } else if (value.includes('gpt-audio')) {
4702- else if (value.includes('gpt-audio')) {
47034693 return max_128k;
4704- }
4694+ } else if (value.startsWith('o1')) {
4705- else if (value.startsWith('o1')) {
47064695 return max_128k;
4707- }
4696+ } else if (value.startsWith('o4') || value.startsWith('o3')) {
4708- else if (value.startsWith('o4') || value.startsWith('o3')) {
47094697 return max_200k;
4710- }
4698+ } else if (value.includes('chatgpt-4o-latest') || value.includes('gpt-4-turbo') || value.includes('gpt-4o') || value.includes('gpt-4-1106') || value.includes('gpt-4-0125') || value.includes('gpt-4-vision')) {
4711- else if (value.includes('chatgpt-4o-latest') || value.includes('gpt-4-turbo') || value.includes('gpt-4o') || value.includes('gpt-4-1106') || value.includes('gpt-4-0125') || value.includes('gpt-4-vision')) {
47124699 return max_128k;
4713- }
4700+ } else if (value.includes('gpt-3.5-turbo-1106')) {
4714- else if (value.includes('gpt-3.5-turbo-1106')) {
47154701 return max_16k;
4716- }
4702+ } else if (['gpt-4', 'gpt-4-0314', 'gpt-4-0613'].includes(value)) {
4717- else if (['gpt-4', 'gpt-4-0314', 'gpt-4-0613'].includes(value)) {
47184703 return max_8k;
4719- }
4704+ } else if (['gpt-4-32k', 'gpt-4-32k-0314', 'gpt-4-32k-0613'].includes(value)) {
4720- else if (['gpt-4-32k', 'gpt-4-32k-0314', 'gpt-4-32k-0613'].includes(value)) {
47214705 return max_32k;
4722- }
4706+ } else if (value.includes('gpt-realtime')) {
4723- else if (value.includes('gpt-realtime')) {
47244707 return max_32k;
4725- }
4708+ } else if (['gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613'].includes(value)) {
4726- else if (['gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613'].includes(value)) {
47274709 return max_16k;
4728- }
4710+ } else if (value == 'code-davinci-002') {
4729- else if (value == 'code-davinci-002') {
47304711 return max_8k;
4731- }
4712+ } else if (['text-curie-001', 'text-babbage-001', 'text-ada-001'].includes(value)) {
4732- else if (['text-curie-001', 'text-babbage-001', 'text-ada-001'].includes(value)) {
47334713 return max_2k;
47344714 } else {
4735- else {
47364715 // default to gpt-3 (4095 tokens)
47374716 return max_4k;
47384717 }
@@ -5269,8 +5248,7 @@ async function onModelChange() {
52695248 if (value && (value.includes('claude') || value.includes('palm-2'))) {
52705249 oai_settings.temp_openai = Math.min(claude_max_temp, oai_settings.temp_openai);
52715250 $('#temp_openai').attr('max', claude_max_temp).val(oai_settings.temp_openai).trigger('input');
52725251 } else {
5273- else {
52745252 oai_settings.temp_openai = Math.min(oai_max_temp, oai_settings.temp_openai);
52755253 $('#temp_openai').attr('max', oai_max_temp).val(oai_settings.temp_openai).trigger('input');
52765254 }
@@ -5281,17 +5259,13 @@ async function onModelChange() {
52815259 if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
52825260 if (oai_settings.max_context_unlocked) {
52835261 $('#openai_max_context').attr('max', unlocked_max);
5284- }
5262+ } else if (value.startsWith('claude-sonnet-4-5') || value.startsWith('claude-opus-4-6')) {
5285- else if (value.startsWith('claude-sonnet-4-5') || value.startsWith('claude-opus-4-6')) {
52865263 $('#openai_max_context').attr('max', max_1mil);
5287- }
5264+ } else if (value == 'claude-2.1' || value.startsWith('claude-3') || value.startsWith('claude-opus') || value.startsWith('claude-haiku') || value.startsWith('claude-sonnet')) {
5288- else if (value == 'claude-2.1' || value.startsWith('claude-3') || value.startsWith('claude-opus') || value.startsWith('claude-haiku') || value.startsWith('claude-sonnet')) {
52895265 $('#openai_max_context').attr('max', max_200k);
5290- }
5266+ } else if (value.endsWith('100k') || value.startsWith('claude-2') || value === 'claude-instant-1.2') {
5291- else if (value.endsWith('100k') || value.startsWith('claude-2') || value === 'claude-instant-1.2') {
52925267 $('#openai_max_context').attr('max', claude_100k_max);
52935268 } else {
5294- else {
52955269 $('#openai_max_context').attr('max', claude_max);
52965270 }
52975271
@@ -5327,23 +5301,17 @@ async function onModelChange() {
53275301 if (oai_settings.chat_completion_source === chat_completion_sources.COHERE) {
53285302 if (oai_settings.max_context_unlocked) {
53295303 $('#openai_max_context').attr('max', unlocked_max);
5330- }
5304+ } else if (['command-light-nightly', 'command-light', 'command'].includes(oai_settings.cohere_model)) {
5331- else if (['command-light-nightly', 'command-light', 'command'].includes(oai_settings.cohere_model)) {
53325305 $('#openai_max_context').attr('max', max_4k);
5333- }
5306+ } else if (oai_settings.cohere_model.includes('command-r') || ['c4ai-aya-23', 'c4ai-aya-expanse-32b', 'command-nightly', 'command-a-vision-07-2025'].includes(oai_settings.cohere_model)) {
5334- else if (oai_settings.cohere_model.includes('command-r') || ['c4ai-aya-23', 'c4ai-aya-expanse-32b', 'command-nightly', 'command-a-vision-07-2025'].includes(oai_settings.cohere_model)) {
53355307 $('#openai_max_context').attr('max', max_128k);
5336- }
5308+ } else if (['command-a-03-2025'].includes(oai_settings.cohere_model)) {
5337- else if (['command-a-03-2025'].includes(oai_settings.cohere_model)) {
53385309 $('#openai_max_context').attr('max', max_256k);
5339- }
5310+ } else if (['c4ai-aya-23-8b', 'c4ai-aya-expanse-8b'].includes(oai_settings.cohere_model)) {
5340- else if (['c4ai-aya-23-8b', 'c4ai-aya-expanse-8b'].includes(oai_settings.cohere_model)) {
53415311 $('#openai_max_context').attr('max', max_8k);
5342- }
5312+ } else if (['c4ai-aya-vision-8b', 'c4ai-aya-vision-32b'].includes(oai_settings.cohere_model)) {
5343- else if (['c4ai-aya-vision-8b', 'c4ai-aya-vision-32b'].includes(oai_settings.cohere_model)) {
53445313 $('#openai_max_context').attr('max', max_16k);
53455314 } else {
5346- else {
53475315 $('#openai_max_context').attr('max', max_4k);
53485316 }
53495317 oai_settings.openai_max_context = Math.min(Number($('#openai_max_context').attr('max')), oai_settings.openai_max_context);
@@ -5354,19 +5322,15 @@ async function onModelChange() {
53545322 if (oai_settings.chat_completion_source === chat_completion_sources.PERPLEXITY) {
53555323 if (oai_settings.max_context_unlocked) {
53565324 $('#openai_max_context').attr('max', unlocked_max);
5357- }
5325+ } else if (['sonar', 'sonar-reasoning', 'sonar-reasoning-pro', 'r1-1776'].includes(oai_settings.perplexity_model)) {
5358- else if (['sonar', 'sonar-reasoning', 'sonar-reasoning-pro', 'r1-1776'].includes(oai_settings.perplexity_model)) {
53595326 $('#openai_max_context').attr('max', 127000);
5360- }
5327+ } else if (['sonar-pro'].includes(oai_settings.perplexity_model)) {
5361- else if (['sonar-pro'].includes(oai_settings.perplexity_model)) {
53625328 $('#openai_max_context').attr('max', 200000);
5363- }
5329+ } else if (oai_settings.perplexity_model.includes('llama-3.1')) {
5364- else if (oai_settings.perplexity_model.includes('llama-3.1')) {
53655330 const isOnline = oai_settings.perplexity_model.includes('online');
53665331 const contextSize = isOnline ? 128 * 1024 - 4000 : 128 * 1024;
53675332 $('#openai_max_context').attr('max', contextSize);
53685333 } else {
5369- else {
53705334 $('#openai_max_context').attr('max', max_128k);
53715335 }
53725336 oai_settings.openai_max_context = Math.min(Number($('#openai_max_context').attr('max')), oai_settings.openai_max_context);
@@ -5660,81 +5624,57 @@ async function onConnectButtonClick(e) {
56605624function toggleChatCompletionForms() {
56615625 if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
56625626 $('#model_claude_select').trigger('change');
5663- }
5627+ } else if (oai_settings.chat_completion_source == chat_completion_sources.OPENAI) {
5664- else if (oai_settings.chat_completion_source == chat_completion_sources.OPENAI) {
56655628 if (oai_settings.show_external_models && (!Array.isArray(model_list) || model_list.length == 0)) {
56665629 // Wait until the models list is loaded so that we could show a proper saved model
56675630 } else {
5668- else {
56695631 $('#model_openai_select').trigger('change');
56705632 }
5671- }
5633+ } else if (oai_settings.chat_completion_source == chat_completion_sources.MAKERSUITE) {
5672- else if (oai_settings.chat_completion_source == chat_completion_sources.MAKERSUITE) {
56735634 $('#model_google_select').trigger('change');
5674- }
5635+ } else if (oai_settings.chat_completion_source == chat_completion_sources.VERTEXAI) {
5675- else if (oai_settings.chat_completion_source == chat_completion_sources.VERTEXAI) {
56765636 $('#model_vertexai_select').trigger('change');
56775637 // Update UI based on authentication mode
56785638 onVertexAIAuthModeChange.call($('#vertexai_auth_mode')[0]);
5679- }
5639+ } else if (oai_settings.chat_completion_source == chat_completion_sources.OPENROUTER) {
5680- else if (oai_settings.chat_completion_source == chat_completion_sources.OPENROUTER) {
56815640 $('#model_openrouter_select').trigger('change');
5682- }
5641+ } else if (oai_settings.chat_completion_source == chat_completion_sources.AI21) {
5683- else if (oai_settings.chat_completion_source == chat_completion_sources.AI21) {
56845642 $('#model_ai21_select').trigger('change');
5685- }
5643+ } else if (oai_settings.chat_completion_source == chat_completion_sources.MISTRALAI) {
5686- else if (oai_settings.chat_completion_source == chat_completion_sources.MISTRALAI) {
56875644 $('#model_mistralai_select').trigger('change');
5688- }
5645+ } else if (oai_settings.chat_completion_source == chat_completion_sources.COHERE) {
5689- else if (oai_settings.chat_completion_source == chat_completion_sources.COHERE) {
56905646 $('#model_cohere_select').trigger('change');
5691- }
5647+ } else if (oai_settings.chat_completion_source == chat_completion_sources.PERPLEXITY) {
5692- else if (oai_settings.chat_completion_source == chat_completion_sources.PERPLEXITY) {
56935648 $('#model_perplexity_select').trigger('change');
5694- }
5649+ } else if (oai_settings.chat_completion_source == chat_completion_sources.GROQ) {
5695- else if (oai_settings.chat_completion_source == chat_completion_sources.GROQ) {
56965650 $('#model_groq_select').trigger('change');
5697- }
5651+ } else if (oai_settings.chat_completion_source == chat_completion_sources.CHUTES) {
5698- else if (oai_settings.chat_completion_source == chat_completion_sources.CHUTES) {
56995652 $('#model_chutes_select').trigger('change');
5700- }
5653+ } else if (oai_settings.chat_completion_source == chat_completion_sources.SILICONFLOW) {
5701- else if (oai_settings.chat_completion_source == chat_completion_sources.SILICONFLOW) {
57025654 $('#model_siliconflow_select').trigger('change');
5703- }
5655+ } else if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB) {
5704- else if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB) {
57055656 $('#model_electronhub_select').trigger('change');
5706- }
5657+ } else if (oai_settings.chat_completion_source == chat_completion_sources.NANOGPT) {
5707- else if (oai_settings.chat_completion_source == chat_completion_sources.NANOGPT) {
57085658 $('#model_nanogpt_select').trigger('change');
5709- }
5659+ } else if (oai_settings.chat_completion_source == chat_completion_sources.CUSTOM) {
5710- else if (oai_settings.chat_completion_source == chat_completion_sources.CUSTOM) {
57115660 $('#model_custom_select').trigger('change');
5712- }
5661+ } else if (oai_settings.chat_completion_source == chat_completion_sources.DEEPSEEK) {
5713- else if (oai_settings.chat_completion_source == chat_completion_sources.DEEPSEEK) {
57145662 $('#model_deepseek_select').trigger('change');
5715- }
5663+ } else if (oai_settings.chat_completion_source == chat_completion_sources.AIMLAPI) {
5716- else if (oai_settings.chat_completion_source == chat_completion_sources.AIMLAPI) {
57175664 $('#model_aimlapi_select').trigger('change');
5718- }
5665+ } else if (oai_settings.chat_completion_source == chat_completion_sources.XAI) {
5719- else if (oai_settings.chat_completion_source == chat_completion_sources.XAI) {
57205666 $('#model_xai_select').trigger('change');
5721- }
5667+ } else if (oai_settings.chat_completion_source == chat_completion_sources.POLLINATIONS) {
5722- else if (oai_settings.chat_completion_source == chat_completion_sources.POLLINATIONS) {
57235668 $('#model_pollinations_select').trigger('change');
5724- }
5669+ } else if (oai_settings.chat_completion_source == chat_completion_sources.MOONSHOT) {
5725- else if (oai_settings.chat_completion_source == chat_completion_sources.MOONSHOT) {
57265670 $('#model_moonshot_select').trigger('change');
5727- }
5671+ } else if (oai_settings.chat_completion_source == chat_completion_sources.FIREWORKS) {
5728- else if (oai_settings.chat_completion_source == chat_completion_sources.FIREWORKS) {
57295672 $('#model_fireworks_select').trigger('change');
5730- }
5673+ } else if (oai_settings.chat_completion_source == chat_completion_sources.COMETAPI) {
5731- else if (oai_settings.chat_completion_source == chat_completion_sources.COMETAPI) {
57325674 $('#model_cometapi_select').trigger('change');
5733- }
5675+ } else if (oai_settings.chat_completion_source == chat_completion_sources.AZURE_OPENAI) {
5734- else if (oai_settings.chat_completion_source == chat_completion_sources.AZURE_OPENAI) {
57355676 $('#azure_openai_model').trigger('change');
5736- }
5677+ } else if (oai_settings.chat_completion_source == chat_completion_sources.ZAI) {
5737- else if (oai_settings.chat_completion_source == chat_completion_sources.ZAI) {
57385678 $('#model_zai_select').trigger('change');
57395679 }
57405680
@@ -5757,8 +5697,7 @@ async function testApiConnection() {
57575697 const reply = await sendOpenAIRequest('quiet', [{ 'role': 'user', 'content': 'Hi' }], new AbortController().signal);
57585698 console.log(reply);
57595699 toastr.success(t`API connection successful!`);
5760- }
5700+ } catch (err) {
5761- catch (err) {
57625701 toastr.error(t`Could not get a reply from API. Check your connection settings / API key and try again.`);
57635702 }
57645703}
public/scripts/personas.js+2 -3
@@ -1552,9 +1552,8 @@ async function loadPersonaForCurrentChat({ doRender = false } = {}) {
15521552 }
15531553 toastr.success(message, t`Persona Auto Selected`, { escapeHtml: false });
15541554 }
1555- }
1555+ } else if (chatPersona && power_user.persona_auto_lock && !chat_metadata.persona) {
15561556 // Even if it's the same persona, we still might need to auto-lock to chat if that's enabled
1557- else if (chatPersona && power_user.persona_auto_lock && !chat_metadata.persona) {
15581557 await lockPersona('chat');
15591558 }
15601559
public/scripts/power-user.js+18 -30
@@ -810,9 +810,8 @@ async function CreateZenSliders(elmnt) {
810810 handle.text(handleText)
811811 .css('margin-left', `${leftMargin}px`);
812812 //console.log(`${newSlider.attr('id')} initial value:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)
813- }
813+ } else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
814814 //handling creation of rep_pen_range for ooba
815- else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
816815 if ($('#rep_pen_range_textgenerationwebui_zensliders').length !== 0) {
817816 $('#rep_pen_range_textgenerationwebui_zensliders').remove();
818817 }
@@ -821,22 +820,19 @@ async function CreateZenSliders(elmnt) {
821820 leftMargin = ((stepNumber) / numSteps) * 50 * -1;
822821 if (sliderValue === offVal) {
823822 handleText = 'Off';
824823 handle.css('color', 'rgba(128,128,128,0.5)');
825- }
824+ } else if (sliderValue === allVal) { handleText = 'All'; } else { handle.css('color', ''); }
826- else if (sliderValue === allVal) { handleText = 'All'; }
827- else { handle.css('color', ''); }
828825 handle.text(handleText)
829826 .css('margin-left', `${leftMargin}px`);
830827 //console.log(sliderValue, handleText, offVal, allVal)
831828 //console.log(`${newSlider.attr('id')} sliderValue = ${sliderValue}, handleText:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)
832829 originalSlider.val(steps[sliderValue]);
833830 } else {
834831 //create all other sliders
835- else {
836832 var numVal = Number(sliderValue).toFixed(decimals);
837833 offVal = Number(offVal).toFixed(decimals);
838834 if (numVal === offVal) {
839835 handle.text('Off').css('color', 'rgba(128,128,128,0.5)');
840836 } else {
841837 handle.text(numVal).css('color', '');
842838 }
@@ -928,29 +924,24 @@ async function CreateZenSliders(elmnt) {
928924 width: ${newSlider.width()}
929925 percent of max: ${percentOfMax}
930926 left: ${leftPos}`) */
931- //special handling for response length slider, pulls text aliases for step values from an array
932927 if (newSlider.attr('id') == 'amount_gen_zenslider') {
928+ //special handling for response length slider, pulls text aliases for step values from an array
933929 handleText = steps[stepNumber];
934930 handle.text(handleText);
935931 newSlider.val(stepNumber);
936932 numVal = steps[stepNumber];
937- }
933+ } else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
938934 //special handling for TextCompletion rep pen range slider, pulls text aliases for step values from an array
939- else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
940935 handleText = steps[stepNumber];
941936 handle.text(handleText);
942937 newSlider.val(stepNumber);
943938 if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5)'); } else if (numVal === allVal) { handle.text('All'); } else { handle.css('color', ''); }
944- else if (numVal === allVal) { handle.text('All'); }
945- else { handle.css('color', ''); }
946939 numVal = steps[stepNumber];
947940 } else {
948941 //everything else uses the flat slider value
949942 //also note: the above sliders are not custom inputtable due to the array aliasing
950- else {
951943 //show 'off' if disabled value is set
952944 if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5)'); } else { handle.text(ui.value.toFixed(decimals)).css('color', ''); }
953- else { handle.text(ui.value.toFixed(decimals)).css('color', ''); }
954945 newSlider.val(handleText);
955946 }
956947 //for manually typed-in values we must adjust left position because JQUI doesn't do it for us
@@ -991,8 +982,7 @@ function switchSpoilerMode() {
991982 $('#firstMessageWrapper').hide();
992983 $('#spoiler_free_desc').addClass('flex1');
993984 $('#creators_note_desc_hidden').show();
994985 } else {
995- else {
996986 $('#descriptionWrapper').show();
997987 $('#firstMessageWrapper').show();
998988 $('#spoiler_free_desc').removeClass('flex1');
@@ -2524,8 +2514,7 @@ async function saveTheme(name = undefined, theme = undefined) {
25242514 option.value = name;
25252515 option.innerText = name;
25262516 $('#themes').append(option);
25272517 } else {
2528- else {
25292518 themes[themeIndex] = theme;
25302519 $(`#themes option[value="${name}"]`).prop('selected', true);
25312520 }
@@ -2632,8 +2621,7 @@ async function saveMovingUI() {
26322621 option.value = name;
26332622 option.innerText = name;
26342623 $('#movingUIPresets').append(option);
26352624 } else {
2636- else {
26372625 movingUIPresets[movingUIPresetIndex] = movingUIPreset;
26382626 $(`#movingUIPresets option[value="${name}"]`).prop('selected', true);
26392627 }
public/scripts/preset-manager.js+2 -4
@@ -608,15 +608,13 @@ class PresetManager {
608608 presets[preset_names.indexOf(name)] = preset;
609609 $(this.select).find(`option[value="${name}"]`).prop('selected', true);
610610 $(this.select).val(name).trigger('change');
611611 } else {
612- else {
613612 const value = preset_names[name];
614613 presets[value] = preset;
615614 $(this.select).find(`option[value="${value}"]`).prop('selected', true);
616615 $(this.select).val(value).trigger('change');
617616 }
618617 } else {
619- else {
620618 presets.push(preset);
621619 const value = presets.length - 1;
622620
public/scripts/samplerSelect.js+1 -3
@@ -246,9 +246,7 @@ async function listSamplers(main_api, arrayOnly = false) {
246246
247247 if (prioritizeManualSamplerSelect) {
248248 finalState = isManuallyActivated;
249- }
249+ } else if (!isInDefaultState) {
250-
251- else if (!isInDefaultState) {
252250 finalState = displayModified === SELECT_SAMPLER.SHOWN;
253251 customColor = finalState ? forcedOnColoring : forcedOffColoring;
254252 }
public/scripts/slash-commands.js+4 -8
@@ -3026,8 +3026,7 @@ export function initDefaultSlashCommands() {
30263026 try {
30273027 const text = await navigator.clipboard.readText();
30283028 return text;
3029- }
3029+ } catch (error) {
3030- catch (error) {
30313030 console.error('Error reading clipboard:', error);
30323031 toastr.warning(t`Failed to read clipboard text. Have you granted the permission?`);
30333032 return '';
@@ -4432,8 +4431,7 @@ async function sendUserMessageCallback(args, text) {
44324431 const name = args.name || '';
44334432 const avatar = findPersonaByName(name) || user_avatar;
44344433 message = await sendMessageAsUser(text, bias, insertAt, compact, name, avatar);
44354434 } else {
4436- else {
44374435 message = await sendMessageAsUser(text, bias, insertAt, compact);
44384436 }
44394437
@@ -4640,12 +4638,10 @@ export function getNameAndAvatarForMessage(character, name = null) {
46404638 let force_avatar, original_avatar;
46414639 if (character?.avatar === currentChar?.avatar || isNeutralCharacter) {
46424640 // If the targeted character is the currently selected one in a solo chat, we don't need to force any avatars
4643- }
4641+ } else if (character && character.avatar !== 'none') {
4644- else if (character && character.avatar !== 'none') {
46454642 force_avatar = getThumbnailUrl('avatar', character.avatar);
46464643 original_avatar = character.avatar;
46474644 } else {
4648- else {
46494645 force_avatar = default_avatar;
46504646 original_avatar = default_avatar;
46514647 }
public/scripts/sse-stream.js+20 -32
@@ -111,8 +111,8 @@ function getDelay(s) {
111111 * @returns {AsyncGenerator<{data: object, chunk: string, reasoning?: boolean}>} The parsed data and the chunk to be sent.
112112 */
113113async function* parseStreamData(json) {
114- // Cohere
115114 if (typeof json.delta === 'object' && typeof json.delta.message === 'object' && ['tool-plan-delta', 'content-delta'].includes(json.type)) {
115+ // Cohere
116116 const text = json?.delta?.message?.content?.text ?? '';
117117 for (let i = 0; i < text.length; i++) {
118118 const str = json.delta.message.content.text[i];
@@ -122,9 +122,8 @@ async function* parseStreamData(json) {
122122 };
123123 }
124124 return;
125- }
125+ } else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
126126 // Claude
127- else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
128127 if (json.delta.text.length > 0) {
129128 for (let i = 0; i < json.delta.text.length; i++) {
130129 const str = json.delta.text[i];
@@ -135,8 +134,8 @@ async function* parseStreamData(json) {
135134 }
136135 }
137136 return;
138- }
137+ } else if (typeof json.delta === 'object' && typeof json.delta.thinking === 'string') {
139- else if (typeof json.delta === 'object' && typeof json.delta.thinking === 'string') {
138+ // Claude (reasoning content)
140139 if (json.delta.thinking.length > 0) {
141140 for (let i = 0; i < json.delta.thinking.length; i++) {
142141 const str = json.delta.thinking[i];
@@ -148,9 +147,8 @@ async function* parseStreamData(json) {
148147 }
149148 }
150149 return;
151- }
150+ } else if (Array.isArray(json.candidates)) {
152- // MakerSuite
151+ // Google VertexAI / AI Studio
153- else if (Array.isArray(json.candidates)) {
154152 for (let i = 0; i < json.candidates.length; i++) {
155153 const isNotPrimary = json.candidates?.[0]?.index > 0;
156154 const hasToolCalls = json?.candidates?.[0]?.content?.parts?.some(p => p?.functionCall);
@@ -187,9 +185,8 @@ async function* parseStreamData(json) {
187185 }
188186 }
189187 return;
190- }
188+ } else if (typeof json.token === 'string' && json.token.length > 0) {
191189 // NovelAI / KoboldCpp Classic
192- else if (typeof json.token === 'string' && json.token.length > 0) {
193190 for (let i = 0; i < json.token.length; i++) {
194191 const str = json.token[i];
195192 yield {
@@ -198,9 +195,8 @@ async function* parseStreamData(json) {
198195 };
199196 }
200197 return;
201- }
198+ } else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
202199 // llama.cpp?
203- else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
204200 const isNotPrimary = json?.index > 0;
205201 if (isNotPrimary) {
206202 throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -213,9 +209,8 @@ async function* parseStreamData(json) {
213209 };
214210 }
215211 return;
216- }
212+ } else if (Array.isArray(json.choices)) {
217213 // OpenAI-likes and friends
218- else if (Array.isArray(json.choices)) {
219214 const isNotPrimary = json?.choices?.[0]?.index > 0;
220215 if (isNotPrimary || json.choices.length === 0) {
221216 throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -233,8 +228,7 @@ async function* parseStreamData(json) {
233228 };
234229 }
235230 return;
236- }
231+ } else if (typeof json.choices[0].thinking === 'string' && json.choices[0].thinking.length > 0) {
237- else if (typeof json.choices[0].thinking === 'string' && json.choices[0].thinking.length > 0) {
238232 for (let j = 0; j < json.choices[0].thinking.length; j++) {
239233 const str = json.choices[0].thinking[j];
240234 const choiceClone = structuredClone(json.choices[0]);
@@ -247,8 +241,7 @@ async function* parseStreamData(json) {
247241 };
248242 }
249243 return;
250- }
244+ } else if (typeof json.choices[0].delta === 'object') {
251- else if (typeof json.choices[0].delta === 'object') {
252245 if (typeof json.choices[0].delta.text === 'string' && json.choices[0].delta.text.length > 0) {
253246 for (let j = 0; j < json.choices[0].delta.text.length; j++) {
254247 const str = json.choices[0].delta.text[j];
@@ -261,8 +254,7 @@ async function* parseStreamData(json) {
261254 };
262255 }
263256 return;
264- }
257+ } else if (typeof json.choices[0].delta.reasoning_content === 'string' && json.choices[0].delta.reasoning_content.length > 0) {
265- else if (typeof json.choices[0].delta.reasoning_content === 'string' && json.choices[0].delta.reasoning_content.length > 0) {
266258 for (let j = 0; j < json.choices[0].delta.reasoning_content.length; j++) {
267259 const str = json.choices[0].delta.reasoning_content[j];
268260 const isLastSymbol = j === json.choices[0].delta.reasoning_content.length - 1;
@@ -277,8 +269,7 @@ async function* parseStreamData(json) {
277269 };
278270 }
279271 return;
280- }
272+ } else if (typeof json.choices[0].delta.reasoning === 'string' && json.choices[0].delta.reasoning.length > 0) {
281- else if (typeof json.choices[0].delta.reasoning === 'string' && json.choices[0].delta.reasoning.length > 0) {
282273 for (let j = 0; j < json.choices[0].delta.reasoning.length; j++) {
283274 const str = json.choices[0].delta.reasoning[j];
284275 const isLastSymbol = j === json.choices[0].delta.reasoning.length - 1;
@@ -293,8 +284,7 @@ async function* parseStreamData(json) {
293284 };
294285 }
295286 return;
296- }
287+ } else if (typeof json.choices[0].delta.content === 'string' && json.choices[0].delta.content.length > 0) {
297- else if (typeof json.choices[0].delta.content === 'string' && json.choices[0].delta.content.length > 0) {
298288 for (let j = 0; j < json.choices[0].delta.content.length; j++) {
299289 const str = json.choices[0].delta.content[j];
300290 const choiceClone = structuredClone(json.choices[0]);
@@ -306,8 +296,7 @@ async function* parseStreamData(json) {
306296 };
307297 }
308298 return;
309- }
299+ } else if (Array.isArray(json.choices[0].delta.content) && json.choices[0].delta.content.length > 0) {
310- else if (Array.isArray(json.choices[0].delta.content) && json.choices[0].delta.content.length > 0) {
311300 if (Array.isArray(json.choices[0].delta.content[0].thinking) && json.choices[0].delta.content[0].thinking.length > 0) {
312301 if (typeof json.choices[0].delta.content[0].thinking[0].text === 'string' && json.choices[0].delta.content[0].thinking[0].text.length > 0) {
313302 for (let j = 0; j < json.choices[0].delta.content[0].thinking[0].text.length; j++) {
@@ -325,8 +314,7 @@ async function* parseStreamData(json) {
325314 }
326315 }
327316 }
328- }
317+ } else if (typeof json.choices[0].message === 'object') {
329- else if (typeof json.choices[0].message === 'object') {
330318 if (typeof json.choices[0].message.content === 'string' && json.choices[0].message.content.length > 0) {
331319 for (let j = 0; j < json.choices[0].message.content.length; j++) {
332320 const str = json.choices[0].message.content[j];
public/scripts/stats.js+1 -2
@@ -209,8 +209,7 @@ async function recreateStats() {
209209 if (!response.ok) {
210210 toastr.error('Stats could not be loaded. Try reloading the page.');
211211 throw new Error('Error getting stats');
212212 } else {
213- else {
214213 toastr.success('Stats file recreated successfully!');
215214 }
216215}
public/scripts/tags.js+2 -4
@@ -858,8 +858,7 @@ function addTagToMap(tagId, characterId = null) {
858858 if (!Array.isArray(tag_map[key])) {
859859 tag_map[key] = [tagId];
860860 return true;
861861 } else {
862- else {
863862 if (tag_map[key].includes(tagId))
864863 return false;
865864
@@ -885,8 +884,7 @@ function removeTagFromMap(tagId, characterId = null) {
885884 if (!Array.isArray(tag_map[key])) {
886885 tag_map[key] = [];
887886 return false;
888887 } else {
889- else {
890888 const indexOf = tag_map[key].indexOf(tagId);
891889 tag_map[key].splice(indexOf, 1);
892890 return indexOf !== -1;
public/scripts/textgen-models.js+3 -6
@@ -541,14 +541,11 @@ export async function loadFeatherlessModels(data) {
541541
542542 if (selectedCategory === 'All') {
543543 return matchesSearch && matchesClass;
544- }
544+ } else if (selectedCategory === 'Top') {
545- else if (selectedCategory === 'Top') {
546545 return matchesSearch && matchesClass && matchesTop;
547- }
546+ } else if (selectedCategory === 'New') {
548- else if (selectedCategory === 'New') {
549547 return matchesSearch && matchesClass && matchesNew;
550548 } else {
551- else {
552549 return matchesSearch && matchesClass;
553550 }
554551 });
public/scripts/textgen-settings.js+4 -8
@@ -1040,12 +1040,10 @@ export function initTextGenSettings() {
10401040 if (isCheckbox) {
10411041 const value = $(this).prop('checked');
10421042 textgenerationwebui_settings[id] = value;
1043- }
1043+ } else if (isText) {
1044- else if (isText) {
10451044 const value = $(this).val();
10461045 textgenerationwebui_settings[id] = value;
10471046 } else {
1048- else {
10491047 const value = Number($(this).val());
10501048 $(`#${id}_counter_textgenerationwebui`).val(value);
10511049 textgenerationwebui_settings[id] = value;
@@ -1254,11 +1252,9 @@ function setSettingByName(setting, value, trigger) {
12541252 if ('send_banned_tokens' === setting) {
12551253 $(`#${setting}_textgenerationwebui`).trigger('change');
12561254 }
1257- }
1255+ } else if (isText) {
1258- else if (isText) {
12591256 $(`#${setting}_textgenerationwebui`).val(value);
12601257 } else {
1261- else {
12621258 const val = parseFloat(value);
12631259 $(`#${setting}_textgenerationwebui`).val(val);
12641260 $(`#${setting}_counter_textgenerationwebui`).val(val);
public/scripts/tokenizers.js+31 -64
@@ -603,47 +603,34 @@ export function getTokenizerModel() {
603603
604604 if (model?.architecture?.tokenizer === 'Llama2') {
605605 return llamaTokenizer;
606- }
606+ } else if (model?.architecture?.tokenizer === 'Llama3') {
607- else if (model?.architecture?.tokenizer === 'Llama3') {
608607 return llama3Tokenizer;
609- }
608+ } else if (model?.architecture?.tokenizer === 'Mistral') {
610- else if (model?.architecture?.tokenizer === 'Mistral') {
611609 return mistralTokenizer;
612- }
610+ } else if (model?.architecture?.tokenizer === 'Yi') {
613- else if (model?.architecture?.tokenizer === 'Yi') {
614611 return yiTokenizer;
615- }
612+ } else if (model?.architecture?.tokenizer === 'Gemini') {
616- else if (model?.architecture?.tokenizer === 'Gemini') {
617613 return gemmaTokenizer;
618- }
614+ } else if (model?.architecture?.tokenizer === 'Qwen') {
619- else if (model?.architecture?.tokenizer === 'Qwen') {
620615 return qwen2Tokenizer;
621- }
616+ } else if (model?.architecture?.tokenizer === 'Cohere') {
622- else if (model?.architecture?.tokenizer === 'Cohere') {
623617 if (model?.id && model?.id.includes('command-a')) {
624618 return commandATokenizer;
625619 }
626620 return commandRTokenizer;
627- }
621+ } else if (oai_settings.openrouter_model.includes('gpt-4o')) {
628- else if (oai_settings.openrouter_model.includes('gpt-4o')) {
629622 return gpt4oTokenizer;
630- }
623+ } else if (oai_settings.openrouter_model.includes('gpt-4')) {
631- else if (oai_settings.openrouter_model.includes('gpt-4')) {
632624 return gpt4Tokenizer;
633- }
625+ } else if (oai_settings.openrouter_model.includes('gpt-3.5-turbo')) {
634- else if (oai_settings.openrouter_model.includes('gpt-3.5-turbo')) {
635626 return turboTokenizer;
636- }
627+ } else if (oai_settings.openrouter_model.includes('claude')) {
637- else if (oai_settings.openrouter_model.includes('claude')) {
638628 return claudeTokenizer;
639- }
629+ } else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
640- else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
641630 return gpt2Tokenizer;
642- }
631+ } else if (oai_settings.openrouter_model.includes('jamba')) {
643- else if (oai_settings.openrouter_model.includes('jamba')) {
644632 return jambaTokenizer;
645- }
633+ } else if (oai_settings.openrouter_model.includes('deepseek')) {
646- else if (oai_settings.openrouter_model.includes('deepseek')) {
647634 return deepseekTokenizer;
648635 }
649636 }
@@ -651,50 +638,35 @@ export function getTokenizerModel() {
651638 if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB && oai_settings.electronhub_model) {
652639 if (oai_settings.electronhub_model.includes('gpt-4o') || oai_settings.electronhub_model.includes('gpt-5')) {
653640 return gpt4oTokenizer;
654- }
641+ } else if (oai_settings.electronhub_model.includes('gpt-4.1') || oai_settings.electronhub_model.includes('gpt-4.5')) {
655- else if (oai_settings.electronhub_model.includes('gpt-4.1') || oai_settings.electronhub_model.includes('gpt-4.5')) {
656642 return gpt4oTokenizer;
657- }
643+ } else if (oai_settings.electronhub_model.includes('gpt-4')) {
658- else if (oai_settings.electronhub_model.includes('gpt-4')) {
659644 return gpt4Tokenizer;
660- }
645+ } else if (oai_settings.electronhub_model.includes('gpt-3.5-turbo')) {
661- else if (oai_settings.electronhub_model.includes('gpt-3.5-turbo')) {
662646 return turboTokenizer;
663- }
647+ } else if (oai_settings.electronhub_model.includes('claude')) {
664- else if (oai_settings.electronhub_model.includes('claude')) {
665648 return claudeTokenizer;
666- }
649+ } else if (oai_settings.electronhub_model.includes('jamba')) {
667- else if (oai_settings.electronhub_model.includes('jamba')) {
668650 return jambaTokenizer;
669- }
651+ } else if (oai_settings.electronhub_model.includes('deepseek') || oai_settings.electronhub_model.includes('sonar-reasoning') || oai_settings.electronhub_model.includes('r1')) {
670- else if (oai_settings.electronhub_model.includes('deepseek') || oai_settings.electronhub_model.includes('sonar-reasoning') || oai_settings.electronhub_model.includes('r1')) {
671652 return deepseekTokenizer;
672- }
653+ } else if (oai_settings.electronhub_model.includes('qwen')) {
673- else if (oai_settings.electronhub_model.includes('qwen')) {
674654 return qwen2Tokenizer;
675- }
655+ } else if (oai_settings.electronhub_model.includes('gemma')) {
676- else if (oai_settings.electronhub_model.includes('gemma')) {
677656 return gemmaTokenizer;
678- }
657+ } else if (oai_settings.electronhub_model.includes('mistral')) {
679- else if (oai_settings.electronhub_model.includes('mistral')) {
680658 return mistralTokenizer;
681- }
659+ } else if (oai_settings.electronhub_model.includes('yi')) {
682- else if (oai_settings.electronhub_model.includes('yi')) {
683660 return yiTokenizer;
684- }
661+ } else if (oai_settings.electronhub_model.includes('llama3') || oai_settings.electronhub_model.includes('llama-3') || oai_settings.electronhub_model.startsWith('l3')) {
685- else if (oai_settings.electronhub_model.includes('llama3') || oai_settings.electronhub_model.includes('llama-3') || oai_settings.electronhub_model.startsWith('l3')) {
686662 return llama3Tokenizer;
687- }
663+ } else if (oai_settings.electronhub_model.includes('llama')) {
688- else if (oai_settings.electronhub_model.includes('llama')) {
689664 return llamaTokenizer;
690- }
665+ } else if (oai_settings.electronhub_model.includes('command-a')) {
691- else if (oai_settings.electronhub_model.includes('command-a')) {
692666 return commandATokenizer;
693- }
667+ } else if (oai_settings.electronhub_model.includes('command-r')) {
694- else if (oai_settings.electronhub_model.includes('command-r')) {
695668 return commandRTokenizer;
696- }
669+ } else if (oai_settings.electronhub_model.includes('nemo')) {
697- else if (oai_settings.electronhub_model.includes('nemo')) {
698670 return nemoTokenizer;
699671 }
700672 }
@@ -814,9 +786,7 @@ export function countTokensOpenAI(messages, full = false) {
814786
815787 if (typeof cachedCount === 'number') {
816788 token_count += cachedCount;
817789 } else {
818-
819- else {
820790 jQuery.ajax({
821791 async: false,
822792 type: 'POST', //
@@ -866,9 +836,7 @@ export async function countTokensOpenAIAsync(messages, full = false) {
866836
867837 if (typeof cachedCount === 'number') {
868838 token_count += cachedCount;
869839 } else {
870-
871- else {
872840 const data = await jQuery.ajax({
873841 async: true,
874842 type: 'POST', //
@@ -898,8 +866,7 @@ function getTokenCacheObject() {
898866 try {
899867 if (selected_group) {
900868 chatId = groups.find(x => x.id == selected_group)?.chat_id;
901- }
869+ } else if (this_chid !== undefined) {
902- else if (this_chid !== undefined) {
903870 chatId = characters[this_chid].chat;
904871 }
905872 } catch {
public/scripts/user.js+1 -2
@@ -327,8 +327,7 @@ async function changePassword(handle, callback) {
327327
328328 toastr.success('Password changed successfully', 'Password Changed');
329329 callback();
330- }
330+ } catch (error) {
331- catch (error) {
332331 console.error('Error changing password:', error);
333332 }
334333}
public/scripts/util/SimpleMutex.js+1 -2
@@ -36,8 +36,7 @@ export class SimpleMutex {
3636 try {
3737 this.isBusy = true;
3838 await this.callback(...args);
3939 } finally {
40- finally {
4140 this.isBusy = false;
4241 }
4342 }
public/scripts/variables.js+1 -2
@@ -388,8 +388,7 @@ async function timesCallback(args, value) {
388388 command.breakController = new SlashCommandBreakController();
389389 command.scope.setMacro('timesIndex', i);
390390 result = await command.execute();
391391 } else {
392- else {
393392 result = await executeSubCommands(command.replace(/\{\{timesIndex\}\}/g, i.toString()), args._scope, args._parserFlags, args._abortController);
394393 }
395394 if (result.isAborted) break;
public/scripts/welcome-screen.js+1 -2
@@ -716,8 +716,7 @@ export async function openPermanentAssistantChat({ tryCreate = true, created = f
716716 console.log(`Character not found for avatar ID: ${avatar}. Creating new assistant.`);
717717 await createPermanentAssistant();
718718 return openPermanentAssistantChat({ tryCreate: false, created: true });
719- }
719+ } catch (error) {
720- catch (error) {
721720 console.error('Error creating permanent assistant:', error);
722721 toastr.error(t`Failed to create ${neutralCharacterName}. See console for details.`);
723722 return;
public/scripts/world-info.js+7 -14
@@ -351,8 +351,7 @@ class WorldInfoBuffer {
351351
352352 if (keyWords.length > 1) {
353353 return haystack.includes(transformedString);
354354 } else {
355- else {
356355 // Use custom boundaries to include punctuation and other non-alphanumeric characters
357356 const regex = new RegExp(`(?:^|\\W)(${escapeRegex(transformedString)})(?:$|\\W)`);
358357 if (regex.test(haystack)) {
@@ -1141,8 +1140,7 @@ function registerWorldInfoSlashCommands() {
11411140 // Also assign the book now - additional if requested, otherwise as primary
11421141 if (type === 'additional') {
11431142 await charUpdateAddAuxWorld(character.avatar, newName);
11441143 } else {
1145- else {
11461144 await charUpdatePrimaryWorld(newName);
11471145 }
11481146 // Refresh UI, if needed
@@ -2169,8 +2167,7 @@ export function sortWorldInfoEntries(data, { customSort = null } = {}) {
21692167 const bScore = worldInfoFilter.getScore(FILTER_TYPES.WORLD_INFO_SEARCH, b.uid);
21702168 return aScore - bScore;
21712169 };
2172- }
2170+ } else if (sortRule === 'custom') {
2173- else if (sortRule === 'custom') {
21742171 // First by display index
21752172 primarySort = (a, b) => {
21762173 const aValue = a.displayIndex;
@@ -4434,8 +4431,7 @@ export async function getSortedEntries() {
44344431
44354432 // Need to deep clone the entries to avoid modifying the cached data
44364433 return structuredClone(entries);
4437- }
4434+ } catch (e) {
4438- catch (e) {
44394435 console.error(e);
44404436 return [];
44414437 }
@@ -4481,8 +4477,7 @@ function parseDecorators(content) {
44814477 if (isKnownDecorator(splited[i])) {
44824478 decorators.push(splited[i].startsWith('@@@') ? splited[i].substring(1) : splited[i]);
44834479 fallbacked = false;
44844480 } else {
4485- else {
44864481 fallbacked = true;
44874482 }
44884483 } else {
@@ -5506,8 +5501,7 @@ export function checkEmbeddedWorld(chid) {
55065501 }
55075502 };
55085503 callGenericPopup(html, POPUP_TYPE.CONFIRM, '', { okButton: 'Yes' }).then(checkResult);
55095504 } else {
5510- else {
55115505 toastr.info(
55125506 'To import and use it, select "Import Card Lore" in the "More..." dropdown menu on the character panel.',
55135507 `${characters[chid].name} has an embedded World/Lorebook`,
@@ -6121,8 +6115,7 @@ export function initWorldInfo() {
61216115 } else if (hasEmbed && !event.shiftKey) {
61226116 await importEmbeddedWorldInfo();
61236117 saveCharacterDebounced();
61246118 } else {
6125- else {
61266119 openSetWorldMenu();
61276120 }
61286121 });
src/endpoints/assets.js+5 -10
@@ -173,8 +173,7 @@ router.post('/get', async (request, response) => {
173173 }
174174 }
175175 }
176- }
176+ } catch (err) {
177- catch (err) {
178177 console.error(err);
179178 }
180179 return response.send(output);
@@ -255,8 +254,7 @@ router.post('/download', async (request, response) => {
255254 fs.copyFileSync(temp_path, file_path);
256255 fs.unlinkSync(temp_path);
257256 response.sendStatus(200);
258- }
257+ } catch (error) {
259- catch (error) {
260258 console.error(error);
261259 response.sendStatus(500);
262260 }
@@ -299,15 +297,13 @@ router.post('/delete', async (request, response) => {
299297 if (err) throw err;
300298 });
301299 console.info('Asset deleted.');
302300 } else {
303- else {
304301 console.error('Asset not found.');
305302 response.sendStatus(400);
306303 }
307304 // Move into asset place
308305 response.sendStatus(200);
309- }
306+ } catch (error) {
310- catch (error) {
311307 console.error(error);
312308 response.sendStatus(500);
313309 }
@@ -372,8 +368,7 @@ router.post('/character', async (request, response) => {
372368 output.push(`/characters/${name}/${category}/${i}`);
373369 }
374370 return response.send(output);
375- }
371+ } catch (err) {
376- catch (err) {
377372 console.error(err);
378373 return response.sendStatus(500);
379374 }
src/endpoints/backends/chat-completions.js+3 -6
@@ -1425,8 +1425,7 @@ async function sendElectronHubRequest(request, response) {
14251425 console.debug('Electron Hub response:', generateResponseJson);
14261426 return response.send(generateResponseJson);
14271427 }
1428- }
1428+ } catch (error) {
1429- catch (error) {
14301429 console.error('Error communicating with Electron Hub: ', error);
14311430 if (!response.headersSent) {
14321431 response.send({ error: true });
@@ -1527,8 +1526,7 @@ async function sendChutesRequest(request, response) {
15271526 console.debug('Chutes response:', generateResponseJson);
15281527 return response.send(generateResponseJson);
15291528 }
1530- }
1529+ } catch (error) {
1531- catch (error) {
15321530 console.error('Error communicating with Chutes: ', error);
15331531 if (!response.headersSent) {
15341532 response.send({ error: true });
@@ -1910,8 +1908,7 @@ router.post('/status', async function (request, statusResponse) {
19101908 console.warn('Chat Completion endpoint did not return a list of models.');
19111909 }
19121910 }
19131911 } else {
1914- else {
19151912 console.error('Chat Completion status check failed. Either Access Token is incorrect or API endpoint is down.');
19161913 statusResponse.send({ error: true, data: { data: [] } });
19171914 }
src/endpoints/backends/text-completions.js+1 -2
@@ -405,8 +405,7 @@ router.post('/generate', async function (request, response) {
405405 const completionsStream = await fetch(url, args);
406406 // Pipe remote SSE stream to Express response
407407 forwardFetchResponse(completionsStream, response);
408408 } else {
409- else {
410409 const completionsReply = await fetch(url, args);
411410
412411 if (completionsReply.ok) {
src/endpoints/backups.js+2 -4
@@ -45,8 +45,7 @@ router.post('/chat/delete', async (request, response) => {
4545
4646 await fsPromises.unlink(filePath);
4747 return response.sendStatus(200);
48- }
48+ } catch (error) {
49- catch (error) {
5049 console.error(error);
5150 return response.sendStatus(500);
5251 }
@@ -67,8 +66,7 @@ router.post('/chat/download', async (request, response) => {
6766 }
6867
6968 return response.download(filePath);
70- }
69+ } catch (error) {
71- catch (error) {
7270 console.error(error);
7371 return response.sendStatus(500);
7472 }
src/endpoints/characters.js+6 -11
@@ -326,9 +326,8 @@ async function tryReadImage(imgPath, crop) {
326326 try {
327327 const rawImg = await Jimp.read(imgPath);
328328 return await applyAvatarCropResize(rawImg, crop);
329- }
329+ } catch (error) {
330330 // If it's an unsupported type of image (APNG) - just read the file as buffer
331- catch (error) {
332331 console.error(`Failed to read image: ${imgPath}`, error);
333332 return fs.readFileSync(imgPath);
334333 }
@@ -423,8 +422,7 @@ const processCharacter = async (item, directories, { shallow }) => {
423422 character.date_last_chat = dateLastChat;
424423 character.data_size = calculateDataSize(jsonObject?.data);
425424 return shallow ? toShallow(character) : character;
426- }
425+ } catch (err) {
427- catch (err) {
428426 console.error(`Could not process character: ${item}`);
429427
430428 if (err instanceof SyntaxError) {
@@ -1081,8 +1079,7 @@ router.post('/rename', validateAvatarUrlMiddleware, async function (request, res
10811079
10821080 // Return new avatar name to ST
10831081 return response.send({ avatar: newAvatarName });
1084- }
1082+ } catch (err) {
1085- catch (err) {
10861083 console.error(err);
10871084 return response.sendStatus(500);
10881085 }
@@ -1495,8 +1492,7 @@ router.post('/duplicate', validateAvatarUrlMiddleware, async function (request,
14951492 fs.copyFileSync(filename, newFilename);
14961493 console.info(`${filename} was copied to ${newFilename}`);
14971494 response.send({ path: path.parse(newFilename).base });
1498- }
1495+ } catch (error) {
1499- catch (error) {
15001496 console.error(error);
15011497 return response.send({ error: true });
15021498 }
@@ -1532,8 +1528,7 @@ router.post('/export', validateAvatarUrlMiddleware, async function (request, res
15321528 const jsonObject = getCharaCardV2(JSON.parse(json), request.user.directories);
15331529 unsetPrivateFields(jsonObject);
15341530 return response.type('json').send(JSON.stringify(jsonObject, null, 4));
15351531 } catch {
1536- catch {
15371532 return response.sendStatus(400);
15381533 }
15391534 }
src/endpoints/chats.js+1 -2
@@ -837,8 +837,7 @@ router.post('/group/save', async function (request, response) {
837837 if (Array.isArray(chatData)) {
838838 await trySaveChat(chatData, chatFilePath, request.body.force, handle, String(id), request.user.directories.backups);
839839 return response.send({ ok: true });
840840 } else {
841- else {
842841 return response.status(400).send({ error: 'The request\'s body.chat is not an array.' });
843842 }
844843 } catch (error) {
src/endpoints/content-manager.js+4 -8
@@ -941,12 +941,10 @@ router.post('/importURL', async (request, response) => {
941941 if (chubParsed?.type === 'character') {
942942 console.info('Downloading chub character:', chubParsed.id);
943943 result = await downloadChubCharacter(chubParsed.id);
944- }
944+ } else if (chubParsed?.type === 'lorebook') {
945- else if (chubParsed?.type === 'lorebook') {
946945 console.info('Downloading chub lorebook:', chubParsed.id);
947946 result = await downloadChubLorebook(chubParsed.id);
948947 } else {
949- else {
950948 return response.sendStatus(404);
951949 }
952950 } else if (isRisu) {
@@ -1020,12 +1018,10 @@ router.post('/importUUID', async (request, response) => {
10201018 if (uuidType === 'character') {
10211019 console.info('Downloading chub character:', uuid);
10221020 result = await downloadChubCharacter(uuid);
1023- }
1021+ } else if (uuidType === 'lorebook') {
1024- else if (uuidType === 'lorebook') {
10251022 console.info('Downloading chub lorebook:', uuid);
10261023 result = await downloadChubLorebook(uuid);
10271024 } else {
1028- else {
10291025 return response.sendStatus(404);
10301026 }
10311027 }
src/endpoints/groups.js+1 -2
@@ -145,8 +145,7 @@ router.post('/all', (request, response) => {
145145 group.date_last_chat = date_last_chat;
146146 group.chat_size = chat_size;
147147 groups.push(group);
148- }
148+ } catch (error) {
149- catch (error) {
150149 console.error(error);
151150 }
152151 });
src/endpoints/horde.js+1 -2
@@ -113,8 +113,7 @@ router.post('/text-models', async (request, response) => {
113113 try {
114114 const metadata = await getHordeTextModelMetadata();
115115 data = await mergeModelsAndMetadata(data, metadata);
116- }
116+ } catch (error) {
117- catch (error) {
118117 console.error('Failed to fetch metadata:', error);
119118 }
120119
src/endpoints/novelai.js+3 -6
@@ -154,8 +154,7 @@ router.post('/status', async function (req, res) {
154154 } else if (response.status == 401) {
155155 console.error('NovelAI Access Token is incorrect.');
156156 return res.send({ error: true });
157157 } else {
158- else {
159158 console.warn('NovelAI returned an error:', response.statusText);
160159 return res.send({ error: true });
161160 }
@@ -281,8 +280,7 @@ router.post('/generate', async function (req, res) {
281280 try {
282281 const data = JSON.parse(text);
283282 message = data.message;
284283 } catch {
285- catch {
286284 // ignore
287285 }
288286
@@ -476,8 +474,7 @@ router.post('/generate-voice', async (request, response) => {
476474 const buffer = Buffer.concat(chunks.map(chunk => new Uint8Array(chunk)));
477475 response.setHeader('Content-Type', 'audio/mpeg');
478476 return response.send(buffer);
479- }
477+ } catch (error) {
480- catch (error) {
481478 console.error(error);
482479 return response.sendStatus(500);
483480 }
src/endpoints/openai.js+1 -2
@@ -262,8 +262,7 @@ router.post('/caption-image', async (request, response) => {
262262 }
263263
264264 return response.json({ caption });
265- }
265+ } catch (error) {
266- catch (error) {
267266 console.error(error);
268267 response.status(500).send('Internal server error');
269268 }
src/endpoints/settings.js+1 -2
@@ -58,8 +58,7 @@ function readAndParseFromDirectory(directoryPath, fileExtension = '.json') {
5858 try {
5959 const file = fs.readFileSync(path.join(directoryPath, item), 'utf-8');
6060 parsedFiles.push(fileExtension == '.json' ? JSON.parse(file) : file);
6161 } catch {
62- catch {
6362 // skip
6463 }
6564 });
src/endpoints/sprites.js+1 -2
@@ -143,8 +143,7 @@ router.get('/get', function (request, response) {
143143 };
144144 });
145145 }
146- }
146+ } catch (err) {
147- catch (err) {
148147 console.error(err);
149148 }
150149 return response.send(sprites);
src/endpoints/stable-diffusion.js+4 -8
@@ -1316,8 +1316,7 @@ chutes.post('/models', async (request, response) => {
13161316 const chutesData = /** @type {{items: Array<{name: string}>}} */ (data);
13171317 const models = chutesData.items.map(x => ({ value: x.name, text: x.name })).sort((a, b) => a?.text?.localeCompare(b?.text));
13181318 return response.send(models);
1319- }
1319+ } catch (error) {
1320- catch (error) {
13211320 console.error(error);
13221321 return response.sendStatus(500);
13231322 }
@@ -1363,8 +1362,7 @@ chutes.post('/generate', async (request, response) => {
13631362 const base64 = Buffer.from(buffer).toString('base64');
13641363
13651364 return response.send({ image: base64 });
1366- }
1365+ } catch (error) {
1367- catch (error) {
13681366 console.error(error);
13691367 return response.sendStatus(500);
13701368 }
@@ -1405,8 +1403,7 @@ nanogpt.post('/models', async (request, response) => {
14051403
14061404 const models = Object.values(imageModels).map(x => ({ value: x.model, text: x.name }));
14071405 return response.send(models);
1408- }
1406+ } catch (error) {
1409- catch (error) {
14101407 console.error(error);
14111408 return response.sendStatus(500);
14121409 }
@@ -1447,8 +1444,7 @@ nanogpt.post('/generate', async (request, response) => {
14471444 }
14481445
14491446 return response.send({ image });
1450- }
1447+ } catch (error) {
1451- catch (error) {
14521448 console.error(error);
14531449 return response.sendStatus(500);
14541450 }
src/prompt-converters.js+3 -6
@@ -939,8 +939,7 @@ export function mergeMessages(messages, names, { strict = false, placeholders =
939939 if (mergedMessages.length && placeholders) {
940940 if (mergedMessages[0].role === 'system' && (mergedMessages.length === 1 || mergedMessages[1].role !== 'user')) {
941941 mergedMessages.splice(1, 0, { role: 'user', content: PROMPT_PLACEHOLDER });
942- }
942+ } else if (mergedMessages[0].role !== 'system' && mergedMessages[0].role !== 'user') {
943- else if (mergedMessages[0].role !== 'system' && mergedMessages[0].role !== 'user') {
944943 mergedMessages.unshift({ role: 'user', content: PROMPT_PLACEHOLDER });
945944 }
946945 }
@@ -964,11 +963,9 @@ export function convertTextCompletionPrompt(messages) {
964963 messages.forEach(m => {
965964 if (m.role === 'system' && m.name === undefined) {
966965 messageStrings.push('System: ' + m.content);
967- }
966+ } else if (m.role === 'system' && m.name !== undefined) {
968- else if (m.role === 'system' && m.name !== undefined) {
969967 messageStrings.push(m.name + ': ' + m.content);
970968 } else {
971- else {
972969 messageStrings.push(m.role + ': ' + m.content);
973970 }
974971 });
src/users.js+1 -2
@@ -680,8 +680,7 @@ export async function getUserAvatar(handle) {
680680 const mimeType = mime.lookup(avatarPath);
681681 const base64Content = fs.readFileSync(avatarPath, 'base64');
682682 return `data:${mimeType};base64,${base64Content}`;
683683 } catch {
684- catch {
685684 // Ignore errors
686685 return PUBLIC_USER_AVATAR;
687686 }
src/util.js+3 -6
@@ -157,8 +157,7 @@ export async function getVersion() {
157157 const remoteLatest = await git.revparse([trackingBranch]);
158158 isLatest = localLatest === remoteLatest;
159159 }
160160 } catch {
161- catch {
162161 // suppress exception
163162 }
164163
@@ -821,8 +820,7 @@ export function mergeObjectWithYaml(obj, yamlString) {
821820 Object.assign(obj, item);
822821 }
823822 }
824- }
823+ } else if (parsedObject && typeof parsedObject === 'object') {
825- else if (parsedObject && typeof parsedObject === 'object') {
826824 Object.assign(obj, parsedObject);
827825 }
828826 } catch {
@@ -1307,8 +1305,7 @@ export function safeReadFileSync(filePath, options = { encoding: 'utf-8' }) {
13071305export function setWindowTitle(title) {
13081306 if (process.platform === 'win32') {
13091307 process.title = title;
13101308 } else {
1311- else {
13121309 process.stdout.write(`\x1b]2;${title}\x1b\x5c`);
13131310 }
13141311}
src/vectors/extras-vectors.js+1 -2
@@ -34,8 +34,7 @@ async function getExtrasVectorImpl(text, apiUrl, apiKey) {
3434 try {
3535 url = new URL(apiUrl);
3636 url.pathname = '/api/embeddings/compute';
37- }
37+ } catch (error) {
38- catch (error) {
3938 console.error('Failed to set up Extras API call:', error);
4039 console.debug('Extras API URL given was:', apiUrl);
4140 throw error;