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 = {
102 // These rules should eventually be enabled.102 // These rules should eventually be enabled.
103 'no-async-promise-executor': 'off',103 'no-async-promise-executor': 'off',
104 'no-inner-declarations': 'off',104 'no-inner-declarations': 'off',
105 'brace-style': 'off',
106 // Additional formatting rules based on codebase conventions105 // Additional formatting rules based on codebase conventions
106 'brace-style': ['error', '1tbs', { allowSingleLine: true }],
107 'array-bracket-spacing': ['error', 'never'],107 'array-bracket-spacing': ['error', 'never'],
108 'computed-property-spacing': ['error', 'never'],108 'computed-property-spacing': ['error', 'never'],
109 'block-spacing': ['error', 'always'],109 'block-spacing': ['error', 'always'],
plugins.js+1 -2
@@ -89,8 +89,7 @@ async function installPlugin(pluginName) {
8989
90 await git().clone(pluginName, pluginPath, { '--depth': 1 });90 await git().clone(pluginName, pluginPath, { '--depth': 1 });
91 console.log(`Plugin ${color.green(pluginName)} installed to ${color.cyan(pluginPath)}`);91 console.log(`Plugin ${color.green(pluginName)} installed to ${color.cyan(pluginPath)}`);
92 }92 } catch (error) {
93 catch (error) {
94 console.error(color.red(`Failed to install plugin ${pluginName}`), error);93 console.error(color.red(`Failed to install plugin ${pluginName}`), error);
95 }94 }
96}95}
public/script.js+57 -121
@@ -512,8 +512,7 @@ export function reloadMarkdownProcessor() {
512export function getCurrentChatId() {512export function getCurrentChatId() {
513 if (selected_group) {513 if (selected_group) {
514 return groups.find(x => x.id == selected_group)?.chat_id;514 return groups.find(x => x.id == selected_group)?.chat_id;
515 }515 } else if (this_chid !== undefined) {
516 else if (this_chid !== undefined) {
517 return characters[this_chid]?.chat;516 return characters[this_chid]?.chat;
518 }517 }
519}518}
@@ -910,8 +909,7 @@ function getCharacterBlock(item, id) {
910 const description = item.data?.creator_notes || '';909 const description = item.data?.creator_notes || '';
911 if (description) {910 if (description) {
912 template.find('.ch_description').text(description);911 template.find('.ch_description').text(description);
913 }912 } else {
914 else {
915 template.find('.ch_description').hide();913 template.find('.ch_description').hide();
916 }914 }
917915
@@ -919,8 +917,7 @@ function getCharacterBlock(item, id) {
919 const auxFieldValue = (item.data && item.data[auxFieldName]) || '';917 const auxFieldValue = (item.data && item.data[auxFieldName]) || '';
920 if (auxFieldValue) {918 if (auxFieldValue) {
921 template.find('.character_version').text(auxFieldValue);919 template.find('.character_version').text(auxFieldValue);
922 }920 } else {
923 else {
924 template.find('.character_version').hide();921 template.find('.character_version').hide();
925 }922 }
926923
@@ -1364,16 +1361,14 @@ export async function replaceCurrentChat() {
1364 const chats = Object.values(await chatsResponse.json());1361 const chats = Object.values(await chatsResponse.json());
1365 chats.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes)));1362 chats.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes)));
13661363
1367 // pick existing chat
1368 if (chats.length && typeof chats[0] === 'object') {1364 if (chats.length && typeof chats[0] === 'object') {
1365 // pick existing chat
1369 characters[this_chid].chat = chats[0].file_name.replace('.jsonl', '');1366 characters[this_chid].chat = chats[0].file_name.replace('.jsonl', '');
1370 $('#selected_chat_pole').val(characters[this_chid].chat);1367 $('#selected_chat_pole').val(characters[this_chid].chat);
1371 saveCharacterDebounced();1368 saveCharacterDebounced();
1372 await getChat();1369 await getChat();
1373 }1370 } else {
13741371 // start new chat
1375 // start new chat
1376 else {
1377 characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;1372 characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
1378 $('#selected_chat_pole').val(characters[this_chid].chat);1373 $('#selected_chat_pole').val(characters[this_chid].chat);
1379 saveCharacterDebounced();1374 saveCharacterDebounced();
@@ -1640,11 +1635,9 @@ export async function reloadCurrentChatUnsafe() {
16401635
1641 if (selected_group) {1636 if (selected_group) {
1642 await getGroupChat(selected_group, true);1637 await getGroupChat(selected_group, true);
1643 }1638 } else if (this_chid !== undefined) {
1644 else if (this_chid !== undefined) {
1645 await getChat();1639 await getChat();
1646 }1640 } else {
1647 else {
1648 resetChatState();1641 resetChatState();
1649 restoreNeutralChat();1642 restoreNeutralChat();
1650 await getCharacters();1643 await getCharacters();
@@ -1870,32 +1863,16 @@ export function messageFormatting(mes, ch_name, isSystem, isUser, messageId, san
1870/**1863/**
1871 * Inserts or replaces an SVG icon adjacent to the provided message's timestamp.1864 * Inserts or replaces an SVG icon adjacent to the provided message's timestamp.
1872 *1865 *
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 *
1877 * @param {JQuery<HTMLElement>} mes - The message element containing the timestamp where the icon should be inserted or replaced.1866 * @param {JQuery<HTMLElement>} mes - The message element containing the timestamp where the icon should be inserted or replaced.
1878 * @param {ChatMessageExtra} extra - Contains the API and model details.1867 * @param {ChatMessageExtra} extra - Contains the API and model details.
1879 */1868 */
1880function insertSVGIcon(mes, extra) {1869function insertSVGIcon(mes, extra) {
1881 // Determine the SVG filename1870 // Determine the SVG filename
1882 let modelName;1871 let modelName = extra?.api || '';
18831872
1884 // Claude on OpenRouter or Anthropic1873 // 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;
1899 }1876 }
19001877
1901 const insertOrReplaceSVG = (image, className, targetSelector, insertBefore) => {1878 const insertOrReplaceSVG = (image, className, targetSelector, insertBefore) => {
@@ -3755,8 +3732,7 @@ class StreamingProcessor {
3755 }3732 }
3756 const seconds = (timestamps[timestamps.length - 1] - timestamps[0]) / 1000;3733 const seconds = (timestamps[timestamps.length - 1] - timestamps[0]) / 1000;
3757 console.warn(`Stream stats: ${timestamps.length} tokens, ${seconds.toFixed(2)} seconds, rate: ${Number(timestamps.length / seconds).toFixed(2)} TPS`);3734 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) {
3760 // in the case of a self-inflicted abort, we have already cleaned up3736 // in the case of a self-inflicted abort, we have already cleaned up
3761 if (!this.isFinished) {3737 if (!this.isFinished) {
3762 console.error(err);3738 console.error(err);
@@ -4236,8 +4212,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
4236 textareaText = '';4212 textareaText = '';
4237 if (chat.length && lastMessage.is_user) {4213 if (chat.length && lastMessage.is_user) {
4238 //do nothing? why does this check exist?4214 //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) {
4241 deleteItemizedPromptForMessage(chat.length - 1);4216 deleteItemizedPromptForMessage(chat.length - 1);
4242 chat.length = chat.length - 1;4217 chat.length = chat.length - 1;
4243 await removeLastMessage();4218 await removeLastMessage();
@@ -4282,12 +4257,10 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
4282 // If user message contains no text other than bias - send as a system message4257 // If user message contains no text other than bias - send as a system message
4283 if (messageBias && !removeMacros(textareaText)) {4258 if (messageBias && !removeMacros(textareaText)) {
4284 sendSystemMessage(system_message_types.GENERIC, ' ', { bias: messageBias });4259 sendSystemMessage(system_message_types.GENERIC, ' ', { bias: messageBias });
4285 }4260 } else {
4286 else {
4287 await sendMessageAsUser(textareaText, messageBias);4261 await sendMessageAsUser(textareaText, messageBias);
4288 }4262 }
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) {
4291 // Use send_if_empty if set and the user message is empty. Only when sending messages normally4264 // Use send_if_empty if set and the user message is empty. Only when sending messages normally
4292 await sendMessageAsUser(oai_settings.send_if_empty.trim(), messageBias);4265 await sendMessageAsUser(oai_settings.send_if_empty.trim(), messageBias);
4293 }4266 }
@@ -4406,8 +4379,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
4406 if (main_api == 'koboldhorde' && (horde_settings.auto_adjust_context_length || horde_settings.auto_adjust_response_length)) {4379 if (main_api == 'koboldhorde' && (horde_settings.auto_adjust_context_length || horde_settings.auto_adjust_response_length)) {
4407 try {4380 try {
4408 adjustedParams = await adjustHordeGenerationParams(max_context, amount_gen);4381 adjustedParams = await adjustHordeGenerationParams(max_context, amount_gen);
4409 }4382 } catch {
4410 catch {
4411 unblockGeneration(type);4383 unblockGeneration(type);
4412 return Promise.resolve();4384 return Promise.resolve();
4413 }4385 }
@@ -4585,8 +4557,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
4585 // When continuing generation of previous output, last user message precedes the message to continue4557 // When continuing generation of previous output, last user message precedes the message to continue
4586 if (isContinue) {4558 if (isContinue) {
4587 coreChat.splice(coreChat.length - 1, 0, { mes: jailbreak, is_user: true });4559 coreChat.splice(coreChat.length - 1, 0, { mes: jailbreak, is_user: true });
4588 }4560 } else {
4589 else {
4590 // This operation will result in the injectedIndices indexes being off by one4561 // This operation will result in the injectedIndices indexes being off by one
4591 coreChat.push({ mes: jailbreak, is_user: true });4562 coreChat.push({ mes: jailbreak, is_user: true });
4592 // Add +1 to the elements to correct for the new PHI/Jailbreak message.4563 // 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
5208 if (itemizedIndex !== -1) {5179 if (itemizedIndex !== -1) {
5209 itemizedPrompts[itemizedIndex] = additionalPromptStuff;5180 itemizedPrompts[itemizedIndex] = additionalPromptStuff;
5210 }5181 } else {
5211 else {
5212 itemizedPrompts.push(additionalPromptStuff);5182 itemizedPrompts.push(additionalPromptStuff);
5213 }5183 }
52145184
@@ -5350,17 +5320,14 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
5350 if (isImpersonate) {5320 if (isImpersonate) {
5351 $('#send_textarea').val(getMessage)[0].dispatchEvent(new Event('input', { bubbles: true }));5321 $('#send_textarea').val(getMessage)[0].dispatchEvent(new Event('input', { bubbles: true }));
5352 await eventSource.emit(event_types.IMPERSONATE_READY, getMessage);5322 await eventSource.emit(event_types.IMPERSONATE_READY, getMessage);
5353 }5323 } else if (type == 'quiet') {
5354 else if (type == 'quiet') {
5355 unblockGeneration(type);5324 unblockGeneration(type);
5356 return getMessage;5325 return getMessage;
5357 }5326 } else {
5358 else {
5359 // Without streaming we'll be having a full message on continuation. Treat it as a last chunk.5327 // Without streaming we'll be having a full message on continuation. Treat it as a last chunk.
5360 if (originalType !== 'continue') {5328 if (originalType !== 'continue') {
5361 ({ type, getMessage } = await saveReply({ type, getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));5329 ({ type, getMessage } = await saveReply({ type, getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));
5362 }5330 } else {
5363 else {
5364 ({ type, getMessage } = await saveReply({ type: 'appendFinal', getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));5331 ({ type, getMessage } = await saveReply({ type: 'appendFinal', getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));
5365 }5332 }
53665333
@@ -5829,9 +5796,7 @@ function addChatsPreamble(mesSendString) {
5829function addChatsSeparator(mesSendString) {5796function addChatsSeparator(mesSendString) {
5830 if (power_user.context.chat_start) {5797 if (power_user.context.chat_start) {
5831 return substituteParams(power_user.context.chat_start + '\n') + mesSendString;5798 return substituteParams(power_user.context.chat_start + '\n') + mesSendString;
5832 }5799 } else {
5833
5834 else {
5835 return mesSendString;5800 return mesSendString;
5836 }5801 }
5837}5802}
@@ -7055,16 +7020,13 @@ export async function renameCharacter(name = null, { silent = false, renameChats
7055 } else {7020 } else {
7056 toastr.success(t`Character renamed!`, t`Rename Character`);7021 toastr.success(t`Character renamed!`, t`Rename Character`);
7057 }7022 }
7058 }7023 } else {
7059 else {
7060 throw new Error('Newly renamed character was lost?');7024 throw new Error('Newly renamed character was lost?');
7061 }7025 }
7062 }7026 } else {
7063 else {
7064 throw new Error('Could not rename the character');7027 throw new Error('Could not rename the character');
7065 }7028 }
7066 }7029 } catch (error) {
7067 catch (error) {
7068 // Reloading to prevent data corruption7030 // Reloading to prevent data corruption
7069 if (!silent) await Popup.show.text(t`Rename Character`, t`Something went wrong. The page will be reloaded.`);7031 if (!silent) await Popup.show.text(t`Rename Character`, t`Something went wrong. The page will be reloaded.`);
7070 else toastr.error(t`Something went wrong. The page will be reloaded.`, t`Rename Character`);7032 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
7356 avatarTemplate.append(grpTemplate.children());7318 avatarTemplate.append(grpTemplate.children());
7357 avatarTemplate.attr({ 'data-grid': id, 'data-chid': null });7319 avatarTemplate.attr({ 'data-grid': id, 'data-chid': null });
7358 avatarTemplate.attr('title', `[Group] ${entity.item.name}`);7320 avatarTemplate.attr('title', `[Group] ${entity.item.name}`);
7359 }7321 } else if (entity.type === 'persona') {
7360 else if (entity.type === 'persona') {
7361 avatarTemplate.attr({ 'data-pid': id, 'data-chid': null });7322 avatarTemplate.attr({ 'data-pid': id, 'data-chid': null });
7362 avatarTemplate.find('img').attr('src', getThumbnailUrl('persona', entity.item.avatar));7323 avatarTemplate.find('img').attr('src', getThumbnailUrl('persona', entity.item.avatar));
7363 avatarTemplate.attr('title', `[Persona] ${entity.item.name}\nFile: ${entity.item.avatar}`);7324 avatarTemplate.attr('title', `[Persona] ${entity.item.name}\nFile: ${entity.item.avatar}`);
@@ -8099,8 +8060,7 @@ async function messageEditCancel(messageId = this_edit_mes_id) {
8099 await eventSource.emit(event_types.MESSAGE_UPDATED, messageId);8060 await eventSource.emit(event_types.MESSAGE_UPDATED, messageId);
8100 if (messageId == this_edit_mes_id) {8061 if (messageId == this_edit_mes_id) {
8101 this_edit_mes_id = undefined;8062 this_edit_mes_id = undefined;
8102 }8063 } else {
8103 else {
8104 console.warn(`The message editor was closed on message #${messageId} while #${this_edit_mes_id} is being edited.`);8064 console.warn(`The message editor was closed on message #${messageId} while #${this_edit_mes_id} is being edited.`);
8105 }8065 }
81068066
@@ -8134,8 +8094,7 @@ async function messageEditMove(sourceId, targetId) {
81348094
8135 if (sourceId <= targetId) {8095 if (sourceId <= targetId) {
8136 sourceMessageDiv.insertAfter(targetMessageDiv);8096 sourceMessageDiv.insertAfter(targetMessageDiv);
8137 }8097 } else {
8138 else {
8139 sourceMessageDiv.insertBefore(targetMessageDiv);8098 sourceMessageDiv.insertBefore(targetMessageDiv);
8140 }8099 }
81418100
@@ -8951,11 +8910,13 @@ export function isMessageSwipeable(messageId, message = undefined) {
8951 //User messages are not swipeable.8910 //User messages are not swipeable.
8952 !message.is_user8911 !message.is_user
8953 )8912 )
8954 )8913 ) {
8955 //The message is swipeable.8914 // The message is swipeable.
8956 { return true; }8915 return true;
8957 //The message is not swipeable.8916 } else {
8958 else { return false; }8917 // The message is not swipeable.
8918 return false;
8919 }
8959}8920}
89608921
8961/**8922/**
@@ -9145,8 +9106,7 @@ export async function saveChatConditional() {
91459106
9146 if (selected_group) {9107 if (selected_group) {
9147 await saveGroupChat(selected_group, true);9108 await saveGroupChat(selected_group, true);
9148 }9109 } else {
9149 else {
9150 await saveChat();9110 await saveChat();
9151 }9111 }
91529112
@@ -9252,8 +9212,7 @@ export function closeMessageEditor(what = 'all') {
9252export function setGenerationProgress(progress) {9212export function setGenerationProgress(progress) {
9253 if (!progress) {9213 if (!progress) {
9254 $('#send_textarea').css({ 'background': '', 'transition': '' });9214 $('#send_textarea').css({ 'background': '', 'transition': '' });
9255 }9215 } else {
9256 else {
9257 $('#send_textarea').css({9216 $('#send_textarea').css({
9258 'background': `linear-gradient(90deg, #008000d6 ${progress}%, transparent ${progress}%)`,9217 'background': `linear-gradient(90deg, #008000d6 ${progress}%, transparent ${progress}%)`,
9259 'transition': '0.25s ease-in-out',9218 'transition': '0.25s ease-in-out',
@@ -9767,8 +9726,7 @@ export async function swipe(event, direction, { source, repeated, message = chat
9767 document.body.dataset.swiping = 'true';9726 document.body.dataset.swiping = 'true';
9768 await generation;9727 await generation;
9769 }9728 }
9770 }9729 } catch (error) {
9771 catch (error) {
9772 console.warn(`Swipe failed, Swiping back. ${error}`);9730 console.warn(`Swipe failed, Swiping back. ${error}`);
9773 }9731 }
97749732
@@ -9804,8 +9762,7 @@ export async function swipe(event, direction, { source, repeated, message = chat
9804 //Update the chat.9762 //Update the chat.
9805 await loadFromSwipeId(mesId, chat[mesId].swipe_id);9763 await loadFromSwipeId(mesId, chat[mesId].swipe_id);
9806 await redisplayChat({ startIndex: mesId });9764 await redisplayChat({ startIndex: mesId });
9807 }9765 } else {
9808 else {
9809 await Popup.show.confirm(9766 await Popup.show.confirm(
9810 t`ERROR: <code>syncSwipeToMes</code> has failed to revert the failed ${direction} swipe on message #${mesId}.`,9767 t`ERROR: <code>syncSwipeToMes</code> has failed to revert the failed ${direction} swipe on message #${mesId}.`,
9811 t`<p>After you click OK, the chat will be reloaded to prevent data corruption.</p>`,9768 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
10104 }10061 }
10105 await standardSwipe(newSwipeId);10062 await standardSwipe(newSwipeId);
10106 return;10063 return;
10107 }10064 } else if (direction === SWIPE_DIRECTION.RIGHT) {
10108 //If swiping right.10065 //If swiping right.
10109 else if (direction === SWIPE_DIRECTION.RIGHT) {
10110 // make new slot in array10066 // make new slot in array
10111 if (forceSwipeId == null) newSwipeId++;10067 if (forceSwipeId == null) newSwipeId++;
1011210068
@@ -10133,18 +10089,16 @@ export async function swipe(event, direction, { source, repeated, message = chat
10133 chat[mesId].swipe_id = originalSwipeId;10089 chat[mesId].swipe_id = originalSwipeId;
10134 await endSwipe();10090 await endSwipe();
10135 return;10091 return;
10136 }10092 } else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
10137 //Regenerate the message10093 //Regenerate the message
10138 else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
10139 clearMessageData(chat[mesId]);10094 clearMessageData(chat[mesId]);
10140 let run_generate = true;10095 let run_generate = true;
10141 //Generate.10096 //Generate.
10142 await animateSwipe(run_generate);10097 await animateSwipe(run_generate);
10143 await endSwipe();10098 await endSwipe();
10144 return;10099 return;
10145 }10100 } else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
10146 // Loop to the first swipe.10101 // Loop to the first swipe.
10147 else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
10148 newSwipeId = 0;10102 newSwipeId = 0;
10149 }10103 }
10150 }10104 }
@@ -10363,8 +10317,7 @@ export async function doNewChat({ deleteCurrentChat = false } = {}) {
10363 if (selected_group) {10317 if (selected_group) {
10364 await createNewGroupChat(selected_group);10318 await createNewGroupChat(selected_group);
10365 if (deleteCurrentChat) await deleteGroupChat(selected_group, chat_file_for_del, { jumpToNewChat: false }); // don't jump, new chat was already created and jumped to above10319 if (deleteCurrentChat) await deleteGroupChat(selected_group, chat_file_for_del, { jumpToNewChat: false }); // don't jump, new chat was already created and jumped to above
10366 }10320 } else {
10367 else {
10368 //RossAscends: added character name to new chat filenames and replaced Date.now() with humanizedDateTime;10321 //RossAscends: added character name to new chat filenames and replaced Date.now() with humanizedDateTime;
10369 chat_metadata = {};10322 chat_metadata = {};
10370 characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;10323 characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
@@ -10427,8 +10380,7 @@ export async function renameGroupOrCharacterChat({ characterId, groupId, oldFile
1042710380
10428 if (groupId) {10381 if (groupId) {
10429 await renameGroupChat(groupId, oldFileName, newFileName);10382 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) {
10432 characters[characterId].chat = newFileName;10384 characters[characterId].chat = newFileName;
10433 $('#selected_chat_pole').val(characters[characterId].chat);10385 $('#selected_chat_pole').val(characters[characterId].chat);
10434 await createOrEditCharacter();10386 await createOrEditCharacter();
@@ -11080,8 +11032,7 @@ jQuery(async function () {
11080 if (popup_type == 'input') {11032 if (popup_type == 'input') {
11081 dialogueResolve($('#dialogue_popup_input').val());11033 dialogueResolve($('#dialogue_popup_input').val());
11082 $('#dialogue_popup_input').val('');11034 $('#dialogue_popup_input').val('');
11083 }11035 } else {
11084 else {
11085 dialogueResolve(true);11036 dialogueResolve(true);
11086 }11037 }
1108711038
@@ -11316,9 +11267,7 @@ jQuery(async function () {
11316 });11267 });
11317 }11268 }
11318 }11269 }
11319 }11270 } else if (id == 'option_start_new_chat') {
11320
11321 else if (id == 'option_start_new_chat') {
11322 if ((selected_group || this_chid !== undefined) && !is_send_press) {11271 if ((selected_group || this_chid !== undefined) && !is_send_press) {
11323 let deleteCurrentChat = false;11272 let deleteCurrentChat = false;
11324 const result = await Popup.show.confirm(t`Start new chat?`, await renderTemplateAsync('newChatConfirm'), {11273 const result = await Popup.show.confirm(t`Start new chat?`, await renderTemplateAsync('newChatConfirm'), {
@@ -11334,9 +11283,7 @@ jQuery(async function () {
11334 const alreadyInTempChat = this_chid === undefined && name2 === neutralCharacterName;11283 const alreadyInTempChat = this_chid === undefined && name2 === neutralCharacterName;
11335 await newAssistantChat({ temporary: alreadyInTempChat });11284 await newAssistantChat({ temporary: alreadyInTempChat });
11336 }11285 }
11337 }11286 } else if (id == 'option_regenerate') {
11338
11339 else if (id == 'option_regenerate') {
11340 //Attempting to regenerate a user message will instead generate a new message.11287 //Attempting to regenerate a user message will instead generate a new message.
11341 if (chat.length && chat.length - 1 === this_edit_mes_id && chat[this_edit_mes_id]?.is_user == false) {11288 if (chat.length && chat.length - 1 === this_edit_mes_id && chat[this_edit_mes_id]?.is_user == false) {
11342 toastr.warning(t`Finish the edit before starting a generation.`, t`You cannot regenerate the message you are editing.`);11289 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 () {
11345 if (is_send_press == false) {11292 if (is_send_press == false) {
11346 if (selected_group) {11293 if (selected_group) {
11347 regenerateGroup();11294 regenerateGroup();
11348 }11295 } else {
11349 else {
11350 is_send_press = true;11296 is_send_press = true;
11351 Generate('regenerate', buildOrFillAdditionalArgs());11297 Generate('regenerate', buildOrFillAdditionalArgs());
11352 }11298 }
11353 }11299 }
11354 }11300 } else if (id == 'option_impersonate') {
11355
11356 else if (id == 'option_impersonate') {
11357 if (is_send_press == false || fromSlashCommand) {11301 if (is_send_press == false || fromSlashCommand) {
11358 is_send_press = true;11302 is_send_press = true;
11359 Generate('impersonate', buildOrFillAdditionalArgs());11303 Generate('impersonate', buildOrFillAdditionalArgs());
11360 }11304 }
11361 }11305 } else if (id == 'option_continue') {
11362
11363 else if (id == 'option_continue') {
11364 if (swipeState == SWIPE_STATE.EDITING) {11306 if (swipeState == SWIPE_STATE.EDITING) {
11365 toastr.warning(t`Confirm the edit to start a generation.`, t`You cannot send a message during a swipe-edit.`);11307 toastr.warning(t`Confirm the edit to start a generation.`, t`You cannot send a message during a swipe-edit.`);
11366 return;11308 return;
@@ -11374,17 +11316,11 @@ jQuery(async function () {
11374 is_send_press = true;11316 is_send_press = true;
11375 Generate('continue', buildOrFillAdditionalArgs());11317 Generate('continue', buildOrFillAdditionalArgs());
11376 }11318 }
11377 }11319 } else if (id == 'option_delete_mes') {
11378
11379 else if (id == 'option_delete_mes') {
11380 setTimeout(() => openMessageDelete(fromSlashCommand), animation_duration);11320 setTimeout(() => openMessageDelete(fromSlashCommand), animation_duration);
11381 }11321 } else if (id == 'option_close_chat') {
11382
11383 else if (id == 'option_close_chat') {
11384 await closeCurrentChat();11322 await closeCurrentChat();
11385 }11323 } else if (id === 'option_settings') {
11386
11387 else if (id === 'option_settings') {
11388 //var checkBox = document.getElementById("waifuMode");11324 //var checkBox = document.getElementById("waifuMode");
11389 var topBar = document.getElementById('top-bar');11325 var topBar = document.getElementById('top-bar');
11390 var topSettingsHolder = document.getElementById('top-settings-holder');11326 var topSettingsHolder = document.getElementById('top-settings-holder');
public/scripts/RossAscends-mods.js+2 -4
@@ -379,8 +379,7 @@ function RA_autoconnect(PrevApi) {
379 || (textgen_settings.type === textgen_types.FEATHERLESS && secret_state[SECRET_KEYS.FEATHERLESS])379 || (textgen_settings.type === textgen_types.FEATHERLESS && secret_state[SECRET_KEYS.FEATHERLESS])
380 ) {380 ) {
381 $('#api_button_textgenerationwebui').trigger('click');381 $('#api_button_textgenerationwebui').trigger('click');
382 }382 } else if (isValidUrl(getTextGenServer())) {
383 else if (isValidUrl(getTextGenServer())) {
384 $('#api_button_textgenerationwebui').trigger('click');383 $('#api_button_textgenerationwebui').trigger('click');
385 }384 }
386 break;385 break;
@@ -1053,8 +1052,7 @@ export function initRossMods() {
1053 $('#send_textarea').trigger('focus');1052 $('#send_textarea').trigger('focus');
1054 reasoningMesDone.trigger('click');1053 reasoningMesDone.trigger('click');
1055 return;1054 return;
1056 }1055 } else if (is_send_press == false) {
1057 else if (is_send_press == false) {
1058 const skipConfirmKey = 'RegenerateWithCtrlEnter';1056 const skipConfirmKey = 'RegenerateWithCtrlEnter';
1059 const skipConfirm = accountStorage.getItem(skipConfirmKey) === 'true';1057 const skipConfirm = accountStorage.getItem(skipConfirmKey) === 'true';
1060 function doRegenerate() {1058 function doRegenerate() {
public/scripts/authors-note.js+2 -4
@@ -231,11 +231,9 @@ function onExtensionFloatingCharaPromptInput() {
231 !existingCharaNote.useChara231 !existingCharaNote.useChara
232 ) {232 ) {
233 extension_settings.note.chara.splice(existingCharaNoteIndex, 1);233 extension_settings.note.chara.splice(existingCharaNoteIndex, 1);
234 }234 } else if (extension_settings.note.chara && existingCharaNote) {
235 else if (extension_settings.note.chara && existingCharaNote) {
236 Object.assign(existingCharaNote, tempCharaNote);235 Object.assign(existingCharaNote, tempCharaNote);
237 }236 } else if (avatarName && tempPrompt.length > 0) {
238 else if (avatarName && tempPrompt.length > 0) {
239 if (!extension_settings.note.chara) {237 if (!extension_settings.note.chara) {
240 extension_settings.note.chara = [];238 extension_settings.note.chara = [];
241 }239 }
public/scripts/bookmarks.js+4 -7
@@ -111,12 +111,10 @@ function getMainChatName() {
111 if (chat_metadata) {111 if (chat_metadata) {
112 if (chat_metadata.main_chat) {112 if (chat_metadata.main_chat) {
113 return chat_metadata.main_chat;113 return chat_metadata.main_chat;
114 }114 } else if (selected_group) {
115 // groups didn't support bookmarks before chat metadata was introduced115 // groups didn't support bookmarks before chat metadata was introduced
116 else if (selected_group) {
117 return null;116 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)) {
120 const tokenIndex = characters[this_chid].chat.lastIndexOf(bookmarkNameToken);118 const tokenIndex = characters[this_chid].chat.lastIndexOf(bookmarkNameToken);
121 chat_metadata.main_chat = characters[this_chid].chat.substring(0, tokenIndex).trim();119 chat_metadata.main_chat = characters[this_chid].chat.substring(0, tokenIndex).trim();
122 return chat_metadata.main_chat;120 return chat_metadata.main_chat;
@@ -146,8 +144,7 @@ export function showBookmarksButtons() {
146 $('#option_back_to_main').hide();144 $('#option_back_to_main').hide();
147 $('#option_new_bookmark').show();145 $('#option_new_bookmark').show();
148 }146 }
149 }147 } catch {
150 catch {
151 $('#option_back_to_main').hide();148 $('#option_back_to_main').hide();
152 $('#option_new_bookmark').hide();149 $('#option_new_bookmark').hide();
153 $('#option_convert_to_group').hide();150 $('#option_convert_to_group').hide();
public/scripts/chats.js+3 -6
@@ -832,11 +832,9 @@ async function openExternalMediaOverridesDialog() {
832832
833 if (power_user.external_media_allowed_overrides.includes(entityId)) {833 if (power_user.external_media_allowed_overrides.includes(entityId)) {
834 template.find('#forbid_media_override_allowed').prop('checked', true);834 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)) {
837 template.find('#forbid_media_override_forbidden').prop('checked', true);836 template.find('#forbid_media_override_forbidden').prop('checked', true);
838 }837 } else {
839 else {
840 template.find('#forbid_media_override_global').prop('checked', true);838 template.find('#forbid_media_override_global').prop('checked', true);
841 }839 }
842840
@@ -1678,8 +1676,7 @@ async function runScraper(scraperId, target, callback) {
16781676
1679 toastr.success(t`Scraped ${files.length} files from ${scraperId} to ${target}.`, t`Data Bank`);1677 toastr.success(t`Scraped ${files.length} files from ${scraperId} to ${target}.`, t`Data Bank`);
1680 callback();1678 callback();
1681 }1679 } catch (error) {
1682 catch (error) {
1683 console.error('Scraping failed', error);1680 console.error('Scraping failed', error);
1684 toastr.error(t`Check browser console for details.`, t`Scraping failed`);1681 toastr.error(t`Check browser console for details.`, t`Scraping failed`);
1685 }1682 }
public/scripts/dynamic-styles.js+1 -2
@@ -73,8 +73,7 @@ function applyDynamicFocusStyles(styleSheet, { fromExtension = false } = {}) {
73 const isHover = selector.includes(':hover'), isFocus = selector.includes(':focus');73 const isHover = selector.includes(':hover'), isFocus = selector.includes(':focus');
74 if (isHover && isFocus) {74 if (isHover && isFocus) {
75 // We currently do nothing here. Rules containing both hover and focus are very specific and should never be automatically touched75 // 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) {
78 const baseSelector = selector.replace(/:hover/g, PLACEHOLDER).trim();77 const baseSelector = selector.replace(/:hover/g, PLACEHOLDER).trim();
79 hoverRules.push({ baseSelector, rule, wrappers: [...wrappers] });78 hoverRules.push({ baseSelector, rule, wrappers: [...wrappers] });
80 } else if (isFocus) {79 } else if (isFocus) {
public/scripts/extensions.js+3 -6
@@ -278,12 +278,10 @@ async function discoverExtensions() {
278 if (response.ok) {278 if (response.ok) {
279 const extensions = await response.json();279 const extensions = await response.json();
280 return extensions;280 return extensions;
281 }281 } else {
282 else {
283 return [];282 return [];
284 }283 }
285 }284 } catch (err) {
286 catch (err) {
287 console.error(err);285 console.error(err);
288 return [];286 return [];
289 }287 }
@@ -627,8 +625,7 @@ async function connectToApi(baseUrl) {
627 }625 }
628626
629 updateStatus(getExtensionsResult.ok);627 updateStatus(getExtensionsResult.ok);
630 }628 } catch {
631 catch {
632 updateStatus(false);629 updateStatus(false);
633 }630 }
634}631}
public/scripts/extensions/assets/index.js+6 -12
@@ -82,8 +82,7 @@ function getAuthorFromUrl(url) {
82 result.name = pathSegments[0];82 result.name = pathSegments[0];
83 result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`;83 result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`;
84 }84 }
85 }85 } catch (error) {
86 catch (error) {
87 console.debug(DEBUG_PREFIX, 'Error parsing URL:', error);86 console.debug(DEBUG_PREFIX, 'Error parsing URL:', error);
88 }87 }
8988
@@ -199,8 +198,7 @@ async function downloadAssetsList(url) {
199 label.removeClass('fa-trash');198 label.removeClass('fa-trash');
200 label.removeClass('redOverlayGlow');199 label.removeClass('redOverlayGlow');
201 });200 });
202 }201 } else {
203 else {
204 console.debug(DEBUG_PREFIX, 'not installed, unchecked');202 console.debug(DEBUG_PREFIX, 'not installed, unchecked');
205 element.prop('checked', false);203 element.prop('checked', false);
206 element.on('click', assetInstall);204 element.on('click', assetInstall);
@@ -346,8 +344,7 @@ async function installAsset(url, assetType, filename) {
346 console.debug(DEBUG_PREFIX, 'Character downloaded.');344 console.debug(DEBUG_PREFIX, 'Character downloaded.');
347 }345 }
348 }346 }
349 }347 } catch (err) {
350 catch (err) {
351 console.log(err);348 console.log(err);
352 return [];349 return [];
353 }350 }
@@ -373,8 +370,7 @@ async function deleteAsset(assetType, filename) {
373 if (result.ok) {370 if (result.ok) {
374 console.debug(DEBUG_PREFIX, 'Deletion success.');371 console.debug(DEBUG_PREFIX, 'Deletion success.');
375 }372 }
376 }373 } catch (err) {
377 catch (err) {
378 console.log(err);374 console.log(err);
379 return [];375 return [];
380 }376 }
@@ -427,8 +423,7 @@ async function updateCurrentAssets() {
427 headers: getRequestHeaders({ omitContentType: true }),423 headers: getRequestHeaders({ omitContentType: true }),
428 });424 });
429 currentAssets = result.ok ? (await result.json()) : {};425 currentAssets = result.ok ? (await result.json()) : {};
430 }426 } catch (err) {
431 catch (err) {
432 console.log(err);427 console.log(err);
433 }428 }
434 console.debug(DEBUG_PREFIX, 'Current assets found:', currentAssets);429 console.debug(DEBUG_PREFIX, 'Current assets found:', currentAssets);
@@ -490,8 +485,7 @@ jQuery(async () => {
490 connectButton.addClass('fa-plug-circle-exclamation');485 connectButton.addClass('fa-plug-circle-exclamation');
491 connectButton.removeClass('redOverlayGlow');486 connectButton.removeClass('redOverlayGlow');
492 }487 }
493 }488 } else {
494 else {
495 console.debug(DEBUG_PREFIX, 'Connection refused by user');489 console.debug(DEBUG_PREFIX, 'Connection refused by user');
496 }490 }
497 });491 });
public/scripts/extensions/caption/index.js+4 -8
@@ -68,8 +68,7 @@ async function setImageIcon() {
68 const sendButton = $('#send_picture .extensionsMenuExtensionButton');68 const sendButton = $('#send_picture .extensionsMenuExtensionButton');
69 sendButton.addClass('fa-image');69 sendButton.addClass('fa-image');
70 sendButton.removeClass('fa-hourglass-half');70 sendButton.removeClass('fa-hourglass-half');
71 }71 } catch (error) {
72 catch (error) {
73 console.log(error);72 console.log(error);
74 }73 }
75}74}
@@ -82,8 +81,7 @@ async function setSpinnerIcon() {
82 const sendButton = $('#send_picture .extensionsMenuExtensionButton');81 const sendButton = $('#send_picture .extensionsMenuExtensionButton');
83 sendButton.removeClass('fa-image');82 sendButton.removeClass('fa-image');
84 sendButton.addClass('fa-hourglass-half');83 sendButton.addClass('fa-hourglass-half');
85 }84 } catch (error) {
86 catch (error) {
87 console.log(error);85 console.log(error);
88 }86 }
89}87}
@@ -376,14 +374,12 @@ async function getCaptionForFile(file, prompt, quiet) {
376 await sendCaptionedMessage(caption, imagePath, file.type);374 await sendCaptionedMessage(caption, imagePath, file.type);
377 }375 }
378 return caption;376 return caption;
379 }377 } catch (error) {
380 catch (error) {
381 const errorMessage = error.message || 'Unknown error';378 const errorMessage = error.message || 'Unknown error';
382 toastr.error(errorMessage, 'Failed to caption');379 toastr.error(errorMessage, 'Failed to caption');
383 console.error(error);380 console.error(error);
384 return '';381 return '';
385 }382 } finally {
386 finally {
387 setImageIcon();383 setImageIcon();
388 }384 }
389}385}
public/scripts/extensions/expressions/index.js+15 -26
@@ -363,8 +363,7 @@ export async function visualNovelUpdateLayers(container) {
363 if (power_user.reduced_motion) {363 if (power_user.reduced_motion) {
364 element.css('left', currentPosition + 'px');364 element.css('left', currentPosition + 'px');
365 requestAnimationFrame(() => resolve());365 requestAnimationFrame(() => resolve());
366 }366 } else {
367 else {
368 element.animate({ left: currentPosition + 'px' }, 500, () => {367 element.animate({ left: currentPosition + 'px' }, 500, () => {
369 resolve();368 resolve();
370 });369 });
@@ -525,8 +524,7 @@ async function moduleWorker({ newChat = false } = {}) {
525 }524 }
526525
527 return;526 return;
528 }527 } else {
529 else {
530 // force reload expressions list on connect to API528 // force reload expressions list on connect to API
531 if (offlineMode.is(':visible')) {529 if (offlineMode.is(':visible')) {
532 expressionsList = null;530 expressionsList = null;
@@ -599,11 +597,9 @@ async function moduleWorker({ newChat = false } = {}) {
599 }597 }
600598
601 await sendExpressionCall(spriteFolderName, expression, { force: force, vnMode: vnMode });599 await sendExpressionCall(spriteFolderName, expression, { force: force, vnMode: vnMode });
602 }600 } catch (error) {
603 catch (error) {
604 console.log(error);601 console.log(error);
605 }602 } finally {
606 finally {
607 inApiCall = false;603 inApiCall = false;
608 lastCharacter = context.groupId || context.characterId;604 lastCharacter = context.groupId || context.characterId;
609 lastMessage = currentLastMessage.mes;605 lastMessage = currentLastMessage.mes;
@@ -631,8 +627,7 @@ function getFolderNameByMessage(message) {
631627
632 if (context.groupId) {628 if (context.groupId) {
633 avatarPath = message.original_avatar || context.characters.find(x => message.force_avatar && message.force_avatar.includes(encodeURIComponent(x.avatar)))?.avatar;629 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) {
636 avatarPath = getCharaFilename();631 avatarPath = getCharaFilename();
637 }632 }
638633
@@ -1303,8 +1298,7 @@ async function getSpritesList(name) {
1303 }1298 }
13041299
1305 return grouped;1300 return grouped;
1306 }1301 } catch (err) {
1307 catch (err) {
1308 console.log(err);1302 console.log(err);
1309 return [];1303 return [];
1310 }1304 }
@@ -1476,9 +1470,8 @@ function chooseSpriteForExpression(spriteFolderName, expression, { prevExpressio
1476 const searched = sprite.files.find(x => x.fileName === overrideSpriteFile);1470 const searched = sprite.files.find(x => x.fileName === overrideSpriteFile);
1477 if (searched) spriteFile = searched;1471 if (searched) spriteFile = searched;
1478 else toastr.warning(t`Couldn't find sprite file ${overrideSpriteFile} for expression ${expression}.`, t`Sprite Not Found`);1472 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) {
1480 // Else calculate next expression, if multiple are allowed1474 // Else calculate next expression, if multiple are allowed
1481 else if (extension_settings.expressions.allowMultiple && sprite.files.length > 1) {
1482 let possibleFiles = sprite.files;1475 let possibleFiles = sprite.files;
1483 if (extension_settings.expressions.rerollIfSame) {1476 if (extension_settings.expressions.rerollIfSame) {
1484 possibleFiles = possibleFiles.filter(x => !prevExpressionSrc || x.imageSrc !== prevExpressionSrc);1477 possibleFiles = possibleFiles.filter(x => !prevExpressionSrc || x.imageSrc !== prevExpressionSrc);
@@ -1593,8 +1586,7 @@ async function setExpression(spriteFolderName, expression, { force = false, over
1593 }1586 }
15941587
1595 console.info('Expression set', { expression: spriteFile.expression, file: spriteFile.fileName });1588 console.info('Expression set', { expression: spriteFile.expression, file: spriteFile.fileName });
1596 }1589 } else {
1597 else {
1598 img.attr('data-sprite-folder-name', spriteFolderName);1590 img.attr('data-sprite-folder-name', spriteFolderName);
15991591
1600 img.off('error');1592 img.off('error');
@@ -1844,19 +1836,16 @@ async function onClickExpressionUpload(event) {
1844 const fileNameWithoutExtension = withoutExtension(file.name);1836 const fileNameWithoutExtension = withoutExtension(file.name);
1845 const validFileName = validateExpressionSpriteName(expression, fileNameWithoutExtension);1837 const validFileName = validateExpressionSpriteName(expression, fileNameWithoutExtension);
18461838
1847 // If there is no expression yet and it's a valid expression, we just take it
1848 if (!clickedFileName && validFileName) {1839 if (!clickedFileName && validFileName) {
1840 // If there is no expression yet and it's a valid expression, we just take it
1849 spriteName = fileNameWithoutExtension;1841 spriteName = fileNameWithoutExtension;
1850 }1842 } else if (clickedFileName === file.name) {
1851 // If the filename matches the one that was clicked, we just take it and replace it1843 // If the filename matches the one that was clicked, we just take it and replace it
1852 else if (clickedFileName === file.name) {
1853 spriteName = fileNameWithoutExtension;1844 spriteName = fileNameWithoutExtension;
1854 }1845 } else if (!matchesExisting && validFileName) {
1855 // If it's a valid filename and there's no existing file with the same name, we just take it1846 // 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) {
1857 spriteName = fileNameWithoutExtension;1847 spriteName = fileNameWithoutExtension;
1858 }1848 } else {
1859 else {
1860 /** @type {import('../../popup.js').CustomPopupButton[]} */1849 /** @type {import('../../popup.js').CustomPopupButton[]} */
1861 const customButtons = [];1850 const customButtons = [];
1862 if (clickedFileName) {1851 if (clickedFileName) {
public/scripts/extensions/memory/index.js+2 -4
@@ -881,11 +881,9 @@ async function summarizeChatExtras(context) {
881 }881 }
882882
883 setMemoryContext(summary, true);883 setMemoryContext(summary, true);
884 }884 } catch (error) {
885 catch (error) {
886 console.log(error);885 console.log(error);
887 }886 } finally {
888 finally {
889 inApiCall = false;887 inApiCall = false;
890 }888 }
891}889}
public/scripts/extensions/quick-reply/src/QuickReply.js+1 -2
@@ -398,8 +398,7 @@ export class QuickReply {
398 if (this.icon) {398 if (this.icon) {
399 icon.classList.add('fa-solid');399 icon.classList.add('fa-solid');
400 icon.classList.add(this.icon);400 icon.classList.add(this.icon);
401 }401 } else {
402 else {
403 icon.textContent = '…';402 icon.textContent = '…';
404 }403 }
405 icon.addEventListener('click', async () => {404 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) {
3021 const errorText = 'SD prompt text generation failed. ' + reason;3021 const errorText = 'SD prompt text generation failed. ' + reason;
3022 toastr.error(errorText, 'Image Generation');3022 toastr.error(errorText, 'Image Generation');
3023 throw new Error(errorText);3023 throw new Error(errorText);
3024 }3024 } finally {
3025 finally {
3026 $(stopButton).hide();3025 $(stopButton).hide();
3027 restoreOriginalDimensions(dimensions);3026 restoreOriginalDimensions(dimensions);
3028 eventSource.removeListener(CUSTOM_STOP_EVENT, stopListener);3027 eventSource.removeListener(CUSTOM_STOP_EVENT, stopListener);
public/scripts/extensions/tts/coqui.js+4 -8
@@ -497,8 +497,7 @@ class CoquiTtsProvider {
497 const language_label = JSON.stringify(model_settings.languages[i]).replaceAll('"', '');497 const language_label = JSON.stringify(model_settings.languages[i]).replaceAll('"', '');
498 $('#coqui_api_model_settings_language').append(new Option(language_label, i));498 $('#coqui_api_model_settings_language').append(new Option(language_label, i));
499 }499 }
500 }500 } else {
501 else {
502 $('#coqui_api_model_settings_language').hide();501 $('#coqui_api_model_settings_language').hide();
503 }502 }
504503
@@ -516,8 +515,7 @@ class CoquiTtsProvider {
516 const speaker_label = JSON.stringify(model_settings.speakers[i]).replaceAll('"', '');515 const speaker_label = JSON.stringify(model_settings.speakers[i]).replaceAll('"', '');
517 $('#coqui_api_model_settings_speaker').append(new Option(speaker_label, i));516 $('#coqui_api_model_settings_speaker').append(new Option(speaker_label, i));
518 }517 }
519 }518 } else {
520 else {
521 $('#coqui_api_model_settings_speaker').hide();519 $('#coqui_api_model_settings_speaker').hide();
522 }520 }
523521
@@ -536,15 +534,13 @@ class CoquiTtsProvider {
536 if (model_state == 'installed') {534 if (model_state == 'installed') {
537 $('#coqui_api_model_install_status').text('Model already installed on extras server');535 $('#coqui_api_model_install_status').text('Model already installed on extras server');
538 $('#coqui_api_model_install_button').hide();536 $('#coqui_api_model_install_button').hide();
539 }537 } else {
540 else {
541 let action = 'download';538 let action = 'download';
542 if (model_state == 'corrupted') {539 if (model_state == 'corrupted') {
543 action = 'repare';540 action = 'repare';
544 //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 });541 //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 });
545 $('#coqui_api_model_install_status').text('Model found but incomplete try install again (maybe still downloading)'); // (remove and download again)542 $('#coqui_api_model_install_status').text('Model found but incomplete try install again (maybe still downloading)'); // (remove and download again)
546 }543 } else {
547 else {
548 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 });544 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 });
549 $('#coqui_api_model_install_status').text('Model not found on extras server');545 $('#coqui_api_model_install_status').text('Model not found on extras server');
550 }546 }
public/scripts/extensions/tts/index.js+2 -4
@@ -346,8 +346,7 @@ globalThis.tts_preview = function (id) {
346346
347 if (audio instanceof HTMLAudioElement && !$(audio).data('disabled')) {347 if (audio instanceof HTMLAudioElement && !$(audio).data('disabled')) {
348 audio.play();348 audio.play();
349 }349 } else {
350 else {
351 ttsProvider.previewTtsVoice(id);350 ttsProvider.previewTtsVoice(id);
352 }351 }
353};352};
@@ -1452,8 +1451,7 @@ async function initVoiceMapInternal(unrestricted) {
1452 let voiceIdsFromProvider;1451 let voiceIdsFromProvider;
1453 try {1452 try {
1454 voiceIdsFromProvider = await ttsProvider.fetchTtsVoiceObjects();1453 voiceIdsFromProvider = await ttsProvider.fetchTtsVoiceObjects();
1455 }1454 } catch {
1456 catch {
1457 toastr.error('TTS Provider failed to return voice ids.');1455 toastr.error('TTS Provider failed to return voice ids.');
1458 }1456 }
14591457
public/scripts/extensions/tts/system.js+1 -2
@@ -29,8 +29,7 @@ var speechUtteranceChunker = function (utt, settings, callback) {
29 callback();29 callback();
30 }30 }
31 });31 });
32 }32 } else {
33 else {
34 var chunkLength = (settings && settings.chunkLength) || 160;33 var chunkLength = (settings && settings.chunkLength) || 160;
35 var pattRegex = new RegExp('^[\\s\\S]{' + Math.floor(chunkLength / 2) + ',' + chunkLength + '}[.!?,]{1}|^[\\s\\S]{1,' + chunkLength + '}$|^[\\s\\S]{1,' + chunkLength + '} ');34 var pattRegex = new RegExp('^[\\s\\S]{' + Math.floor(chunkLength / 2) + ',' + chunkLength + '}[.!?,]{1}|^[\\s\\S]{1,' + chunkLength + '}$|^[\\s\\S]{1,' + chunkLength + '} ');
36 var chunkArr = txt.match(pattRegex);35 var chunkArr = txt.match(pattRegex);
public/scripts/extensions/tts/vits.js+2 -4
@@ -325,8 +325,7 @@ class VITSTtsProvider {
325 if (streaming) {325 if (streaming) {
326 params.append('streaming', streaming);326 params.append('streaming', streaming);
327 // Streaming response only supports MP3327 // Streaming response only supports MP3
328 }328 } else {
329 else {
330 params.append('format', this.settings.format);329 params.append('format', this.settings.format);
331 }330 }
332 params.append('lang', lang ?? this.settings.lang);331 params.append('lang', lang ?? this.settings.lang);
@@ -337,8 +336,7 @@ class VITSTtsProvider {
337336
338 if (model_type == this.modelTypes.W2V2_VITS) {337 if (model_type == this.modelTypes.W2V2_VITS) {
339 params.append('emotion', this.settings.dim_emotion);338 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) {
342 params.append('sdp_ratio', this.settings.sdp_ratio);340 params.append('sdp_ratio', this.settings.sdp_ratio);
343 params.append('emotion', this.settings.emotion);341 params.append('emotion', this.settings.emotion);
344 if (this.settings.text_prompt) {342 if (this.settings.text_prompt) {
public/scripts/extensions/vectors/index.js+2 -4
@@ -251,8 +251,7 @@ async function summarizeExtra(element) {
251 const data = await apiResult.json();251 const data = await apiResult.json();
252 element.text = data.summary;252 element.text = data.summary;
253 }253 }
254 }254 } catch (error) {
255 catch (error) {
256 console.log(error);255 console.log(error);
257 return false;256 return false;
258 }257 }
@@ -938,8 +937,7 @@ function throwIfSourceInvalid() {
938 if (!settings.alt_endpoint_url) {937 if (!settings.alt_endpoint_url) {
939 throw new Error('Vectors: API URL missing', { cause: 'api_url_missing' });938 throw new Error('Vectors: API URL missing', { cause: 'api_url_missing' });
940 }939 }
941 }940 } else {
942 else {
943 if (settings.source === 'ollama' && !textgenerationwebui_settings.server_urls[textgen_types.OLLAMA] ||941 if (settings.source === 'ollama' && !textgenerationwebui_settings.server_urls[textgen_types.OLLAMA] ||
944 settings.source === 'vllm' && !textgenerationwebui_settings.server_urls[textgen_types.VLLM] ||942 settings.source === 'vllm' && !textgenerationwebui_settings.server_urls[textgen_types.VLLM] ||
945 settings.source === 'koboldcpp' && !textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP] ||943 settings.source === 'koboldcpp' && !textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP] ||
public/scripts/filters.js+1 -2
@@ -328,8 +328,7 @@ export class FilterHelper {
328 // We can filter easily by checking if we have saved a score328 // We can filter easily by checking if we have saved a score
329 const score = _this.getScore(FILTER_TYPES.SEARCH, `${entity.type}.${entity.id}`);329 const score = _this.getScore(FILTER_TYPES.SEARCH, `${entity.type}.${entity.id}`);
330 return score !== undefined;330 return score !== undefined;
331 }331 } else {
332 else {
333 // Compare insensitive and without accents332 // Compare insensitive and without accents
334 return includesIgnoreCaseAndAccents(entity.item?.name, searchValue);333 return includesIgnoreCaseAndAccents(entity.item?.name, searchValue);
335 }334 }
public/scripts/group-chats.js+13 -25
@@ -173,9 +173,8 @@ async function regenerateGroup() {
173 // for new generations after the update173 // for new generations after the update
174 if ((generationId && this_generationId) && generationId !== this_generationId) {174 if ((generationId && this_generationId) && generationId !== this_generationId) {
175 break;175 break;
176 }176 } else if (lastMes.is_user || lastMes.is_system) {
177 // legacy for generations before the update177 // legacy for generations before the update
178 else if (lastMes.is_user || lastMes.is_system) {
179 break;178 break;
180 }179 }
181180
@@ -392,8 +391,7 @@ export function findGroupMemberId(arg, full = false) {
392 console.log(`Targeting group member ${chid} (${arg}) from search result`, result[0]);391 console.log(`Targeting group member ${chid} (${arg}) from search result`, result[0]);
393392
394 return !full ? chid : { ...{ id: chid }, ...result[0].item };393 return !full ? chid : { ...{ id: chid }, ...result[0].item };
395 }394 } else {
396 else {
397 const memberAvatar = group.members[index];395 const memberAvatar = group.members[index];
398396
399 if (memberAvatar === undefined) {397 if (memberAvatar === undefined) {
@@ -744,8 +742,7 @@ export async function renameGroupMember(oldAvatar, newAvatar, newName) {
744 }742 }
745 }743 }
746 }744 }
747 }745 } catch (error) {
748 catch (error) {
749 console.log(`An error during renaming the character ${newName} in group: ${group.name}`);746 console.log(`An error during renaming the character ${newName} in group: ${group.name}`);
750 console.error(error);747 console.error(error);
751 }748 }
@@ -1011,28 +1008,22 @@ async function generateGroupWrapper(byAutoMode, type = null, params = {}) {
1011 if (activatedMembers.length === 0) {1008 if (activatedMembers.length === 0) {
1012 activatedMembers = activateListOrder(group.members.slice(0, 1));1009 activatedMembers = activateListOrder(group.members.slice(0, 1));
1013 }1010 }
1014 }1011 } else if (type === 'swipe' || type === 'continue') {
1015 else if (type === 'swipe' || type === 'continue') {
1016 activatedMembers = activateSwipe(group.members, { allowSystem: false });1012 activatedMembers = activateSwipe(group.members, { allowSystem: false });
10171013
1018 if (activatedMembers.length === 0) {1014 if (activatedMembers.length === 0) {
1019 toastr.warning(t`Deleted group member swiped. To get a reply, add them back to the group.`);1015 toastr.warning(t`Deleted group member swiped. To get a reply, add them back to the group.`);
1020 throw new Error('Deleted group member swiped');1016 throw new Error('Deleted group member swiped');
1021 }1017 }
1022 }1018 } else if (type === 'impersonate') {
1023 else if (type === 'impersonate') {
1024 activatedMembers = activateImpersonate(group.members);1019 activatedMembers = activateImpersonate(group.members);
1025 }1020 } else if (activationStrategy === group_activation_strategy.NATURAL) {
1026 else if (activationStrategy === group_activation_strategy.NATURAL) {
1027 activatedMembers = activateNaturalOrder(enabledMembers, activationText, lastMessage, group.allow_self_responses, isUserInput);1021 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) {
1030 activatedMembers = activateListOrder(enabledMembers);1023 activatedMembers = activateListOrder(enabledMembers);
1031 }1024 } else if (activationStrategy === group_activation_strategy.POOLED) {
1032 else if (activationStrategy === group_activation_strategy.POOLED) {
1033 activatedMembers = activatePooledOrder(enabledMembers, lastMessage, isUserInput);1025 activatedMembers = activatePooledOrder(enabledMembers, lastMessage, isUserInput);
1034 }1026 } else if (activationStrategy === group_activation_strategy.MANUAL && !isUserInput) {
1035 else if (activationStrategy === group_activation_strategy.MANUAL && !isUserInput) {
1036 activatedMembers = shuffle(enabledMembers).slice(0, 1).map(x => characters.findIndex(y => y.avatar === x)).filter(x => x !== -1);1027 activatedMembers = shuffle(enabledMembers).slice(0, 1).map(x => characters.findIndex(y => y.avatar === x)).filter(x => x !== -1);
1037 }1028 }
10381029
@@ -1168,8 +1159,7 @@ function activateSwipe(members, { allowSystem = false } = {}) {
1168 break;1159 break;
1169 }1160 }
1170 }1161 }
1171 }1162 } else {
1172 else {
1173 activatedNames.push(lastMessage.original_avatar);1163 activatedNames.push(lastMessage.original_avatar);
1174 }1164 }
11751165
@@ -1704,8 +1694,7 @@ function getGroupCharacterBlock(character) {
1704 const auxFieldValue = (character.data && character.data[auxFieldName]) || '';1694 const auxFieldValue = (character.data && character.data[auxFieldName]) || '';
1705 if (auxFieldValue) {1695 if (auxFieldValue) {
1706 template.find('.character_version').text(auxFieldValue);1696 template.find('.character_version').text(auxFieldValue);
1707 }1697 } else {
1708 else {
1709 template.find('.character_version').hide();1698 template.find('.character_version').hide();
1710 }1699 }
17111700
@@ -1875,8 +1864,7 @@ function select_group_chats(groupId, skipAnimation) {
1875 if (group) {1864 if (group) {
1876 $('#rm_group_automode_label').show();1865 $('#rm_group_automode_label').show();
1877 $('#rm_button_selected_ch').children('h2').text(groupName);1866 $('#rm_button_selected_ch').children('h2').text(groupName);
1878 }1867 } else {
1879 else {
1880 $('#rm_group_automode_label').hide();1868 $('#rm_group_automode_label').hide();
1881 }1869 }
18821870
public/scripts/horde.js+1 -2
@@ -126,8 +126,7 @@ export async function getStatusHorde() {
126 try {126 try {
127 const hordeStatus = await checkHordeStatus();127 const hordeStatus = await checkHordeStatus();
128 setOnlineStatus(hordeStatus ? t`Connected` : 'no_connection');128 setOnlineStatus(hordeStatus ? t`Connected` : 'no_connection');
129 }129 } catch {
130 catch {
131 setOnlineStatus('no_connection');130 setOnlineStatus('no_connection');
132 }131 }
133132
public/scripts/kai-settings.js+1 -2
@@ -220,8 +220,7 @@ function tryParseStreamingError(response, decoded) {
220 toastr.error(data.error.message || response.statusText, 'KoboldAI API');220 toastr.error(data.error.message || response.statusText, 'KoboldAI API');
221 throw new Error(data);221 throw new Error(data);
222 }222 }
223 }223 } catch {
224 catch {
225 // No JSON. Do nothing.224 // No JSON. Do nothing.
226 }225 }
227}226}
public/scripts/logit-bias.js+4 -10
@@ -117,11 +117,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
117 if (text.startsWith('{') && text.endsWith('}')) {117 if (text.startsWith('{') && text.endsWith('}')) {
118 const tokens = getTextTokens(tokenizerType, text.slice(1, -1));118 const tokens = getTextTokens(tokenizerType, text.slice(1, -1));
119 result.push(getBiasObject(entry.value, tokens));119 result.push(getBiasObject(entry.value, tokens));
120 }120 } else if (text.startsWith('[') && text.endsWith(']')) {
121121 // Raw token ids, JSON serialized
122
123 // Raw token ids, JSON serialized
124 else if (text.startsWith('[') && text.endsWith(']')) {
125 try {122 try {
126 const tokens = JSON.parse(text);123 const tokens = JSON.parse(text);
127124
@@ -133,11 +130,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
133 } catch (err) {130 } catch (err) {
134 console.log(`Failed to parse logit bias token list: ${text}`, err);131 console.log(`Failed to parse logit bias token list: ${text}`, err);
135 }132 }
136 }133 } else {
137134 // Text with a leading space
138
139 // Text with a leading space
140 else {
141 const biasText = ` ${text}`;135 const biasText = ` ${text}`;
142 const tokens = getTextTokens(tokenizerType, biasText);136 const tokens = getTextTokens(tokenizerType, biasText);
143 result.push(getBiasObject(entry.value, tokens));137 result.push(getBiasObject(entry.value, tokens));
public/scripts/macros/engine/MacroCstWalker.js+2 -3
@@ -1001,9 +1001,8 @@ class MacroCstWalker {
1001 endOffset: element.endOffset ?? element.startOffset,1001 endOffset: element.endOffset ?? element.startOffset,
1002 token: element,1002 token: element,
1003 });1003 });
1004 }1004 } else if ('children' in element) {
1005 // Handle nested CstNode (macro or argument)1005 // Handle nested CstNode (macro or argument)
1006 else if ('children' in element) {
1007 const nestedChildren = element.children || {};1006 const nestedChildren = element.children || {};
1008 const nestedEnd = /** @type {IToken?} */ ((nestedChildren['Macro.End'] || [])[0]);1007 const nestedEnd = /** @type {IToken?} */ ((nestedChildren['Macro.End'] || [])[0]);
1009 const nestedStart = /** @type {IToken?} */ ((nestedChildren['Macro.Start'] || [])[0]);1008 const nestedStart = /** @type {IToken?} */ ((nestedChildren['Macro.Start'] || [])[0]);
public/scripts/nai-settings.js+6 -12
@@ -180,8 +180,7 @@ export function loadNovelPreset(preset) {
180 $('#amount_gen').val(preset.max_length).trigger('input');180 $('#amount_gen').val(preset.max_length).trigger('input');
181 $('#max_context_unlocked').prop('checked', needsUnlock).trigger('change');181 $('#max_context_unlocked').prop('checked', needsUnlock).trigger('change');
182 $('#max_context').val(preset.max_context).trigger('input');182 $('#max_context').val(preset.max_context).trigger('input');
183 }183 } else {
184 else {
185 setGenerationParamsFromPreset(preset);184 setGenerationParamsFromPreset(preset);
186 }185 }
187186
@@ -459,10 +458,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
459 if (trimmed.startsWith('{') && trimmed.endsWith('}')) {458 if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
460 const tokens = getTextTokens(tokenizerType, trimmed.slice(1, -1));459 const tokens = getTextTokens(tokenizerType, trimmed.slice(1, -1));
461 result.push(tokens);460 result.push(tokens);
462 }461 } else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
463462 // Raw token ids, JSON serialized
464 // Raw token ids, JSON serialized
465 else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
466 try {463 try {
467 const tokens = JSON.parse(trimmed);464 const tokens = JSON.parse(trimmed);
468465
@@ -474,10 +471,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
474 } catch (err) {471 } catch (err) {
475 console.log(`Failed to parse bad word token list: ${trimmed}`, err);472 console.log(`Failed to parse bad word token list: ${trimmed}`, err);
476 }473 }
477 }474 } else {
478475 // Apply permutations
479 // Apply permutations
480 else {
481 const permutations = getBadWordPermutations(trimmed).map(t => getTextTokens(tokenizerType, t));476 const permutations = getBadWordPermutations(trimmed).map(t => getTextTokens(tokenizerType, t));
482 result.push(...permutations);477 result.push(...permutations);
483 }478 }
@@ -738,8 +733,7 @@ function tryParseStreamingError(response, decoded) {
738 toastr.error(data.message || data.error?.message || response.statusText, 'NovelAI API');733 toastr.error(data.message || data.error?.message || response.statusText, 'NovelAI API');
739 throw new Error(data);734 throw new Error(data);
740 }735 }
741 }736 } catch {
742 catch {
743 // No JSON. Do nothing.737 // No JSON. Do nothing.
744 }738 }
745}739}
public/scripts/openai.js+61 -122
@@ -495,8 +495,7 @@ async function validateReverseProxy() {
495495
496 try {496 try {
497 new URL(oai_settings.reverse_proxy);497 new URL(oai_settings.reverse_proxy);
498 }498 } catch (err) {
499 catch (err) {
500 toastr.error(t`Entered reverse proxy address is not a valid URL`);499 toastr.error(t`Entered reverse proxy address is not a valid URL`);
501 setOnlineStatus('no_connection');500 setOnlineStatus('no_connection');
502 resultCheckStatus();501 resultCheckStatus();
@@ -1551,8 +1550,7 @@ export function tryParseStreamingError(response, decoded, { quiet = false } = {}
1551 !quiet && toastr.error(data.detail?.error?.message || response.statusText, 'Chat Completion API');1550 !quiet && toastr.error(data.detail?.error?.message || response.statusText, 'Chat Completion API');
1552 throw new Error(data);1551 throw new Error(data);
1553 }1552 }
1554 }1553 } catch {
1555 catch {
1556 // No JSON. Do nothing.1554 // No JSON. Do nothing.
1557 }1555 }
1558}1556}
@@ -2868,8 +2866,7 @@ async function sendOpenAIRequest(type, messages, signal, { jsonSchema = null } =
2868 yield { text, swipes: swipes, logprobs: parseChatCompletionLogprobs(parsed), toolCalls: toolCalls, state: state };2866 yield { text, swipes: swipes, logprobs: parseChatCompletionLogprobs(parsed), toolCalls: toolCalls, state: state };
2869 }2867 }
2870 };2868 };
2871 }2869 } else {
2872 else {
2873 const data = await response.json();2870 const data = await response.json();
28742871
2875 checkQuotaError(data);2872 checkQuotaError(data);
@@ -3081,8 +3078,7 @@ async function calculateLogitBias() {
3081 });3078 });
30823079
3083 result = await reply.json();3080 result = await reply.json();
3084 }3081 } catch (err) {
3085 catch (err) {
3086 result = {};3082 result = {};
3087 console.error(err);3083 console.error(err);
3088 }3084 }
@@ -3602,13 +3598,11 @@ export class ChatCompletion {
3602 if (lastMessage && shouldSquash(lastMessage)) {3598 if (lastMessage && shouldSquash(lastMessage)) {
3603 lastMessage.content += '\n' + message.content;3599 lastMessage.content += '\n' + message.content;
3604 lastMessage.tokens = await tokenHandler.countAsync({ role: lastMessage.role, content: lastMessage.content });3600 lastMessage.tokens = await tokenHandler.countAsync({ role: lastMessage.role, content: lastMessage.content });
3605 }3601 } else {
3606 else {
3607 squashedMessages.push(message);3602 squashedMessages.push(message);
3608 lastMessage = message;3603 lastMessage = message;
3609 }3604 }
3610 }3605 } else {
3611 else {
3612 squashedMessages.push(message);3606 squashedMessages.push(message);
3613 lastMessage = message;3607 lastMessage = message;
3614 }3608 }
@@ -4242,8 +4236,7 @@ async function saveOpenAIPreset(name, settings, triggerUi = true) {
4242 Object.assign(openai_settings[value], presetBody);4236 Object.assign(openai_settings[value], presetBody);
4243 $(`#settings_preset_openai option[value="${value}"]`).prop('selected', true);4237 $(`#settings_preset_openai option[value="${value}"]`).prop('selected', true);
4244 if (triggerUi) $('#settings_preset_openai').trigger('change');4238 if (triggerUi) $('#settings_preset_openai').trigger('change');
4245 }4239 } else {
4246 else {
4247 openai_settings.push(presetBody);4240 openai_settings.push(presetBody);
4248 openai_setting_names[data.name] = openai_settings.length - 1;4241 openai_setting_names[data.name] = openai_settings.length - 1;
4249 const option = document.createElement('option');4242 const option = document.createElement('option');
@@ -4692,47 +4685,33 @@ function onSettingsPresetChange() {
4692function getMaxContextOpenAI(value) {4685function getMaxContextOpenAI(value) {
4693 if (oai_settings.max_context_unlocked) {4686 if (oai_settings.max_context_unlocked) {
4694 return unlocked_max;4687 return unlocked_max;
4695 }4688 } else if (value.startsWith('gpt-5')) {
4696 else if (value.startsWith('gpt-5')) {
4697 return max_400k;4689 return max_400k;
4698 }4690 } else if (value.includes('gpt-4.1')) {
4699 else if (value.includes('gpt-4.1')) {
4700 return max_1mil;4691 return max_1mil;
4701 }4692 } else if (value.includes('gpt-audio')) {
4702 else if (value.includes('gpt-audio')) {
4703 return max_128k;4693 return max_128k;
4704 }4694 } else if (value.startsWith('o1')) {
4705 else if (value.startsWith('o1')) {
4706 return max_128k;4695 return max_128k;
4707 }4696 } else if (value.startsWith('o4') || value.startsWith('o3')) {
4708 else if (value.startsWith('o4') || value.startsWith('o3')) {
4709 return max_200k;4697 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')) {
4712 return max_128k;4699 return max_128k;
4713 }4700 } else if (value.includes('gpt-3.5-turbo-1106')) {
4714 else if (value.includes('gpt-3.5-turbo-1106')) {
4715 return max_16k;4701 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)) {
4718 return max_8k;4703 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)) {
4721 return max_32k;4705 return max_32k;
4722 }4706 } else if (value.includes('gpt-realtime')) {
4723 else if (value.includes('gpt-realtime')) {
4724 return max_32k;4707 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)) {
4727 return max_16k;4709 return max_16k;
4728 }4710 } else if (value == 'code-davinci-002') {
4729 else if (value == 'code-davinci-002') {
4730 return max_8k;4711 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)) {
4733 return max_2k;4713 return max_2k;
4734 }4714 } else {
4735 else {
4736 // default to gpt-3 (4095 tokens)4715 // default to gpt-3 (4095 tokens)
4737 return max_4k;4716 return max_4k;
4738 }4717 }
@@ -5269,8 +5248,7 @@ async function onModelChange() {
5269 if (value && (value.includes('claude') || value.includes('palm-2'))) {5248 if (value && (value.includes('claude') || value.includes('palm-2'))) {
5270 oai_settings.temp_openai = Math.min(claude_max_temp, oai_settings.temp_openai);5249 oai_settings.temp_openai = Math.min(claude_max_temp, oai_settings.temp_openai);
5271 $('#temp_openai').attr('max', claude_max_temp).val(oai_settings.temp_openai).trigger('input');5250 $('#temp_openai').attr('max', claude_max_temp).val(oai_settings.temp_openai).trigger('input');
5272 }5251 } else {
5273 else {
5274 oai_settings.temp_openai = Math.min(oai_max_temp, oai_settings.temp_openai);5252 oai_settings.temp_openai = Math.min(oai_max_temp, oai_settings.temp_openai);
5275 $('#temp_openai').attr('max', oai_max_temp).val(oai_settings.temp_openai).trigger('input');5253 $('#temp_openai').attr('max', oai_max_temp).val(oai_settings.temp_openai).trigger('input');
5276 }5254 }
@@ -5281,17 +5259,13 @@ async function onModelChange() {
5281 if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {5259 if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
5282 if (oai_settings.max_context_unlocked) {5260 if (oai_settings.max_context_unlocked) {
5283 $('#openai_max_context').attr('max', unlocked_max);5261 $('#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')) {
5286 $('#openai_max_context').attr('max', max_1mil);5263 $('#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')) {
5289 $('#openai_max_context').attr('max', max_200k);5265 $('#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') {
5292 $('#openai_max_context').attr('max', claude_100k_max);5267 $('#openai_max_context').attr('max', claude_100k_max);
5293 }5268 } else {
5294 else {
5295 $('#openai_max_context').attr('max', claude_max);5269 $('#openai_max_context').attr('max', claude_max);
5296 }5270 }
52975271
@@ -5327,23 +5301,17 @@ async function onModelChange() {
5327 if (oai_settings.chat_completion_source === chat_completion_sources.COHERE) {5301 if (oai_settings.chat_completion_source === chat_completion_sources.COHERE) {
5328 if (oai_settings.max_context_unlocked) {5302 if (oai_settings.max_context_unlocked) {
5329 $('#openai_max_context').attr('max', unlocked_max);5303 $('#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)) {
5332 $('#openai_max_context').attr('max', max_4k);5305 $('#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)) {
5335 $('#openai_max_context').attr('max', max_128k);5307 $('#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)) {
5338 $('#openai_max_context').attr('max', max_256k);5309 $('#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)) {
5341 $('#openai_max_context').attr('max', max_8k);5311 $('#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)) {
5344 $('#openai_max_context').attr('max', max_16k);5313 $('#openai_max_context').attr('max', max_16k);
5345 }5314 } else {
5346 else {
5347 $('#openai_max_context').attr('max', max_4k);5315 $('#openai_max_context').attr('max', max_4k);
5348 }5316 }
5349 oai_settings.openai_max_context = Math.min(Number($('#openai_max_context').attr('max')), oai_settings.openai_max_context);5317 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() {
5354 if (oai_settings.chat_completion_source === chat_completion_sources.PERPLEXITY) {5322 if (oai_settings.chat_completion_source === chat_completion_sources.PERPLEXITY) {
5355 if (oai_settings.max_context_unlocked) {5323 if (oai_settings.max_context_unlocked) {
5356 $('#openai_max_context').attr('max', unlocked_max);5324 $('#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)) {
5359 $('#openai_max_context').attr('max', 127000);5326 $('#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)) {
5362 $('#openai_max_context').attr('max', 200000);5328 $('#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')) {
5365 const isOnline = oai_settings.perplexity_model.includes('online');5330 const isOnline = oai_settings.perplexity_model.includes('online');
5366 const contextSize = isOnline ? 128 * 1024 - 4000 : 128 * 1024;5331 const contextSize = isOnline ? 128 * 1024 - 4000 : 128 * 1024;
5367 $('#openai_max_context').attr('max', contextSize);5332 $('#openai_max_context').attr('max', contextSize);
5368 }5333 } else {
5369 else {
5370 $('#openai_max_context').attr('max', max_128k);5334 $('#openai_max_context').attr('max', max_128k);
5371 }5335 }
5372 oai_settings.openai_max_context = Math.min(Number($('#openai_max_context').attr('max')), oai_settings.openai_max_context);5336 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) {
5660function toggleChatCompletionForms() {5624function toggleChatCompletionForms() {
5661 if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {5625 if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
5662 $('#model_claude_select').trigger('change');5626 $('#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) {
5665 if (oai_settings.show_external_models && (!Array.isArray(model_list) || model_list.length == 0)) {5628 if (oai_settings.show_external_models && (!Array.isArray(model_list) || model_list.length == 0)) {
5666 // Wait until the models list is loaded so that we could show a proper saved model5629 // Wait until the models list is loaded so that we could show a proper saved model
5667 }5630 } else {
5668 else {
5669 $('#model_openai_select').trigger('change');5631 $('#model_openai_select').trigger('change');
5670 }5632 }
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) {
5673 $('#model_google_select').trigger('change');5634 $('#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) {
5676 $('#model_vertexai_select').trigger('change');5636 $('#model_vertexai_select').trigger('change');
5677 // Update UI based on authentication mode5637 // Update UI based on authentication mode
5678 onVertexAIAuthModeChange.call($('#vertexai_auth_mode')[0]);5638 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) {
5681 $('#model_openrouter_select').trigger('change');5640 $('#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) {
5684 $('#model_ai21_select').trigger('change');5642 $('#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) {
5687 $('#model_mistralai_select').trigger('change');5644 $('#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) {
5690 $('#model_cohere_select').trigger('change');5646 $('#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) {
5693 $('#model_perplexity_select').trigger('change');5648 $('#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) {
5696 $('#model_groq_select').trigger('change');5650 $('#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) {
5699 $('#model_chutes_select').trigger('change');5652 $('#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) {
5702 $('#model_siliconflow_select').trigger('change');5654 $('#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) {
5705 $('#model_electronhub_select').trigger('change');5656 $('#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) {
5708 $('#model_nanogpt_select').trigger('change');5658 $('#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) {
5711 $('#model_custom_select').trigger('change');5660 $('#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) {
5714 $('#model_deepseek_select').trigger('change');5662 $('#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) {
5717 $('#model_aimlapi_select').trigger('change');5664 $('#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) {
5720 $('#model_xai_select').trigger('change');5666 $('#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) {
5723 $('#model_pollinations_select').trigger('change');5668 $('#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) {
5726 $('#model_moonshot_select').trigger('change');5670 $('#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) {
5729 $('#model_fireworks_select').trigger('change');5672 $('#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) {
5732 $('#model_cometapi_select').trigger('change');5674 $('#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) {
5735 $('#azure_openai_model').trigger('change');5676 $('#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) {
5738 $('#model_zai_select').trigger('change');5678 $('#model_zai_select').trigger('change');
5739 }5679 }
57405680
@@ -5757,8 +5697,7 @@ async function testApiConnection() {
5757 const reply = await sendOpenAIRequest('quiet', [{ 'role': 'user', 'content': 'Hi' }], new AbortController().signal);5697 const reply = await sendOpenAIRequest('quiet', [{ 'role': 'user', 'content': 'Hi' }], new AbortController().signal);
5758 console.log(reply);5698 console.log(reply);
5759 toastr.success(t`API connection successful!`);5699 toastr.success(t`API connection successful!`);
5760 }5700 } catch (err) {
5761 catch (err) {
5762 toastr.error(t`Could not get a reply from API. Check your connection settings / API key and try again.`);5701 toastr.error(t`Could not get a reply from API. Check your connection settings / API key and try again.`);
5763 }5702 }
5764}5703}
public/scripts/personas.js+2 -3
@@ -1552,9 +1552,8 @@ async function loadPersonaForCurrentChat({ doRender = false } = {}) {
1552 }1552 }
1553 toastr.success(message, t`Persona Auto Selected`, { escapeHtml: false });1553 toastr.success(message, t`Persona Auto Selected`, { escapeHtml: false });
1554 }1554 }
1555 }1555 } else if (chatPersona && power_user.persona_auto_lock && !chat_metadata.persona) {
1556 // Even if it's the same persona, we still might need to auto-lock to chat if that's enabled1556 // 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) {
1558 await lockPersona('chat');1557 await lockPersona('chat');
1559 }1558 }
15601559
public/scripts/power-user.js+18 -30
@@ -810,9 +810,8 @@ async function CreateZenSliders(elmnt) {
810 handle.text(handleText)810 handle.text(handleText)
811 .css('margin-left', `${leftMargin}px`);811 .css('margin-left', `${leftMargin}px`);
812 //console.log(`${newSlider.attr('id')} initial value:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)812 //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') {
814 //handling creation of rep_pen_range for ooba814 //handling creation of rep_pen_range for ooba
815 else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
816 if ($('#rep_pen_range_textgenerationwebui_zensliders').length !== 0) {815 if ($('#rep_pen_range_textgenerationwebui_zensliders').length !== 0) {
817 $('#rep_pen_range_textgenerationwebui_zensliders').remove();816 $('#rep_pen_range_textgenerationwebui_zensliders').remove();
818 }817 }
@@ -821,22 +820,19 @@ async function CreateZenSliders(elmnt) {
821 leftMargin = ((stepNumber) / numSteps) * 50 * -1;820 leftMargin = ((stepNumber) / numSteps) * 50 * -1;
822 if (sliderValue === offVal) {821 if (sliderValue === offVal) {
823 handleText = 'Off';822 handleText = 'Off';
824 handle.css('color', 'rgba(128,128,128,0.5');823 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', ''); }
828 handle.text(handleText)825 handle.text(handleText)
829 .css('margin-left', `${leftMargin}px`);826 .css('margin-left', `${leftMargin}px`);
830 //console.log(sliderValue, handleText, offVal, allVal)827 //console.log(sliderValue, handleText, offVal, allVal)
831 //console.log(`${newSlider.attr('id')} sliderValue = ${sliderValue}, handleText:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)828 //console.log(`${newSlider.attr('id')} sliderValue = ${sliderValue}, handleText:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)
832 originalSlider.val(steps[sliderValue]);829 originalSlider.val(steps[sliderValue]);
833 }830 } else {
834 //create all other sliders831 //create all other sliders
835 else {
836 var numVal = Number(sliderValue).toFixed(decimals);832 var numVal = Number(sliderValue).toFixed(decimals);
837 offVal = Number(offVal).toFixed(decimals);833 offVal = Number(offVal).toFixed(decimals);
838 if (numVal === offVal) {834 if (numVal === offVal) {
839 handle.text('Off').css('color', 'rgba(128,128,128,0.5');835 handle.text('Off').css('color', 'rgba(128,128,128,0.5)');
840 } else {836 } else {
841 handle.text(numVal).css('color', '');837 handle.text(numVal).css('color', '');
842 }838 }
@@ -928,29 +924,24 @@ async function CreateZenSliders(elmnt) {
928 width: ${newSlider.width()}924 width: ${newSlider.width()}
929 percent of max: ${percentOfMax}925 percent of max: ${percentOfMax}
930 left: ${leftPos}`) */926 left: ${leftPos}`) */
931 //special handling for response length slider, pulls text aliases for step values from an array
932 if (newSlider.attr('id') == 'amount_gen_zenslider') {927 if (newSlider.attr('id') == 'amount_gen_zenslider') {
928 //special handling for response length slider, pulls text aliases for step values from an array
933 handleText = steps[stepNumber];929 handleText = steps[stepNumber];
934 handle.text(handleText);930 handle.text(handleText);
935 newSlider.val(stepNumber);931 newSlider.val(stepNumber);
936 numVal = steps[stepNumber];932 numVal = steps[stepNumber];
937 }933 } else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
938 //special handling for TextCompletion rep pen range slider, pulls text aliases for step values from an array934 //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') {
940 handleText = steps[stepNumber];935 handleText = steps[stepNumber];
941 handle.text(handleText);936 handle.text(handleText);
942 newSlider.val(stepNumber);937 newSlider.val(stepNumber);
943 if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5'); }938 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', ''); }
946 numVal = steps[stepNumber];939 numVal = steps[stepNumber];
947 }940 } else {
948 //everything else uses the flat slider value941 //everything else uses the flat slider value
949 //also note: the above sliders are not custom inputtable due to the array aliasing942 //also note: the above sliders are not custom inputtable due to the array aliasing
950 else {
951 //show 'off' if disabled value is set943 //show 'off' if disabled value is set
952 if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5'); }944 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', ''); }
954 newSlider.val(handleText);945 newSlider.val(handleText);
955 }946 }
956 //for manually typed-in values we must adjust left position because JQUI doesn't do it for us947 //for manually typed-in values we must adjust left position because JQUI doesn't do it for us
@@ -991,8 +982,7 @@ function switchSpoilerMode() {
991 $('#firstMessageWrapper').hide();982 $('#firstMessageWrapper').hide();
992 $('#spoiler_free_desc').addClass('flex1');983 $('#spoiler_free_desc').addClass('flex1');
993 $('#creators_note_desc_hidden').show();984 $('#creators_note_desc_hidden').show();
994 }985 } else {
995 else {
996 $('#descriptionWrapper').show();986 $('#descriptionWrapper').show();
997 $('#firstMessageWrapper').show();987 $('#firstMessageWrapper').show();
998 $('#spoiler_free_desc').removeClass('flex1');988 $('#spoiler_free_desc').removeClass('flex1');
@@ -2524,8 +2514,7 @@ async function saveTheme(name = undefined, theme = undefined) {
2524 option.value = name;2514 option.value = name;
2525 option.innerText = name;2515 option.innerText = name;
2526 $('#themes').append(option);2516 $('#themes').append(option);
2527 }2517 } else {
2528 else {
2529 themes[themeIndex] = theme;2518 themes[themeIndex] = theme;
2530 $(`#themes option[value="${name}"]`).prop('selected', true);2519 $(`#themes option[value="${name}"]`).prop('selected', true);
2531 }2520 }
@@ -2632,8 +2621,7 @@ async function saveMovingUI() {
2632 option.value = name;2621 option.value = name;
2633 option.innerText = name;2622 option.innerText = name;
2634 $('#movingUIPresets').append(option);2623 $('#movingUIPresets').append(option);
2635 }2624 } else {
2636 else {
2637 movingUIPresets[movingUIPresetIndex] = movingUIPreset;2625 movingUIPresets[movingUIPresetIndex] = movingUIPreset;
2638 $(`#movingUIPresets option[value="${name}"]`).prop('selected', true);2626 $(`#movingUIPresets option[value="${name}"]`).prop('selected', true);
2639 }2627 }
public/scripts/preset-manager.js+2 -4
@@ -608,15 +608,13 @@ class PresetManager {
608 presets[preset_names.indexOf(name)] = preset;608 presets[preset_names.indexOf(name)] = preset;
609 $(this.select).find(`option[value="${name}"]`).prop('selected', true);609 $(this.select).find(`option[value="${name}"]`).prop('selected', true);
610 $(this.select).val(name).trigger('change');610 $(this.select).val(name).trigger('change');
611 }611 } else {
612 else {
613 const value = preset_names[name];612 const value = preset_names[name];
614 presets[value] = preset;613 presets[value] = preset;
615 $(this.select).find(`option[value="${value}"]`).prop('selected', true);614 $(this.select).find(`option[value="${value}"]`).prop('selected', true);
616 $(this.select).val(value).trigger('change');615 $(this.select).val(value).trigger('change');
617 }616 }
618 }617 } else {
619 else {
620 presets.push(preset);618 presets.push(preset);
621 const value = presets.length - 1;619 const value = presets.length - 1;
622620
public/scripts/samplerSelect.js+1 -3
@@ -246,9 +246,7 @@ async function listSamplers(main_api, arrayOnly = false) {
246246
247 if (prioritizeManualSamplerSelect) {247 if (prioritizeManualSamplerSelect) {
248 finalState = isManuallyActivated;248 finalState = isManuallyActivated;
249 }249 } else if (!isInDefaultState) {
250
251 else if (!isInDefaultState) {
252 finalState = displayModified === SELECT_SAMPLER.SHOWN;250 finalState = displayModified === SELECT_SAMPLER.SHOWN;
253 customColor = finalState ? forcedOnColoring : forcedOffColoring;251 customColor = finalState ? forcedOnColoring : forcedOffColoring;
254 }252 }
public/scripts/slash-commands.js+4 -8
@@ -3026,8 +3026,7 @@ export function initDefaultSlashCommands() {
3026 try {3026 try {
3027 const text = await navigator.clipboard.readText();3027 const text = await navigator.clipboard.readText();
3028 return text;3028 return text;
3029 }3029 } catch (error) {
3030 catch (error) {
3031 console.error('Error reading clipboard:', error);3030 console.error('Error reading clipboard:', error);
3032 toastr.warning(t`Failed to read clipboard text. Have you granted the permission?`);3031 toastr.warning(t`Failed to read clipboard text. Have you granted the permission?`);
3033 return '';3032 return '';
@@ -4432,8 +4431,7 @@ async function sendUserMessageCallback(args, text) {
4432 const name = args.name || '';4431 const name = args.name || '';
4433 const avatar = findPersonaByName(name) || user_avatar;4432 const avatar = findPersonaByName(name) || user_avatar;
4434 message = await sendMessageAsUser(text, bias, insertAt, compact, name, avatar);4433 message = await sendMessageAsUser(text, bias, insertAt, compact, name, avatar);
4435 }4434 } else {
4436 else {
4437 message = await sendMessageAsUser(text, bias, insertAt, compact);4435 message = await sendMessageAsUser(text, bias, insertAt, compact);
4438 }4436 }
44394437
@@ -4640,12 +4638,10 @@ export function getNameAndAvatarForMessage(character, name = null) {
4640 let force_avatar, original_avatar;4638 let force_avatar, original_avatar;
4641 if (character?.avatar === currentChar?.avatar || isNeutralCharacter) {4639 if (character?.avatar === currentChar?.avatar || isNeutralCharacter) {
4642 // If the targeted character is the currently selected one in a solo chat, we don't need to force any avatars4640 // 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') {
4645 force_avatar = getThumbnailUrl('avatar', character.avatar);4642 force_avatar = getThumbnailUrl('avatar', character.avatar);
4646 original_avatar = character.avatar;4643 original_avatar = character.avatar;
4647 }4644 } else {
4648 else {
4649 force_avatar = default_avatar;4645 force_avatar = default_avatar;
4650 original_avatar = default_avatar;4646 original_avatar = default_avatar;
4651 }4647 }
public/scripts/sse-stream.js+20 -32
@@ -111,8 +111,8 @@ function getDelay(s) {
111 * @returns {AsyncGenerator<{data: object, chunk: string, reasoning?: boolean}>} The parsed data and the chunk to be sent.111 * @returns {AsyncGenerator<{data: object, chunk: string, reasoning?: boolean}>} The parsed data and the chunk to be sent.
112 */112 */
113async function* parseStreamData(json) {113async function* parseStreamData(json) {
114 // Cohere
115 if (typeof json.delta === 'object' && typeof json.delta.message === 'object' && ['tool-plan-delta', 'content-delta'].includes(json.type)) {114 if (typeof json.delta === 'object' && typeof json.delta.message === 'object' && ['tool-plan-delta', 'content-delta'].includes(json.type)) {
115 // Cohere
116 const text = json?.delta?.message?.content?.text ?? '';116 const text = json?.delta?.message?.content?.text ?? '';
117 for (let i = 0; i < text.length; i++) {117 for (let i = 0; i < text.length; i++) {
118 const str = json.delta.message.content.text[i];118 const str = json.delta.message.content.text[i];
@@ -122,9 +122,8 @@ async function* parseStreamData(json) {
122 };122 };
123 }123 }
124 return;124 return;
125 }125 } else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
126 // Claude126 // Claude
127 else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
128 if (json.delta.text.length > 0) {127 if (json.delta.text.length > 0) {
129 for (let i = 0; i < json.delta.text.length; i++) {128 for (let i = 0; i < json.delta.text.length; i++) {
130 const str = json.delta.text[i];129 const str = json.delta.text[i];
@@ -135,8 +134,8 @@ async function* parseStreamData(json) {
135 }134 }
136 }135 }
137 return;136 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)
140 if (json.delta.thinking.length > 0) {139 if (json.delta.thinking.length > 0) {
141 for (let i = 0; i < json.delta.thinking.length; i++) {140 for (let i = 0; i < json.delta.thinking.length; i++) {
142 const str = json.delta.thinking[i];141 const str = json.delta.thinking[i];
@@ -148,9 +147,8 @@ async function* parseStreamData(json) {
148 }147 }
149 }148 }
150 return;149 return;
151 }150 } else if (Array.isArray(json.candidates)) {
152 // MakerSuite151 // Google VertexAI / AI Studio
153 else if (Array.isArray(json.candidates)) {
154 for (let i = 0; i < json.candidates.length; i++) {152 for (let i = 0; i < json.candidates.length; i++) {
155 const isNotPrimary = json.candidates?.[0]?.index > 0;153 const isNotPrimary = json.candidates?.[0]?.index > 0;
156 const hasToolCalls = json?.candidates?.[0]?.content?.parts?.some(p => p?.functionCall);154 const hasToolCalls = json?.candidates?.[0]?.content?.parts?.some(p => p?.functionCall);
@@ -187,9 +185,8 @@ async function* parseStreamData(json) {
187 }185 }
188 }186 }
189 return;187 return;
190 }188 } else if (typeof json.token === 'string' && json.token.length > 0) {
191 // NovelAI / KoboldCpp Classic189 // NovelAI / KoboldCpp Classic
192 else if (typeof json.token === 'string' && json.token.length > 0) {
193 for (let i = 0; i < json.token.length; i++) {190 for (let i = 0; i < json.token.length; i++) {
194 const str = json.token[i];191 const str = json.token[i];
195 yield {192 yield {
@@ -198,9 +195,8 @@ async function* parseStreamData(json) {
198 };195 };
199 }196 }
200 return;197 return;
201 }198 } else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
202 // llama.cpp?199 // llama.cpp?
203 else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
204 const isNotPrimary = json?.index > 0;200 const isNotPrimary = json?.index > 0;
205 if (isNotPrimary) {201 if (isNotPrimary) {
206 throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });202 throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -213,9 +209,8 @@ async function* parseStreamData(json) {
213 };209 };
214 }210 }
215 return;211 return;
216 }212 } else if (Array.isArray(json.choices)) {
217 // OpenAI-likes213 // OpenAI-likes and friends
218 else if (Array.isArray(json.choices)) {
219 const isNotPrimary = json?.choices?.[0]?.index > 0;214 const isNotPrimary = json?.choices?.[0]?.index > 0;
220 if (isNotPrimary || json.choices.length === 0) {215 if (isNotPrimary || json.choices.length === 0) {
221 throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });216 throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -233,8 +228,7 @@ async function* parseStreamData(json) {
233 };228 };
234 }229 }
235 return;230 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) {
238 for (let j = 0; j < json.choices[0].thinking.length; j++) {232 for (let j = 0; j < json.choices[0].thinking.length; j++) {
239 const str = json.choices[0].thinking[j];233 const str = json.choices[0].thinking[j];
240 const choiceClone = structuredClone(json.choices[0]);234 const choiceClone = structuredClone(json.choices[0]);
@@ -247,8 +241,7 @@ async function* parseStreamData(json) {
247 };241 };
248 }242 }
249 return;243 return;
250 }244 } else if (typeof json.choices[0].delta === 'object') {
251 else if (typeof json.choices[0].delta === 'object') {
252 if (typeof json.choices[0].delta.text === 'string' && json.choices[0].delta.text.length > 0) {245 if (typeof json.choices[0].delta.text === 'string' && json.choices[0].delta.text.length > 0) {
253 for (let j = 0; j < json.choices[0].delta.text.length; j++) {246 for (let j = 0; j < json.choices[0].delta.text.length; j++) {
254 const str = json.choices[0].delta.text[j];247 const str = json.choices[0].delta.text[j];
@@ -261,8 +254,7 @@ async function* parseStreamData(json) {
261 };254 };
262 }255 }
263 return;256 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) {
266 for (let j = 0; j < json.choices[0].delta.reasoning_content.length; j++) {258 for (let j = 0; j < json.choices[0].delta.reasoning_content.length; j++) {
267 const str = json.choices[0].delta.reasoning_content[j];259 const str = json.choices[0].delta.reasoning_content[j];
268 const isLastSymbol = j === json.choices[0].delta.reasoning_content.length - 1;260 const isLastSymbol = j === json.choices[0].delta.reasoning_content.length - 1;
@@ -277,8 +269,7 @@ async function* parseStreamData(json) {
277 };269 };
278 }270 }
279 return;271 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) {
282 for (let j = 0; j < json.choices[0].delta.reasoning.length; j++) {273 for (let j = 0; j < json.choices[0].delta.reasoning.length; j++) {
283 const str = json.choices[0].delta.reasoning[j];274 const str = json.choices[0].delta.reasoning[j];
284 const isLastSymbol = j === json.choices[0].delta.reasoning.length - 1;275 const isLastSymbol = j === json.choices[0].delta.reasoning.length - 1;
@@ -293,8 +284,7 @@ async function* parseStreamData(json) {
293 };284 };
294 }285 }
295 return;286 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) {
298 for (let j = 0; j < json.choices[0].delta.content.length; j++) {288 for (let j = 0; j < json.choices[0].delta.content.length; j++) {
299 const str = json.choices[0].delta.content[j];289 const str = json.choices[0].delta.content[j];
300 const choiceClone = structuredClone(json.choices[0]);290 const choiceClone = structuredClone(json.choices[0]);
@@ -306,8 +296,7 @@ async function* parseStreamData(json) {
306 };296 };
307 }297 }
308 return;298 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) {
311 if (Array.isArray(json.choices[0].delta.content[0].thinking) && json.choices[0].delta.content[0].thinking.length > 0) {300 if (Array.isArray(json.choices[0].delta.content[0].thinking) && json.choices[0].delta.content[0].thinking.length > 0) {
312 if (typeof json.choices[0].delta.content[0].thinking[0].text === 'string' && json.choices[0].delta.content[0].thinking[0].text.length > 0) {301 if (typeof json.choices[0].delta.content[0].thinking[0].text === 'string' && json.choices[0].delta.content[0].thinking[0].text.length > 0) {
313 for (let j = 0; j < json.choices[0].delta.content[0].thinking[0].text.length; j++) {302 for (let j = 0; j < json.choices[0].delta.content[0].thinking[0].text.length; j++) {
@@ -325,8 +314,7 @@ async function* parseStreamData(json) {
325 }314 }
326 }315 }
327 }316 }
328 }317 } else if (typeof json.choices[0].message === 'object') {
329 else if (typeof json.choices[0].message === 'object') {
330 if (typeof json.choices[0].message.content === 'string' && json.choices[0].message.content.length > 0) {318 if (typeof json.choices[0].message.content === 'string' && json.choices[0].message.content.length > 0) {
331 for (let j = 0; j < json.choices[0].message.content.length; j++) {319 for (let j = 0; j < json.choices[0].message.content.length; j++) {
332 const str = json.choices[0].message.content[j];320 const str = json.choices[0].message.content[j];
public/scripts/stats.js+1 -2
@@ -209,8 +209,7 @@ async function recreateStats() {
209 if (!response.ok) {209 if (!response.ok) {
210 toastr.error('Stats could not be loaded. Try reloading the page.');210 toastr.error('Stats could not be loaded. Try reloading the page.');
211 throw new Error('Error getting stats');211 throw new Error('Error getting stats');
212 }212 } else {
213 else {
214 toastr.success('Stats file recreated successfully!');213 toastr.success('Stats file recreated successfully!');
215 }214 }
216}215}
public/scripts/tags.js+2 -4
@@ -858,8 +858,7 @@ function addTagToMap(tagId, characterId = null) {
858 if (!Array.isArray(tag_map[key])) {858 if (!Array.isArray(tag_map[key])) {
859 tag_map[key] = [tagId];859 tag_map[key] = [tagId];
860 return true;860 return true;
861 }861 } else {
862 else {
863 if (tag_map[key].includes(tagId))862 if (tag_map[key].includes(tagId))
864 return false;863 return false;
865864
@@ -885,8 +884,7 @@ function removeTagFromMap(tagId, characterId = null) {
885 if (!Array.isArray(tag_map[key])) {884 if (!Array.isArray(tag_map[key])) {
886 tag_map[key] = [];885 tag_map[key] = [];
887 return false;886 return false;
888 }887 } else {
889 else {
890 const indexOf = tag_map[key].indexOf(tagId);888 const indexOf = tag_map[key].indexOf(tagId);
891 tag_map[key].splice(indexOf, 1);889 tag_map[key].splice(indexOf, 1);
892 return indexOf !== -1;890 return indexOf !== -1;
public/scripts/textgen-models.js+3 -6
@@ -541,14 +541,11 @@ export async function loadFeatherlessModels(data) {
541541
542 if (selectedCategory === 'All') {542 if (selectedCategory === 'All') {
543 return matchesSearch && matchesClass;543 return matchesSearch && matchesClass;
544 }544 } else if (selectedCategory === 'Top') {
545 else if (selectedCategory === 'Top') {
546 return matchesSearch && matchesClass && matchesTop;545 return matchesSearch && matchesClass && matchesTop;
547 }546 } else if (selectedCategory === 'New') {
548 else if (selectedCategory === 'New') {
549 return matchesSearch && matchesClass && matchesNew;547 return matchesSearch && matchesClass && matchesNew;
550 }548 } else {
551 else {
552 return matchesSearch && matchesClass;549 return matchesSearch && matchesClass;
553 }550 }
554 });551 });
public/scripts/textgen-settings.js+4 -8
@@ -1040,12 +1040,10 @@ export function initTextGenSettings() {
1040 if (isCheckbox) {1040 if (isCheckbox) {
1041 const value = $(this).prop('checked');1041 const value = $(this).prop('checked');
1042 textgenerationwebui_settings[id] = value;1042 textgenerationwebui_settings[id] = value;
1043 }1043 } else if (isText) {
1044 else if (isText) {
1045 const value = $(this).val();1044 const value = $(this).val();
1046 textgenerationwebui_settings[id] = value;1045 textgenerationwebui_settings[id] = value;
1047 }1046 } else {
1048 else {
1049 const value = Number($(this).val());1047 const value = Number($(this).val());
1050 $(`#${id}_counter_textgenerationwebui`).val(value);1048 $(`#${id}_counter_textgenerationwebui`).val(value);
1051 textgenerationwebui_settings[id] = value;1049 textgenerationwebui_settings[id] = value;
@@ -1254,11 +1252,9 @@ function setSettingByName(setting, value, trigger) {
1254 if ('send_banned_tokens' === setting) {1252 if ('send_banned_tokens' === setting) {
1255 $(`#${setting}_textgenerationwebui`).trigger('change');1253 $(`#${setting}_textgenerationwebui`).trigger('change');
1256 }1254 }
1257 }1255 } else if (isText) {
1258 else if (isText) {
1259 $(`#${setting}_textgenerationwebui`).val(value);1256 $(`#${setting}_textgenerationwebui`).val(value);
1260 }1257 } else {
1261 else {
1262 const val = parseFloat(value);1258 const val = parseFloat(value);
1263 $(`#${setting}_textgenerationwebui`).val(val);1259 $(`#${setting}_textgenerationwebui`).val(val);
1264 $(`#${setting}_counter_textgenerationwebui`).val(val);1260 $(`#${setting}_counter_textgenerationwebui`).val(val);
public/scripts/tokenizers.js+31 -64
@@ -603,47 +603,34 @@ export function getTokenizerModel() {
603603
604 if (model?.architecture?.tokenizer === 'Llama2') {604 if (model?.architecture?.tokenizer === 'Llama2') {
605 return llamaTokenizer;605 return llamaTokenizer;
606 }606 } else if (model?.architecture?.tokenizer === 'Llama3') {
607 else if (model?.architecture?.tokenizer === 'Llama3') {
608 return llama3Tokenizer;607 return llama3Tokenizer;
609 }608 } else if (model?.architecture?.tokenizer === 'Mistral') {
610 else if (model?.architecture?.tokenizer === 'Mistral') {
611 return mistralTokenizer;609 return mistralTokenizer;
612 }610 } else if (model?.architecture?.tokenizer === 'Yi') {
613 else if (model?.architecture?.tokenizer === 'Yi') {
614 return yiTokenizer;611 return yiTokenizer;
615 }612 } else if (model?.architecture?.tokenizer === 'Gemini') {
616 else if (model?.architecture?.tokenizer === 'Gemini') {
617 return gemmaTokenizer;613 return gemmaTokenizer;
618 }614 } else if (model?.architecture?.tokenizer === 'Qwen') {
619 else if (model?.architecture?.tokenizer === 'Qwen') {
620 return qwen2Tokenizer;615 return qwen2Tokenizer;
621 }616 } else if (model?.architecture?.tokenizer === 'Cohere') {
622 else if (model?.architecture?.tokenizer === 'Cohere') {
623 if (model?.id && model?.id.includes('command-a')) {617 if (model?.id && model?.id.includes('command-a')) {
624 return commandATokenizer;618 return commandATokenizer;
625 }619 }
626 return commandRTokenizer;620 return commandRTokenizer;
627 }621 } else if (oai_settings.openrouter_model.includes('gpt-4o')) {
628 else if (oai_settings.openrouter_model.includes('gpt-4o')) {
629 return gpt4oTokenizer;622 return gpt4oTokenizer;
630 }623 } else if (oai_settings.openrouter_model.includes('gpt-4')) {
631 else if (oai_settings.openrouter_model.includes('gpt-4')) {
632 return gpt4Tokenizer;624 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')) {
635 return turboTokenizer;626 return turboTokenizer;
636 }627 } else if (oai_settings.openrouter_model.includes('claude')) {
637 else if (oai_settings.openrouter_model.includes('claude')) {
638 return claudeTokenizer;628 return claudeTokenizer;
639 }629 } else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
640 else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
641 return gpt2Tokenizer;630 return gpt2Tokenizer;
642 }631 } else if (oai_settings.openrouter_model.includes('jamba')) {
643 else if (oai_settings.openrouter_model.includes('jamba')) {
644 return jambaTokenizer;632 return jambaTokenizer;
645 }633 } else if (oai_settings.openrouter_model.includes('deepseek')) {
646 else if (oai_settings.openrouter_model.includes('deepseek')) {
647 return deepseekTokenizer;634 return deepseekTokenizer;
648 }635 }
649 }636 }
@@ -651,50 +638,35 @@ export function getTokenizerModel() {
651 if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB && oai_settings.electronhub_model) {638 if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB && oai_settings.electronhub_model) {
652 if (oai_settings.electronhub_model.includes('gpt-4o') || oai_settings.electronhub_model.includes('gpt-5')) {639 if (oai_settings.electronhub_model.includes('gpt-4o') || oai_settings.electronhub_model.includes('gpt-5')) {
653 return gpt4oTokenizer;640 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')) {
656 return gpt4oTokenizer;642 return gpt4oTokenizer;
657 }643 } else if (oai_settings.electronhub_model.includes('gpt-4')) {
658 else if (oai_settings.electronhub_model.includes('gpt-4')) {
659 return gpt4Tokenizer;644 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')) {
662 return turboTokenizer;646 return turboTokenizer;
663 }647 } else if (oai_settings.electronhub_model.includes('claude')) {
664 else if (oai_settings.electronhub_model.includes('claude')) {
665 return claudeTokenizer;648 return claudeTokenizer;
666 }649 } else if (oai_settings.electronhub_model.includes('jamba')) {
667 else if (oai_settings.electronhub_model.includes('jamba')) {
668 return jambaTokenizer;650 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')) {
671 return deepseekTokenizer;652 return deepseekTokenizer;
672 }653 } else if (oai_settings.electronhub_model.includes('qwen')) {
673 else if (oai_settings.electronhub_model.includes('qwen')) {
674 return qwen2Tokenizer;654 return qwen2Tokenizer;
675 }655 } else if (oai_settings.electronhub_model.includes('gemma')) {
676 else if (oai_settings.electronhub_model.includes('gemma')) {
677 return gemmaTokenizer;656 return gemmaTokenizer;
678 }657 } else if (oai_settings.electronhub_model.includes('mistral')) {
679 else if (oai_settings.electronhub_model.includes('mistral')) {
680 return mistralTokenizer;658 return mistralTokenizer;
681 }659 } else if (oai_settings.electronhub_model.includes('yi')) {
682 else if (oai_settings.electronhub_model.includes('yi')) {
683 return yiTokenizer;660 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')) {
686 return llama3Tokenizer;662 return llama3Tokenizer;
687 }663 } else if (oai_settings.electronhub_model.includes('llama')) {
688 else if (oai_settings.electronhub_model.includes('llama')) {
689 return llamaTokenizer;664 return llamaTokenizer;
690 }665 } else if (oai_settings.electronhub_model.includes('command-a')) {
691 else if (oai_settings.electronhub_model.includes('command-a')) {
692 return commandATokenizer;666 return commandATokenizer;
693 }667 } else if (oai_settings.electronhub_model.includes('command-r')) {
694 else if (oai_settings.electronhub_model.includes('command-r')) {
695 return commandRTokenizer;668 return commandRTokenizer;
696 }669 } else if (oai_settings.electronhub_model.includes('nemo')) {
697 else if (oai_settings.electronhub_model.includes('nemo')) {
698 return nemoTokenizer;670 return nemoTokenizer;
699 }671 }
700 }672 }
@@ -814,9 +786,7 @@ export function countTokensOpenAI(messages, full = false) {
814786
815 if (typeof cachedCount === 'number') {787 if (typeof cachedCount === 'number') {
816 token_count += cachedCount;788 token_count += cachedCount;
817 }789 } else {
818
819 else {
820 jQuery.ajax({790 jQuery.ajax({
821 async: false,791 async: false,
822 type: 'POST', //792 type: 'POST', //
@@ -866,9 +836,7 @@ export async function countTokensOpenAIAsync(messages, full = false) {
866836
867 if (typeof cachedCount === 'number') {837 if (typeof cachedCount === 'number') {
868 token_count += cachedCount;838 token_count += cachedCount;
869 }839 } else {
870
871 else {
872 const data = await jQuery.ajax({840 const data = await jQuery.ajax({
873 async: true,841 async: true,
874 type: 'POST', //842 type: 'POST', //
@@ -898,8 +866,7 @@ function getTokenCacheObject() {
898 try {866 try {
899 if (selected_group) {867 if (selected_group) {
900 chatId = groups.find(x => x.id == selected_group)?.chat_id;868 chatId = groups.find(x => x.id == selected_group)?.chat_id;
901 }869 } else if (this_chid !== undefined) {
902 else if (this_chid !== undefined) {
903 chatId = characters[this_chid].chat;870 chatId = characters[this_chid].chat;
904 }871 }
905 } catch {872 } catch {
public/scripts/user.js+1 -2
@@ -327,8 +327,7 @@ async function changePassword(handle, callback) {
327327
328 toastr.success('Password changed successfully', 'Password Changed');328 toastr.success('Password changed successfully', 'Password Changed');
329 callback();329 callback();
330 }330 } catch (error) {
331 catch (error) {
332 console.error('Error changing password:', error);331 console.error('Error changing password:', error);
333 }332 }
334}333}
public/scripts/util/SimpleMutex.js+1 -2
@@ -36,8 +36,7 @@ export class SimpleMutex {
36 try {36 try {
37 this.isBusy = true;37 this.isBusy = true;
38 await this.callback(...args);38 await this.callback(...args);
39 }39 } finally {
40 finally {
41 this.isBusy = false;40 this.isBusy = false;
42 }41 }
43 }42 }
public/scripts/variables.js+1 -2
@@ -388,8 +388,7 @@ async function timesCallback(args, value) {
388 command.breakController = new SlashCommandBreakController();388 command.breakController = new SlashCommandBreakController();
389 command.scope.setMacro('timesIndex', i);389 command.scope.setMacro('timesIndex', i);
390 result = await command.execute();390 result = await command.execute();
391 }391 } else {
392 else {
393 result = await executeSubCommands(command.replace(/\{\{timesIndex\}\}/g, i.toString()), args._scope, args._parserFlags, args._abortController);392 result = await executeSubCommands(command.replace(/\{\{timesIndex\}\}/g, i.toString()), args._scope, args._parserFlags, args._abortController);
394 }393 }
395 if (result.isAborted) break;394 if (result.isAborted) break;
public/scripts/welcome-screen.js+1 -2
@@ -716,8 +716,7 @@ export async function openPermanentAssistantChat({ tryCreate = true, created = f
716 console.log(`Character not found for avatar ID: ${avatar}. Creating new assistant.`);716 console.log(`Character not found for avatar ID: ${avatar}. Creating new assistant.`);
717 await createPermanentAssistant();717 await createPermanentAssistant();
718 return openPermanentAssistantChat({ tryCreate: false, created: true });718 return openPermanentAssistantChat({ tryCreate: false, created: true });
719 }719 } catch (error) {
720 catch (error) {
721 console.error('Error creating permanent assistant:', error);720 console.error('Error creating permanent assistant:', error);
722 toastr.error(t`Failed to create ${neutralCharacterName}. See console for details.`);721 toastr.error(t`Failed to create ${neutralCharacterName}. See console for details.`);
723 return;722 return;
public/scripts/world-info.js+7 -14
@@ -351,8 +351,7 @@ class WorldInfoBuffer {
351351
352 if (keyWords.length > 1) {352 if (keyWords.length > 1) {
353 return haystack.includes(transformedString);353 return haystack.includes(transformedString);
354 }354 } else {
355 else {
356 // Use custom boundaries to include punctuation and other non-alphanumeric characters355 // Use custom boundaries to include punctuation and other non-alphanumeric characters
357 const regex = new RegExp(`(?:^|\\W)(${escapeRegex(transformedString)})(?:$|\\W)`);356 const regex = new RegExp(`(?:^|\\W)(${escapeRegex(transformedString)})(?:$|\\W)`);
358 if (regex.test(haystack)) {357 if (regex.test(haystack)) {
@@ -1141,8 +1140,7 @@ function registerWorldInfoSlashCommands() {
1141 // Also assign the book now - additional if requested, otherwise as primary1140 // Also assign the book now - additional if requested, otherwise as primary
1142 if (type === 'additional') {1141 if (type === 'additional') {
1143 await charUpdateAddAuxWorld(character.avatar, newName);1142 await charUpdateAddAuxWorld(character.avatar, newName);
1144 }1143 } else {
1145 else {
1146 await charUpdatePrimaryWorld(newName);1144 await charUpdatePrimaryWorld(newName);
1147 }1145 }
1148 // Refresh UI, if needed1146 // Refresh UI, if needed
@@ -2169,8 +2167,7 @@ export function sortWorldInfoEntries(data, { customSort = null } = {}) {
2169 const bScore = worldInfoFilter.getScore(FILTER_TYPES.WORLD_INFO_SEARCH, b.uid);2167 const bScore = worldInfoFilter.getScore(FILTER_TYPES.WORLD_INFO_SEARCH, b.uid);
2170 return aScore - bScore;2168 return aScore - bScore;
2171 };2169 };
2172 }2170 } else if (sortRule === 'custom') {
2173 else if (sortRule === 'custom') {
2174 // First by display index2171 // First by display index
2175 primarySort = (a, b) => {2172 primarySort = (a, b) => {
2176 const aValue = a.displayIndex;2173 const aValue = a.displayIndex;
@@ -4434,8 +4431,7 @@ export async function getSortedEntries() {
44344431
4435 // Need to deep clone the entries to avoid modifying the cached data4432 // Need to deep clone the entries to avoid modifying the cached data
4436 return structuredClone(entries);4433 return structuredClone(entries);
4437 }4434 } catch (e) {
4438 catch (e) {
4439 console.error(e);4435 console.error(e);
4440 return [];4436 return [];
4441 }4437 }
@@ -4481,8 +4477,7 @@ function parseDecorators(content) {
4481 if (isKnownDecorator(splited[i])) {4477 if (isKnownDecorator(splited[i])) {
4482 decorators.push(splited[i].startsWith('@@@') ? splited[i].substring(1) : splited[i]);4478 decorators.push(splited[i].startsWith('@@@') ? splited[i].substring(1) : splited[i]);
4483 fallbacked = false;4479 fallbacked = false;
4484 }4480 } else {
4485 else {
4486 fallbacked = true;4481 fallbacked = true;
4487 }4482 }
4488 } else {4483 } else {
@@ -5506,8 +5501,7 @@ export function checkEmbeddedWorld(chid) {
5506 }5501 }
5507 };5502 };
5508 callGenericPopup(html, POPUP_TYPE.CONFIRM, '', { okButton: 'Yes' }).then(checkResult);5503 callGenericPopup(html, POPUP_TYPE.CONFIRM, '', { okButton: 'Yes' }).then(checkResult);
5509 }5504 } else {
5510 else {
5511 toastr.info(5505 toastr.info(
5512 'To import and use it, select "Import Card Lore" in the "More..." dropdown menu on the character panel.',5506 'To import and use it, select "Import Card Lore" in the "More..." dropdown menu on the character panel.',
5513 `${characters[chid].name} has an embedded World/Lorebook`,5507 `${characters[chid].name} has an embedded World/Lorebook`,
@@ -6121,8 +6115,7 @@ export function initWorldInfo() {
6121 } else if (hasEmbed && !event.shiftKey) {6115 } else if (hasEmbed && !event.shiftKey) {
6122 await importEmbeddedWorldInfo();6116 await importEmbeddedWorldInfo();
6123 saveCharacterDebounced();6117 saveCharacterDebounced();
6124 }6118 } else {
6125 else {
6126 openSetWorldMenu();6119 openSetWorldMenu();
6127 }6120 }
6128 });6121 });
src/endpoints/assets.js+5 -10
@@ -173,8 +173,7 @@ router.post('/get', async (request, response) => {
173 }173 }
174 }174 }
175 }175 }
176 }176 } catch (err) {
177 catch (err) {
178 console.error(err);177 console.error(err);
179 }178 }
180 return response.send(output);179 return response.send(output);
@@ -255,8 +254,7 @@ router.post('/download', async (request, response) => {
255 fs.copyFileSync(temp_path, file_path);254 fs.copyFileSync(temp_path, file_path);
256 fs.unlinkSync(temp_path);255 fs.unlinkSync(temp_path);
257 response.sendStatus(200);256 response.sendStatus(200);
258 }257 } catch (error) {
259 catch (error) {
260 console.error(error);258 console.error(error);
261 response.sendStatus(500);259 response.sendStatus(500);
262 }260 }
@@ -299,15 +297,13 @@ router.post('/delete', async (request, response) => {
299 if (err) throw err;297 if (err) throw err;
300 });298 });
301 console.info('Asset deleted.');299 console.info('Asset deleted.');
302 }300 } else {
303 else {
304 console.error('Asset not found.');301 console.error('Asset not found.');
305 response.sendStatus(400);302 response.sendStatus(400);
306 }303 }
307 // Move into asset place304 // Move into asset place
308 response.sendStatus(200);305 response.sendStatus(200);
309 }306 } catch (error) {
310 catch (error) {
311 console.error(error);307 console.error(error);
312 response.sendStatus(500);308 response.sendStatus(500);
313 }309 }
@@ -372,8 +368,7 @@ router.post('/character', async (request, response) => {
372 output.push(`/characters/${name}/${category}/${i}`);368 output.push(`/characters/${name}/${category}/${i}`);
373 }369 }
374 return response.send(output);370 return response.send(output);
375 }371 } catch (err) {
376 catch (err) {
377 console.error(err);372 console.error(err);
378 return response.sendStatus(500);373 return response.sendStatus(500);
379 }374 }
src/endpoints/backends/chat-completions.js+3 -6
@@ -1425,8 +1425,7 @@ async function sendElectronHubRequest(request, response) {
1425 console.debug('Electron Hub response:', generateResponseJson);1425 console.debug('Electron Hub response:', generateResponseJson);
1426 return response.send(generateResponseJson);1426 return response.send(generateResponseJson);
1427 }1427 }
1428 }1428 } catch (error) {
1429 catch (error) {
1430 console.error('Error communicating with Electron Hub: ', error);1429 console.error('Error communicating with Electron Hub: ', error);
1431 if (!response.headersSent) {1430 if (!response.headersSent) {
1432 response.send({ error: true });1431 response.send({ error: true });
@@ -1527,8 +1526,7 @@ async function sendChutesRequest(request, response) {
1527 console.debug('Chutes response:', generateResponseJson);1526 console.debug('Chutes response:', generateResponseJson);
1528 return response.send(generateResponseJson);1527 return response.send(generateResponseJson);
1529 }1528 }
1530 }1529 } catch (error) {
1531 catch (error) {
1532 console.error('Error communicating with Chutes: ', error);1530 console.error('Error communicating with Chutes: ', error);
1533 if (!response.headersSent) {1531 if (!response.headersSent) {
1534 response.send({ error: true });1532 response.send({ error: true });
@@ -1910,8 +1908,7 @@ router.post('/status', async function (request, statusResponse) {
1910 console.warn('Chat Completion endpoint did not return a list of models.');1908 console.warn('Chat Completion endpoint did not return a list of models.');
1911 }1909 }
1912 }1910 }
1913 }1911 } else {
1914 else {
1915 console.error('Chat Completion status check failed. Either Access Token is incorrect or API endpoint is down.');1912 console.error('Chat Completion status check failed. Either Access Token is incorrect or API endpoint is down.');
1916 statusResponse.send({ error: true, data: { data: [] } });1913 statusResponse.send({ error: true, data: { data: [] } });
1917 }1914 }
src/endpoints/backends/text-completions.js+1 -2
@@ -405,8 +405,7 @@ router.post('/generate', async function (request, response) {
405 const completionsStream = await fetch(url, args);405 const completionsStream = await fetch(url, args);
406 // Pipe remote SSE stream to Express response406 // Pipe remote SSE stream to Express response
407 forwardFetchResponse(completionsStream, response);407 forwardFetchResponse(completionsStream, response);
408 }408 } else {
409 else {
410 const completionsReply = await fetch(url, args);409 const completionsReply = await fetch(url, args);
411410
412 if (completionsReply.ok) {411 if (completionsReply.ok) {
src/endpoints/backups.js+2 -4
@@ -45,8 +45,7 @@ router.post('/chat/delete', async (request, response) => {
4545
46 await fsPromises.unlink(filePath);46 await fsPromises.unlink(filePath);
47 return response.sendStatus(200);47 return response.sendStatus(200);
48 }48 } catch (error) {
49 catch (error) {
50 console.error(error);49 console.error(error);
51 return response.sendStatus(500);50 return response.sendStatus(500);
52 }51 }
@@ -67,8 +66,7 @@ router.post('/chat/download', async (request, response) => {
67 }66 }
6867
69 return response.download(filePath);68 return response.download(filePath);
70 }69 } catch (error) {
71 catch (error) {
72 console.error(error);70 console.error(error);
73 return response.sendStatus(500);71 return response.sendStatus(500);
74 }72 }
src/endpoints/characters.js+6 -11
@@ -326,9 +326,8 @@ async function tryReadImage(imgPath, crop) {
326 try {326 try {
327 const rawImg = await Jimp.read(imgPath);327 const rawImg = await Jimp.read(imgPath);
328 return await applyAvatarCropResize(rawImg, crop);328 return await applyAvatarCropResize(rawImg, crop);
329 }329 } catch (error) {
330 // If it's an unsupported type of image (APNG) - just read the file as buffer330 // If it's an unsupported type of image (APNG) - just read the file as buffer
331 catch (error) {
332 console.error(`Failed to read image: ${imgPath}`, error);331 console.error(`Failed to read image: ${imgPath}`, error);
333 return fs.readFileSync(imgPath);332 return fs.readFileSync(imgPath);
334 }333 }
@@ -423,8 +422,7 @@ const processCharacter = async (item, directories, { shallow }) => {
423 character.date_last_chat = dateLastChat;422 character.date_last_chat = dateLastChat;
424 character.data_size = calculateDataSize(jsonObject?.data);423 character.data_size = calculateDataSize(jsonObject?.data);
425 return shallow ? toShallow(character) : character;424 return shallow ? toShallow(character) : character;
426 }425 } catch (err) {
427 catch (err) {
428 console.error(`Could not process character: ${item}`);426 console.error(`Could not process character: ${item}`);
429427
430 if (err instanceof SyntaxError) {428 if (err instanceof SyntaxError) {
@@ -1081,8 +1079,7 @@ router.post('/rename', validateAvatarUrlMiddleware, async function (request, res
10811079
1082 // Return new avatar name to ST1080 // Return new avatar name to ST
1083 return response.send({ avatar: newAvatarName });1081 return response.send({ avatar: newAvatarName });
1084 }1082 } catch (err) {
1085 catch (err) {
1086 console.error(err);1083 console.error(err);
1087 return response.sendStatus(500);1084 return response.sendStatus(500);
1088 }1085 }
@@ -1495,8 +1492,7 @@ router.post('/duplicate', validateAvatarUrlMiddleware, async function (request,
1495 fs.copyFileSync(filename, newFilename);1492 fs.copyFileSync(filename, newFilename);
1496 console.info(`${filename} was copied to ${newFilename}`);1493 console.info(`${filename} was copied to ${newFilename}`);
1497 response.send({ path: path.parse(newFilename).base });1494 response.send({ path: path.parse(newFilename).base });
1498 }1495 } catch (error) {
1499 catch (error) {
1500 console.error(error);1496 console.error(error);
1501 return response.send({ error: true });1497 return response.send({ error: true });
1502 }1498 }
@@ -1532,8 +1528,7 @@ router.post('/export', validateAvatarUrlMiddleware, async function (request, res
1532 const jsonObject = getCharaCardV2(JSON.parse(json), request.user.directories);1528 const jsonObject = getCharaCardV2(JSON.parse(json), request.user.directories);
1533 unsetPrivateFields(jsonObject);1529 unsetPrivateFields(jsonObject);
1534 return response.type('json').send(JSON.stringify(jsonObject, null, 4));1530 return response.type('json').send(JSON.stringify(jsonObject, null, 4));
1535 }1531 } catch {
1536 catch {
1537 return response.sendStatus(400);1532 return response.sendStatus(400);
1538 }1533 }
1539 }1534 }
src/endpoints/chats.js+1 -2
@@ -837,8 +837,7 @@ router.post('/group/save', async function (request, response) {
837 if (Array.isArray(chatData)) {837 if (Array.isArray(chatData)) {
838 await trySaveChat(chatData, chatFilePath, request.body.force, handle, String(id), request.user.directories.backups);838 await trySaveChat(chatData, chatFilePath, request.body.force, handle, String(id), request.user.directories.backups);
839 return response.send({ ok: true });839 return response.send({ ok: true });
840 }840 } else {
841 else {
842 return response.status(400).send({ error: 'The request\'s body.chat is not an array.' });841 return response.status(400).send({ error: 'The request\'s body.chat is not an array.' });
843 }842 }
844 } catch (error) {843 } catch (error) {
src/endpoints/content-manager.js+4 -8
@@ -941,12 +941,10 @@ router.post('/importURL', async (request, response) => {
941 if (chubParsed?.type === 'character') {941 if (chubParsed?.type === 'character') {
942 console.info('Downloading chub character:', chubParsed.id);942 console.info('Downloading chub character:', chubParsed.id);
943 result = await downloadChubCharacter(chubParsed.id);943 result = await downloadChubCharacter(chubParsed.id);
944 }944 } else if (chubParsed?.type === 'lorebook') {
945 else if (chubParsed?.type === 'lorebook') {
946 console.info('Downloading chub lorebook:', chubParsed.id);945 console.info('Downloading chub lorebook:', chubParsed.id);
947 result = await downloadChubLorebook(chubParsed.id);946 result = await downloadChubLorebook(chubParsed.id);
948 }947 } else {
949 else {
950 return response.sendStatus(404);948 return response.sendStatus(404);
951 }949 }
952 } else if (isRisu) {950 } else if (isRisu) {
@@ -1020,12 +1018,10 @@ router.post('/importUUID', async (request, response) => {
1020 if (uuidType === 'character') {1018 if (uuidType === 'character') {
1021 console.info('Downloading chub character:', uuid);1019 console.info('Downloading chub character:', uuid);
1022 result = await downloadChubCharacter(uuid);1020 result = await downloadChubCharacter(uuid);
1023 }1021 } else if (uuidType === 'lorebook') {
1024 else if (uuidType === 'lorebook') {
1025 console.info('Downloading chub lorebook:', uuid);1022 console.info('Downloading chub lorebook:', uuid);
1026 result = await downloadChubLorebook(uuid);1023 result = await downloadChubLorebook(uuid);
1027 }1024 } else {
1028 else {
1029 return response.sendStatus(404);1025 return response.sendStatus(404);
1030 }1026 }
1031 }1027 }
src/endpoints/groups.js+1 -2
@@ -145,8 +145,7 @@ router.post('/all', (request, response) => {
145 group.date_last_chat = date_last_chat;145 group.date_last_chat = date_last_chat;
146 group.chat_size = chat_size;146 group.chat_size = chat_size;
147 groups.push(group);147 groups.push(group);
148 }148 } catch (error) {
149 catch (error) {
150 console.error(error);149 console.error(error);
151 }150 }
152 });151 });
src/endpoints/horde.js+1 -2
@@ -113,8 +113,7 @@ router.post('/text-models', async (request, response) => {
113 try {113 try {
114 const metadata = await getHordeTextModelMetadata();114 const metadata = await getHordeTextModelMetadata();
115 data = await mergeModelsAndMetadata(data, metadata);115 data = await mergeModelsAndMetadata(data, metadata);
116 }116 } catch (error) {
117 catch (error) {
118 console.error('Failed to fetch metadata:', error);117 console.error('Failed to fetch metadata:', error);
119 }118 }
120119
src/endpoints/novelai.js+3 -6
@@ -154,8 +154,7 @@ router.post('/status', async function (req, res) {
154 } else if (response.status == 401) {154 } else if (response.status == 401) {
155 console.error('NovelAI Access Token is incorrect.');155 console.error('NovelAI Access Token is incorrect.');
156 return res.send({ error: true });156 return res.send({ error: true });
157 }157 } else {
158 else {
159 console.warn('NovelAI returned an error:', response.statusText);158 console.warn('NovelAI returned an error:', response.statusText);
160 return res.send({ error: true });159 return res.send({ error: true });
161 }160 }
@@ -281,8 +280,7 @@ router.post('/generate', async function (req, res) {
281 try {280 try {
282 const data = JSON.parse(text);281 const data = JSON.parse(text);
283 message = data.message;282 message = data.message;
284 }283 } catch {
285 catch {
286 // ignore284 // ignore
287 }285 }
288286
@@ -476,8 +474,7 @@ router.post('/generate-voice', async (request, response) => {
476 const buffer = Buffer.concat(chunks.map(chunk => new Uint8Array(chunk)));474 const buffer = Buffer.concat(chunks.map(chunk => new Uint8Array(chunk)));
477 response.setHeader('Content-Type', 'audio/mpeg');475 response.setHeader('Content-Type', 'audio/mpeg');
478 return response.send(buffer);476 return response.send(buffer);
479 }477 } catch (error) {
480 catch (error) {
481 console.error(error);478 console.error(error);
482 return response.sendStatus(500);479 return response.sendStatus(500);
483 }480 }
src/endpoints/openai.js+1 -2
@@ -262,8 +262,7 @@ router.post('/caption-image', async (request, response) => {
262 }262 }
263263
264 return response.json({ caption });264 return response.json({ caption });
265 }265 } catch (error) {
266 catch (error) {
267 console.error(error);266 console.error(error);
268 response.status(500).send('Internal server error');267 response.status(500).send('Internal server error');
269 }268 }
src/endpoints/settings.js+1 -2
@@ -58,8 +58,7 @@ function readAndParseFromDirectory(directoryPath, fileExtension = '.json') {
58 try {58 try {
59 const file = fs.readFileSync(path.join(directoryPath, item), 'utf-8');59 const file = fs.readFileSync(path.join(directoryPath, item), 'utf-8');
60 parsedFiles.push(fileExtension == '.json' ? JSON.parse(file) : file);60 parsedFiles.push(fileExtension == '.json' ? JSON.parse(file) : file);
61 }61 } catch {
62 catch {
63 // skip62 // skip
64 }63 }
65 });64 });
src/endpoints/sprites.js+1 -2
@@ -143,8 +143,7 @@ router.get('/get', function (request, response) {
143 };143 };
144 });144 });
145 }145 }
146 }146 } catch (err) {
147 catch (err) {
148 console.error(err);147 console.error(err);
149 }148 }
150 return response.send(sprites);149 return response.send(sprites);
src/endpoints/stable-diffusion.js+4 -8
@@ -1316,8 +1316,7 @@ chutes.post('/models', async (request, response) => {
1316 const chutesData = /** @type {{items: Array<{name: string}>}} */ (data);1316 const chutesData = /** @type {{items: Array<{name: string}>}} */ (data);
1317 const models = chutesData.items.map(x => ({ value: x.name, text: x.name })).sort((a, b) => a?.text?.localeCompare(b?.text));1317 const models = chutesData.items.map(x => ({ value: x.name, text: x.name })).sort((a, b) => a?.text?.localeCompare(b?.text));
1318 return response.send(models);1318 return response.send(models);
1319 }1319 } catch (error) {
1320 catch (error) {
1321 console.error(error);1320 console.error(error);
1322 return response.sendStatus(500);1321 return response.sendStatus(500);
1323 }1322 }
@@ -1363,8 +1362,7 @@ chutes.post('/generate', async (request, response) => {
1363 const base64 = Buffer.from(buffer).toString('base64');1362 const base64 = Buffer.from(buffer).toString('base64');
13641363
1365 return response.send({ image: base64 });1364 return response.send({ image: base64 });
1366 }1365 } catch (error) {
1367 catch (error) {
1368 console.error(error);1366 console.error(error);
1369 return response.sendStatus(500);1367 return response.sendStatus(500);
1370 }1368 }
@@ -1405,8 +1403,7 @@ nanogpt.post('/models', async (request, response) => {
14051403
1406 const models = Object.values(imageModels).map(x => ({ value: x.model, text: x.name }));1404 const models = Object.values(imageModels).map(x => ({ value: x.model, text: x.name }));
1407 return response.send(models);1405 return response.send(models);
1408 }1406 } catch (error) {
1409 catch (error) {
1410 console.error(error);1407 console.error(error);
1411 return response.sendStatus(500);1408 return response.sendStatus(500);
1412 }1409 }
@@ -1447,8 +1444,7 @@ nanogpt.post('/generate', async (request, response) => {
1447 }1444 }
14481445
1449 return response.send({ image });1446 return response.send({ image });
1450 }1447 } catch (error) {
1451 catch (error) {
1452 console.error(error);1448 console.error(error);
1453 return response.sendStatus(500);1449 return response.sendStatus(500);
1454 }1450 }
src/prompt-converters.js+3 -6
@@ -939,8 +939,7 @@ export function mergeMessages(messages, names, { strict = false, placeholders =
939 if (mergedMessages.length && placeholders) {939 if (mergedMessages.length && placeholders) {
940 if (mergedMessages[0].role === 'system' && (mergedMessages.length === 1 || mergedMessages[1].role !== 'user')) {940 if (mergedMessages[0].role === 'system' && (mergedMessages.length === 1 || mergedMessages[1].role !== 'user')) {
941 mergedMessages.splice(1, 0, { role: 'user', content: PROMPT_PLACEHOLDER });941 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') {
944 mergedMessages.unshift({ role: 'user', content: PROMPT_PLACEHOLDER });943 mergedMessages.unshift({ role: 'user', content: PROMPT_PLACEHOLDER });
945 }944 }
946 }945 }
@@ -964,11 +963,9 @@ export function convertTextCompletionPrompt(messages) {
964 messages.forEach(m => {963 messages.forEach(m => {
965 if (m.role === 'system' && m.name === undefined) {964 if (m.role === 'system' && m.name === undefined) {
966 messageStrings.push('System: ' + m.content);965 messageStrings.push('System: ' + m.content);
967 }966 } else if (m.role === 'system' && m.name !== undefined) {
968 else if (m.role === 'system' && m.name !== undefined) {
969 messageStrings.push(m.name + ': ' + m.content);967 messageStrings.push(m.name + ': ' + m.content);
970 }968 } else {
971 else {
972 messageStrings.push(m.role + ': ' + m.content);969 messageStrings.push(m.role + ': ' + m.content);
973 }970 }
974 });971 });
src/users.js+1 -2
@@ -680,8 +680,7 @@ export async function getUserAvatar(handle) {
680 const mimeType = mime.lookup(avatarPath);680 const mimeType = mime.lookup(avatarPath);
681 const base64Content = fs.readFileSync(avatarPath, 'base64');681 const base64Content = fs.readFileSync(avatarPath, 'base64');
682 return `data:${mimeType};base64,${base64Content}`;682 return `data:${mimeType};base64,${base64Content}`;
683 }683 } catch {
684 catch {
685 // Ignore errors684 // Ignore errors
686 return PUBLIC_USER_AVATAR;685 return PUBLIC_USER_AVATAR;
687 }686 }
src/util.js+3 -6
@@ -157,8 +157,7 @@ export async function getVersion() {
157 const remoteLatest = await git.revparse([trackingBranch]);157 const remoteLatest = await git.revparse([trackingBranch]);
158 isLatest = localLatest === remoteLatest;158 isLatest = localLatest === remoteLatest;
159 }159 }
160 }160 } catch {
161 catch {
162 // suppress exception161 // suppress exception
163 }162 }
164163
@@ -821,8 +820,7 @@ export function mergeObjectWithYaml(obj, yamlString) {
821 Object.assign(obj, item);820 Object.assign(obj, item);
822 }821 }
823 }822 }
824 }823 } else if (parsedObject && typeof parsedObject === 'object') {
825 else if (parsedObject && typeof parsedObject === 'object') {
826 Object.assign(obj, parsedObject);824 Object.assign(obj, parsedObject);
827 }825 }
828 } catch {826 } catch {
@@ -1307,8 +1305,7 @@ export function safeReadFileSync(filePath, options = { encoding: 'utf-8' }) {
1307export function setWindowTitle(title) {1305export function setWindowTitle(title) {
1308 if (process.platform === 'win32') {1306 if (process.platform === 'win32') {
1309 process.title = title;1307 process.title = title;
1310 }1308 } else {
1311 else {
1312 process.stdout.write(`\x1b]2;${title}\x1b\x5c`);1309 process.stdout.write(`\x1b]2;${title}\x1b\x5c`);
1313 }1310 }
1314}1311}
src/vectors/extras-vectors.js+1 -2
@@ -34,8 +34,7 @@ async function getExtrasVectorImpl(text, apiUrl, apiKey) {
34 try {34 try {
35 url = new URL(apiUrl);35 url = new URL(apiUrl);
36 url.pathname = '/api/embeddings/compute';36 url.pathname = '/api/embeddings/compute';
37 }37 } catch (error) {
38 catch (error) {
39 console.error('Failed to set up Extras API call:', error);38 console.error('Failed to set up Extras API call:', error);
40 console.debug('Extras API URL given was:', apiUrl);39 console.debug('Extras API URL given was:', apiUrl);
41 throw error;40 throw error;