Chore: enable brace-style eslint check (#5159)

* eslint: enable brace-style check

* Fix jsdoc and color

* fix: correct CSS color syntax in CreateZenSliders function
This commit is contained in:
Cohee
2026-02-15 01:46:32 +02:00
committed by GitHub
parent 357da3219b
commit 4d1619ba47
62 changed files with 344 additions and 676 deletions
+1 -1
View File
@@ -102,8 +102,8 @@ module.exports = {
// These rules should eventually be enabled. // These rules should eventually be enabled.
'no-async-promise-executor': 'off', 'no-async-promise-executor': 'off',
'no-inner-declarations': 'off', 'no-inner-declarations': 'off',
'brace-style': 'off',
// Additional formatting rules based on codebase conventions // Additional formatting rules based on codebase conventions
'brace-style': ['error', '1tbs', { allowSingleLine: true }],
'array-bracket-spacing': ['error', 'never'], 'array-bracket-spacing': ['error', 'never'],
'computed-property-spacing': ['error', 'never'], 'computed-property-spacing': ['error', 'never'],
'block-spacing': ['error', 'always'], 'block-spacing': ['error', 'always'],
+1 -2
View File
@@ -89,8 +89,7 @@ async function installPlugin(pluginName) {
await git().clone(pluginName, pluginPath, { '--depth': 1 }); await git().clone(pluginName, pluginPath, { '--depth': 1 });
console.log(`Plugin ${color.green(pluginName)} installed to ${color.cyan(pluginPath)}`); console.log(`Plugin ${color.green(pluginName)} installed to ${color.cyan(pluginPath)}`);
} } catch (error) {
catch (error) {
console.error(color.red(`Failed to install plugin ${pluginName}`), error); console.error(color.red(`Failed to install plugin ${pluginName}`), error);
} }
} }
+57 -121
View File
@@ -512,8 +512,7 @@ export function reloadMarkdownProcessor() {
export function getCurrentChatId() { export function getCurrentChatId() {
if (selected_group) { if (selected_group) {
return groups.find(x => x.id == selected_group)?.chat_id; return groups.find(x => x.id == selected_group)?.chat_id;
} } else if (this_chid !== undefined) {
else if (this_chid !== undefined) {
return characters[this_chid]?.chat; return characters[this_chid]?.chat;
} }
} }
@@ -910,8 +909,7 @@ function getCharacterBlock(item, id) {
const description = item.data?.creator_notes || ''; const description = item.data?.creator_notes || '';
if (description) { if (description) {
template.find('.ch_description').text(description); template.find('.ch_description').text(description);
} } else {
else {
template.find('.ch_description').hide(); template.find('.ch_description').hide();
} }
@@ -919,8 +917,7 @@ function getCharacterBlock(item, id) {
const auxFieldValue = (item.data && item.data[auxFieldName]) || ''; const auxFieldValue = (item.data && item.data[auxFieldName]) || '';
if (auxFieldValue) { if (auxFieldValue) {
template.find('.character_version').text(auxFieldValue); template.find('.character_version').text(auxFieldValue);
} } else {
else {
template.find('.character_version').hide(); template.find('.character_version').hide();
} }
@@ -1364,16 +1361,14 @@ export async function replaceCurrentChat() {
const chats = Object.values(await chatsResponse.json()); const chats = Object.values(await chatsResponse.json());
chats.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes))); chats.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes)));
// pick existing chat
if (chats.length && typeof chats[0] === 'object') { if (chats.length && typeof chats[0] === 'object') {
// pick existing chat
characters[this_chid].chat = chats[0].file_name.replace('.jsonl', ''); characters[this_chid].chat = chats[0].file_name.replace('.jsonl', '');
$('#selected_chat_pole').val(characters[this_chid].chat); $('#selected_chat_pole').val(characters[this_chid].chat);
saveCharacterDebounced(); saveCharacterDebounced();
await getChat(); await getChat();
} } else {
// start new chat
// start new chat
else {
characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`; characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
$('#selected_chat_pole').val(characters[this_chid].chat); $('#selected_chat_pole').val(characters[this_chid].chat);
saveCharacterDebounced(); saveCharacterDebounced();
@@ -1640,11 +1635,9 @@ export async function reloadCurrentChatUnsafe() {
if (selected_group) { if (selected_group) {
await getGroupChat(selected_group, true); await getGroupChat(selected_group, true);
} } else if (this_chid !== undefined) {
else if (this_chid !== undefined) {
await getChat(); await getChat();
} } else {
else {
resetChatState(); resetChatState();
restoreNeutralChat(); restoreNeutralChat();
await getCharacters(); await getCharacters();
@@ -1870,32 +1863,16 @@ export function messageFormatting(mes, ch_name, isSystem, isUser, messageId, san
/** /**
* Inserts or replaces an SVG icon adjacent to the provided message's timestamp. * Inserts or replaces an SVG icon adjacent to the provided message's timestamp.
* *
* If the `extra.api` is "openai" and `extra.model` contains the substring "claude",
* the function fetches the "claude.svg". Otherwise, it fetches the SVG named after
* the value in `extra.api`.
*
* @param {JQuery<HTMLElement>} mes - The message element containing the timestamp where the icon should be inserted or replaced. * @param {JQuery<HTMLElement>} mes - The message element containing the timestamp where the icon should be inserted or replaced.
* @param {ChatMessageExtra} extra - Contains the API and model details. * @param {ChatMessageExtra} extra - Contains the API and model details.
*/ */
function insertSVGIcon(mes, extra) { function insertSVGIcon(mes, extra) {
// Determine the SVG filename // Determine the SVG filename
let modelName; let modelName = extra?.api || '';
// Claude on OpenRouter or Anthropic // If there's no API information, we can't determine which SVG to use
if (extra.api === 'openai' && extra.model?.toLowerCase().includes('claude')) { if (!modelName) {
modelName = 'claude'; return;
}
// OpenAI on OpenRouter
else if (extra.api === 'openai' && extra.model?.toLowerCase().includes('openai')) {
modelName = 'openai';
}
// OpenRouter website model or other models
else if (extra.api === 'openai' && (extra.model === null || extra.model?.toLowerCase().includes('/'))) {
modelName = 'openrouter';
}
// Everything else
else {
modelName = extra.api;
} }
const insertOrReplaceSVG = (image, className, targetSelector, insertBefore) => { const insertOrReplaceSVG = (image, className, targetSelector, insertBefore) => {
@@ -3755,8 +3732,7 @@ class StreamingProcessor {
} }
const seconds = (timestamps[timestamps.length - 1] - timestamps[0]) / 1000; const seconds = (timestamps[timestamps.length - 1] - timestamps[0]) / 1000;
console.warn(`Stream stats: ${timestamps.length} tokens, ${seconds.toFixed(2)} seconds, rate: ${Number(timestamps.length / seconds).toFixed(2)} TPS`); console.warn(`Stream stats: ${timestamps.length} tokens, ${seconds.toFixed(2)} seconds, rate: ${Number(timestamps.length / seconds).toFixed(2)} TPS`);
} } catch (err) {
catch (err) {
// in the case of a self-inflicted abort, we have already cleaned up // in the case of a self-inflicted abort, we have already cleaned up
if (!this.isFinished) { if (!this.isFinished) {
console.error(err); console.error(err);
@@ -4236,8 +4212,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
textareaText = ''; textareaText = '';
if (chat.length && lastMessage.is_user) { if (chat.length && lastMessage.is_user) {
//do nothing? why does this check exist? //do nothing? why does this check exist?
} } else if (type !== 'quiet' && type !== 'swipe' && !isImpersonate && !dryRun && !depth && chat.length) {
else if (type !== 'quiet' && type !== 'swipe' && !isImpersonate && !dryRun && !depth && chat.length) {
deleteItemizedPromptForMessage(chat.length - 1); deleteItemizedPromptForMessage(chat.length - 1);
chat.length = chat.length - 1; chat.length = chat.length - 1;
await removeLastMessage(); await removeLastMessage();
@@ -4282,12 +4257,10 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
// If user message contains no text other than bias - send as a system message // If user message contains no text other than bias - send as a system message
if (messageBias && !removeMacros(textareaText)) { if (messageBias && !removeMacros(textareaText)) {
sendSystemMessage(system_message_types.GENERIC, ' ', { bias: messageBias }); sendSystemMessage(system_message_types.GENERIC, ' ', { bias: messageBias });
} } else {
else {
await sendMessageAsUser(textareaText, messageBias); await sendMessageAsUser(textareaText, messageBias);
} }
} } else if (textareaText == '' && !automatic_trigger && !dryRun && [undefined, 'normal'].includes(type) && main_api == 'openai' && oai_settings.send_if_empty.trim().length > 0 && !depth) {
else if (textareaText == '' && !automatic_trigger && !dryRun && [undefined, 'normal'].includes(type) && main_api == 'openai' && oai_settings.send_if_empty.trim().length > 0 && !depth) {
// Use send_if_empty if set and the user message is empty. Only when sending messages normally // Use send_if_empty if set and the user message is empty. Only when sending messages normally
await sendMessageAsUser(oai_settings.send_if_empty.trim(), messageBias); await sendMessageAsUser(oai_settings.send_if_empty.trim(), messageBias);
} }
@@ -4406,8 +4379,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
if (main_api == 'koboldhorde' && (horde_settings.auto_adjust_context_length || horde_settings.auto_adjust_response_length)) { if (main_api == 'koboldhorde' && (horde_settings.auto_adjust_context_length || horde_settings.auto_adjust_response_length)) {
try { try {
adjustedParams = await adjustHordeGenerationParams(max_context, amount_gen); adjustedParams = await adjustHordeGenerationParams(max_context, amount_gen);
} } catch {
catch {
unblockGeneration(type); unblockGeneration(type);
return Promise.resolve(); return Promise.resolve();
} }
@@ -4585,8 +4557,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
// When continuing generation of previous output, last user message precedes the message to continue // When continuing generation of previous output, last user message precedes the message to continue
if (isContinue) { if (isContinue) {
coreChat.splice(coreChat.length - 1, 0, { mes: jailbreak, is_user: true }); coreChat.splice(coreChat.length - 1, 0, { mes: jailbreak, is_user: true });
} } else {
else {
// This operation will result in the injectedIndices indexes being off by one // This operation will result in the injectedIndices indexes being off by one
coreChat.push({ mes: jailbreak, is_user: true }); coreChat.push({ mes: jailbreak, is_user: true });
// Add +1 to the elements to correct for the new PHI/Jailbreak message. // 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
if (itemizedIndex !== -1) { if (itemizedIndex !== -1) {
itemizedPrompts[itemizedIndex] = additionalPromptStuff; itemizedPrompts[itemizedIndex] = additionalPromptStuff;
} } else {
else {
itemizedPrompts.push(additionalPromptStuff); itemizedPrompts.push(additionalPromptStuff);
} }
@@ -5350,17 +5320,14 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
if (isImpersonate) { if (isImpersonate) {
$('#send_textarea').val(getMessage)[0].dispatchEvent(new Event('input', { bubbles: true })); $('#send_textarea').val(getMessage)[0].dispatchEvent(new Event('input', { bubbles: true }));
await eventSource.emit(event_types.IMPERSONATE_READY, getMessage); await eventSource.emit(event_types.IMPERSONATE_READY, getMessage);
} } else if (type == 'quiet') {
else if (type == 'quiet') {
unblockGeneration(type); unblockGeneration(type);
return getMessage; return getMessage;
} } else {
else {
// Without streaming we'll be having a full message on continuation. Treat it as a last chunk. // Without streaming we'll be having a full message on continuation. Treat it as a last chunk.
if (originalType !== 'continue') { if (originalType !== 'continue') {
({ type, getMessage } = await saveReply({ type, getMessage, title, swipes, reasoning, imageUrls, reasoningSignature })); ({ type, getMessage } = await saveReply({ type, getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));
} } else {
else {
({ type, getMessage } = await saveReply({ type: 'appendFinal', getMessage, title, swipes, reasoning, imageUrls, reasoningSignature })); ({ type, getMessage } = await saveReply({ type: 'appendFinal', getMessage, title, swipes, reasoning, imageUrls, reasoningSignature }));
} }
@@ -5829,9 +5796,7 @@ function addChatsPreamble(mesSendString) {
function addChatsSeparator(mesSendString) { function addChatsSeparator(mesSendString) {
if (power_user.context.chat_start) { if (power_user.context.chat_start) {
return substituteParams(power_user.context.chat_start + '\n') + mesSendString; return substituteParams(power_user.context.chat_start + '\n') + mesSendString;
} } else {
else {
return mesSendString; return mesSendString;
} }
} }
@@ -7055,16 +7020,13 @@ export async function renameCharacter(name = null, { silent = false, renameChats
} else { } else {
toastr.success(t`Character renamed!`, t`Rename Character`); toastr.success(t`Character renamed!`, t`Rename Character`);
} }
} } else {
else {
throw new Error('Newly renamed character was lost?'); throw new Error('Newly renamed character was lost?');
} }
} } else {
else {
throw new Error('Could not rename the character'); throw new Error('Could not rename the character');
} }
} } catch (error) {
catch (error) {
// Reloading to prevent data corruption // Reloading to prevent data corruption
if (!silent) await Popup.show.text(t`Rename Character`, t`Something went wrong. The page will be reloaded.`); if (!silent) await Popup.show.text(t`Rename Character`, t`Something went wrong. The page will be reloaded.`);
else toastr.error(t`Something went wrong. The page will be reloaded.`, t`Rename Character`); 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
avatarTemplate.append(grpTemplate.children()); avatarTemplate.append(grpTemplate.children());
avatarTemplate.attr({ 'data-grid': id, 'data-chid': null }); avatarTemplate.attr({ 'data-grid': id, 'data-chid': null });
avatarTemplate.attr('title', `[Group] ${entity.item.name}`); avatarTemplate.attr('title', `[Group] ${entity.item.name}`);
} } else if (entity.type === 'persona') {
else if (entity.type === 'persona') {
avatarTemplate.attr({ 'data-pid': id, 'data-chid': null }); avatarTemplate.attr({ 'data-pid': id, 'data-chid': null });
avatarTemplate.find('img').attr('src', getThumbnailUrl('persona', entity.item.avatar)); avatarTemplate.find('img').attr('src', getThumbnailUrl('persona', entity.item.avatar));
avatarTemplate.attr('title', `[Persona] ${entity.item.name}\nFile: ${entity.item.avatar}`); avatarTemplate.attr('title', `[Persona] ${entity.item.name}\nFile: ${entity.item.avatar}`);
@@ -8099,8 +8060,7 @@ async function messageEditCancel(messageId = this_edit_mes_id) {
await eventSource.emit(event_types.MESSAGE_UPDATED, messageId); await eventSource.emit(event_types.MESSAGE_UPDATED, messageId);
if (messageId == this_edit_mes_id) { if (messageId == this_edit_mes_id) {
this_edit_mes_id = undefined; this_edit_mes_id = undefined;
} } else {
else {
console.warn(`The message editor was closed on message #${messageId} while #${this_edit_mes_id} is being edited.`); console.warn(`The message editor was closed on message #${messageId} while #${this_edit_mes_id} is being edited.`);
} }
@@ -8134,8 +8094,7 @@ async function messageEditMove(sourceId, targetId) {
if (sourceId <= targetId) { if (sourceId <= targetId) {
sourceMessageDiv.insertAfter(targetMessageDiv); sourceMessageDiv.insertAfter(targetMessageDiv);
} } else {
else {
sourceMessageDiv.insertBefore(targetMessageDiv); sourceMessageDiv.insertBefore(targetMessageDiv);
} }
@@ -8951,11 +8910,13 @@ export function isMessageSwipeable(messageId, message = undefined) {
//User messages are not swipeable. //User messages are not swipeable.
!message.is_user !message.is_user
) )
) ) {
//The message is swipeable. // The message is swipeable.
{ return true; } return true;
//The message is not swipeable. } else {
else { return false; } // The message is not swipeable.
return false;
}
} }
/** /**
@@ -9145,8 +9106,7 @@ export async function saveChatConditional() {
if (selected_group) { if (selected_group) {
await saveGroupChat(selected_group, true); await saveGroupChat(selected_group, true);
} } else {
else {
await saveChat(); await saveChat();
} }
@@ -9252,8 +9212,7 @@ export function closeMessageEditor(what = 'all') {
export function setGenerationProgress(progress) { export function setGenerationProgress(progress) {
if (!progress) { if (!progress) {
$('#send_textarea').css({ 'background': '', 'transition': '' }); $('#send_textarea').css({ 'background': '', 'transition': '' });
} } else {
else {
$('#send_textarea').css({ $('#send_textarea').css({
'background': `linear-gradient(90deg, #008000d6 ${progress}%, transparent ${progress}%)`, 'background': `linear-gradient(90deg, #008000d6 ${progress}%, transparent ${progress}%)`,
'transition': '0.25s ease-in-out', 'transition': '0.25s ease-in-out',
@@ -9767,8 +9726,7 @@ export async function swipe(event, direction, { source, repeated, message = chat
document.body.dataset.swiping = 'true'; document.body.dataset.swiping = 'true';
await generation; await generation;
} }
} } catch (error) {
catch (error) {
console.warn(`Swipe failed, Swiping back. ${error}`); console.warn(`Swipe failed, Swiping back. ${error}`);
} }
@@ -9804,8 +9762,7 @@ export async function swipe(event, direction, { source, repeated, message = chat
//Update the chat. //Update the chat.
await loadFromSwipeId(mesId, chat[mesId].swipe_id); await loadFromSwipeId(mesId, chat[mesId].swipe_id);
await redisplayChat({ startIndex: mesId }); await redisplayChat({ startIndex: mesId });
} } else {
else {
await Popup.show.confirm( await Popup.show.confirm(
t`ERROR: <code>syncSwipeToMes</code> has failed to revert the failed ${direction} swipe on message #${mesId}.`, t`ERROR: <code>syncSwipeToMes</code> has failed to revert the failed ${direction} swipe on message #${mesId}.`,
t`<p>After you click OK, the chat will be reloaded to prevent data corruption.</p>`, 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
} }
await standardSwipe(newSwipeId); await standardSwipe(newSwipeId);
return; return;
} } else if (direction === SWIPE_DIRECTION.RIGHT) {
//If swiping right. //If swiping right.
else if (direction === SWIPE_DIRECTION.RIGHT) {
// make new slot in array // make new slot in array
if (forceSwipeId == null) newSwipeId++; if (forceSwipeId == null) newSwipeId++;
@@ -10133,18 +10089,16 @@ export async function swipe(event, direction, { source, repeated, message = chat
chat[mesId].swipe_id = originalSwipeId; chat[mesId].swipe_id = originalSwipeId;
await endSwipe(); await endSwipe();
return; return;
} } else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
//Regenerate the message //Regenerate the message
else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
clearMessageData(chat[mesId]); clearMessageData(chat[mesId]);
let run_generate = true; let run_generate = true;
//Generate. //Generate.
await animateSwipe(run_generate); await animateSwipe(run_generate);
await endSwipe(); await endSwipe();
return; return;
} } else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
// Loop to the first swipe. // Loop to the first swipe.
else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
newSwipeId = 0; newSwipeId = 0;
} }
} }
@@ -10363,8 +10317,7 @@ export async function doNewChat({ deleteCurrentChat = false } = {}) {
if (selected_group) { if (selected_group) {
await createNewGroupChat(selected_group); await createNewGroupChat(selected_group);
if (deleteCurrentChat) await deleteGroupChat(selected_group, chat_file_for_del, { jumpToNewChat: false }); // don't jump, new chat was already created and jumped to above if (deleteCurrentChat) await deleteGroupChat(selected_group, chat_file_for_del, { jumpToNewChat: false }); // don't jump, new chat was already created and jumped to above
} } else {
else {
//RossAscends: added character name to new chat filenames and replaced Date.now() with humanizedDateTime; //RossAscends: added character name to new chat filenames and replaced Date.now() with humanizedDateTime;
chat_metadata = {}; chat_metadata = {};
characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`; characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
@@ -10427,8 +10380,7 @@ export async function renameGroupOrCharacterChat({ characterId, groupId, oldFile
if (groupId) { if (groupId) {
await renameGroupChat(groupId, oldFileName, newFileName); await renameGroupChat(groupId, oldFileName, newFileName);
} } else if (characterId !== undefined && String(characterId) === String(this_chid) && characters[characterId]?.chat === oldFileName) {
else if (characterId !== undefined && String(characterId) === String(this_chid) && characters[characterId]?.chat === oldFileName) {
characters[characterId].chat = newFileName; characters[characterId].chat = newFileName;
$('#selected_chat_pole').val(characters[characterId].chat); $('#selected_chat_pole').val(characters[characterId].chat);
await createOrEditCharacter(); await createOrEditCharacter();
@@ -11080,8 +11032,7 @@ jQuery(async function () {
if (popup_type == 'input') { if (popup_type == 'input') {
dialogueResolve($('#dialogue_popup_input').val()); dialogueResolve($('#dialogue_popup_input').val());
$('#dialogue_popup_input').val(''); $('#dialogue_popup_input').val('');
} } else {
else {
dialogueResolve(true); dialogueResolve(true);
} }
@@ -11316,9 +11267,7 @@ jQuery(async function () {
}); });
} }
} }
} } else if (id == 'option_start_new_chat') {
else if (id == 'option_start_new_chat') {
if ((selected_group || this_chid !== undefined) && !is_send_press) { if ((selected_group || this_chid !== undefined) && !is_send_press) {
let deleteCurrentChat = false; let deleteCurrentChat = false;
const result = await Popup.show.confirm(t`Start new chat?`, await renderTemplateAsync('newChatConfirm'), { const result = await Popup.show.confirm(t`Start new chat?`, await renderTemplateAsync('newChatConfirm'), {
@@ -11334,9 +11283,7 @@ jQuery(async function () {
const alreadyInTempChat = this_chid === undefined && name2 === neutralCharacterName; const alreadyInTempChat = this_chid === undefined && name2 === neutralCharacterName;
await newAssistantChat({ temporary: alreadyInTempChat }); await newAssistantChat({ temporary: alreadyInTempChat });
} }
} } else if (id == 'option_regenerate') {
else if (id == 'option_regenerate') {
//Attempting to regenerate a user message will instead generate a new message. //Attempting to regenerate a user message will instead generate a new message.
if (chat.length && chat.length - 1 === this_edit_mes_id && chat[this_edit_mes_id]?.is_user == false) { if (chat.length && chat.length - 1 === this_edit_mes_id && chat[this_edit_mes_id]?.is_user == false) {
toastr.warning(t`Finish the edit before starting a generation.`, t`You cannot regenerate the message you are editing.`); 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 () {
if (is_send_press == false) { if (is_send_press == false) {
if (selected_group) { if (selected_group) {
regenerateGroup(); regenerateGroup();
} } else {
else {
is_send_press = true; is_send_press = true;
Generate('regenerate', buildOrFillAdditionalArgs()); Generate('regenerate', buildOrFillAdditionalArgs());
} }
} }
} } else if (id == 'option_impersonate') {
else if (id == 'option_impersonate') {
if (is_send_press == false || fromSlashCommand) { if (is_send_press == false || fromSlashCommand) {
is_send_press = true; is_send_press = true;
Generate('impersonate', buildOrFillAdditionalArgs()); Generate('impersonate', buildOrFillAdditionalArgs());
} }
} } else if (id == 'option_continue') {
else if (id == 'option_continue') {
if (swipeState == SWIPE_STATE.EDITING) { if (swipeState == SWIPE_STATE.EDITING) {
toastr.warning(t`Confirm the edit to start a generation.`, t`You cannot send a message during a swipe-edit.`); toastr.warning(t`Confirm the edit to start a generation.`, t`You cannot send a message during a swipe-edit.`);
return; return;
@@ -11374,17 +11316,11 @@ jQuery(async function () {
is_send_press = true; is_send_press = true;
Generate('continue', buildOrFillAdditionalArgs()); Generate('continue', buildOrFillAdditionalArgs());
} }
} } else if (id == 'option_delete_mes') {
else if (id == 'option_delete_mes') {
setTimeout(() => openMessageDelete(fromSlashCommand), animation_duration); setTimeout(() => openMessageDelete(fromSlashCommand), animation_duration);
} } else if (id == 'option_close_chat') {
else if (id == 'option_close_chat') {
await closeCurrentChat(); await closeCurrentChat();
} } else if (id === 'option_settings') {
else if (id === 'option_settings') {
//var checkBox = document.getElementById("waifuMode"); //var checkBox = document.getElementById("waifuMode");
var topBar = document.getElementById('top-bar'); var topBar = document.getElementById('top-bar');
var topSettingsHolder = document.getElementById('top-settings-holder'); var topSettingsHolder = document.getElementById('top-settings-holder');
+2 -4
View File
@@ -379,8 +379,7 @@ function RA_autoconnect(PrevApi) {
|| (textgen_settings.type === textgen_types.FEATHERLESS && secret_state[SECRET_KEYS.FEATHERLESS]) || (textgen_settings.type === textgen_types.FEATHERLESS && secret_state[SECRET_KEYS.FEATHERLESS])
) { ) {
$('#api_button_textgenerationwebui').trigger('click'); $('#api_button_textgenerationwebui').trigger('click');
} } else if (isValidUrl(getTextGenServer())) {
else if (isValidUrl(getTextGenServer())) {
$('#api_button_textgenerationwebui').trigger('click'); $('#api_button_textgenerationwebui').trigger('click');
} }
break; break;
@@ -1053,8 +1052,7 @@ export function initRossMods() {
$('#send_textarea').trigger('focus'); $('#send_textarea').trigger('focus');
reasoningMesDone.trigger('click'); reasoningMesDone.trigger('click');
return; return;
} } else if (is_send_press == false) {
else if (is_send_press == false) {
const skipConfirmKey = 'RegenerateWithCtrlEnter'; const skipConfirmKey = 'RegenerateWithCtrlEnter';
const skipConfirm = accountStorage.getItem(skipConfirmKey) === 'true'; const skipConfirm = accountStorage.getItem(skipConfirmKey) === 'true';
function doRegenerate() { function doRegenerate() {
+2 -4
View File
@@ -231,11 +231,9 @@ function onExtensionFloatingCharaPromptInput() {
!existingCharaNote.useChara !existingCharaNote.useChara
) { ) {
extension_settings.note.chara.splice(existingCharaNoteIndex, 1); extension_settings.note.chara.splice(existingCharaNoteIndex, 1);
} } else if (extension_settings.note.chara && existingCharaNote) {
else if (extension_settings.note.chara && existingCharaNote) {
Object.assign(existingCharaNote, tempCharaNote); Object.assign(existingCharaNote, tempCharaNote);
} } else if (avatarName && tempPrompt.length > 0) {
else if (avatarName && tempPrompt.length > 0) {
if (!extension_settings.note.chara) { if (!extension_settings.note.chara) {
extension_settings.note.chara = []; extension_settings.note.chara = [];
} }
+4 -7
View File
@@ -111,12 +111,10 @@ function getMainChatName() {
if (chat_metadata) { if (chat_metadata) {
if (chat_metadata.main_chat) { if (chat_metadata.main_chat) {
return chat_metadata.main_chat; return chat_metadata.main_chat;
} } else if (selected_group) {
// groups didn't support bookmarks before chat metadata was introduced // groups didn't support bookmarks before chat metadata was introduced
else if (selected_group) {
return null; return null;
} } else if (characters[this_chid].chat && characters[this_chid].chat.includes(bookmarkNameToken)) {
else if (characters[this_chid].chat && characters[this_chid].chat.includes(bookmarkNameToken)) {
const tokenIndex = characters[this_chid].chat.lastIndexOf(bookmarkNameToken); const tokenIndex = characters[this_chid].chat.lastIndexOf(bookmarkNameToken);
chat_metadata.main_chat = characters[this_chid].chat.substring(0, tokenIndex).trim(); chat_metadata.main_chat = characters[this_chid].chat.substring(0, tokenIndex).trim();
return chat_metadata.main_chat; return chat_metadata.main_chat;
@@ -146,8 +144,7 @@ export function showBookmarksButtons() {
$('#option_back_to_main').hide(); $('#option_back_to_main').hide();
$('#option_new_bookmark').show(); $('#option_new_bookmark').show();
} }
} } catch {
catch {
$('#option_back_to_main').hide(); $('#option_back_to_main').hide();
$('#option_new_bookmark').hide(); $('#option_new_bookmark').hide();
$('#option_convert_to_group').hide(); $('#option_convert_to_group').hide();
+3 -6
View File
@@ -832,11 +832,9 @@ async function openExternalMediaOverridesDialog() {
if (power_user.external_media_allowed_overrides.includes(entityId)) { if (power_user.external_media_allowed_overrides.includes(entityId)) {
template.find('#forbid_media_override_allowed').prop('checked', true); template.find('#forbid_media_override_allowed').prop('checked', true);
} } else if (power_user.external_media_forbidden_overrides.includes(entityId)) {
else if (power_user.external_media_forbidden_overrides.includes(entityId)) {
template.find('#forbid_media_override_forbidden').prop('checked', true); template.find('#forbid_media_override_forbidden').prop('checked', true);
} } else {
else {
template.find('#forbid_media_override_global').prop('checked', true); template.find('#forbid_media_override_global').prop('checked', true);
} }
@@ -1678,8 +1676,7 @@ async function runScraper(scraperId, target, callback) {
toastr.success(t`Scraped ${files.length} files from ${scraperId} to ${target}.`, t`Data Bank`); toastr.success(t`Scraped ${files.length} files from ${scraperId} to ${target}.`, t`Data Bank`);
callback(); callback();
} } catch (error) {
catch (error) {
console.error('Scraping failed', error); console.error('Scraping failed', error);
toastr.error(t`Check browser console for details.`, t`Scraping failed`); toastr.error(t`Check browser console for details.`, t`Scraping failed`);
} }
+1 -2
View File
@@ -73,8 +73,7 @@ function applyDynamicFocusStyles(styleSheet, { fromExtension = false } = {}) {
const isHover = selector.includes(':hover'), isFocus = selector.includes(':focus'); const isHover = selector.includes(':hover'), isFocus = selector.includes(':focus');
if (isHover && isFocus) { if (isHover && isFocus) {
// We currently do nothing here. Rules containing both hover and focus are very specific and should never be automatically touched // We currently do nothing here. Rules containing both hover and focus are very specific and should never be automatically touched
} } else if (isHover) {
else if (isHover) {
const baseSelector = selector.replace(/:hover/g, PLACEHOLDER).trim(); const baseSelector = selector.replace(/:hover/g, PLACEHOLDER).trim();
hoverRules.push({ baseSelector, rule, wrappers: [...wrappers] }); hoverRules.push({ baseSelector, rule, wrappers: [...wrappers] });
} else if (isFocus) { } else if (isFocus) {
+3 -6
View File
@@ -278,12 +278,10 @@ async function discoverExtensions() {
if (response.ok) { if (response.ok) {
const extensions = await response.json(); const extensions = await response.json();
return extensions; return extensions;
} } else {
else {
return []; return [];
} }
} } catch (err) {
catch (err) {
console.error(err); console.error(err);
return []; return [];
} }
@@ -627,8 +625,7 @@ async function connectToApi(baseUrl) {
} }
updateStatus(getExtensionsResult.ok); updateStatus(getExtensionsResult.ok);
} } catch {
catch {
updateStatus(false); updateStatus(false);
} }
} }
+6 -12
View File
@@ -82,8 +82,7 @@ function getAuthorFromUrl(url) {
result.name = pathSegments[0]; result.name = pathSegments[0];
result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`; result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`;
} }
} } catch (error) {
catch (error) {
console.debug(DEBUG_PREFIX, 'Error parsing URL:', error); console.debug(DEBUG_PREFIX, 'Error parsing URL:', error);
} }
@@ -199,8 +198,7 @@ async function downloadAssetsList(url) {
label.removeClass('fa-trash'); label.removeClass('fa-trash');
label.removeClass('redOverlayGlow'); label.removeClass('redOverlayGlow');
}); });
} } else {
else {
console.debug(DEBUG_PREFIX, 'not installed, unchecked'); console.debug(DEBUG_PREFIX, 'not installed, unchecked');
element.prop('checked', false); element.prop('checked', false);
element.on('click', assetInstall); element.on('click', assetInstall);
@@ -346,8 +344,7 @@ async function installAsset(url, assetType, filename) {
console.debug(DEBUG_PREFIX, 'Character downloaded.'); console.debug(DEBUG_PREFIX, 'Character downloaded.');
} }
} }
} } catch (err) {
catch (err) {
console.log(err); console.log(err);
return []; return [];
} }
@@ -373,8 +370,7 @@ async function deleteAsset(assetType, filename) {
if (result.ok) { if (result.ok) {
console.debug(DEBUG_PREFIX, 'Deletion success.'); console.debug(DEBUG_PREFIX, 'Deletion success.');
} }
} } catch (err) {
catch (err) {
console.log(err); console.log(err);
return []; return [];
} }
@@ -427,8 +423,7 @@ async function updateCurrentAssets() {
headers: getRequestHeaders({ omitContentType: true }), headers: getRequestHeaders({ omitContentType: true }),
}); });
currentAssets = result.ok ? (await result.json()) : {}; currentAssets = result.ok ? (await result.json()) : {};
} } catch (err) {
catch (err) {
console.log(err); console.log(err);
} }
console.debug(DEBUG_PREFIX, 'Current assets found:', currentAssets); console.debug(DEBUG_PREFIX, 'Current assets found:', currentAssets);
@@ -490,8 +485,7 @@ jQuery(async () => {
connectButton.addClass('fa-plug-circle-exclamation'); connectButton.addClass('fa-plug-circle-exclamation');
connectButton.removeClass('redOverlayGlow'); connectButton.removeClass('redOverlayGlow');
} }
} } else {
else {
console.debug(DEBUG_PREFIX, 'Connection refused by user'); console.debug(DEBUG_PREFIX, 'Connection refused by user');
} }
}); });
+4 -8
View File
@@ -68,8 +68,7 @@ async function setImageIcon() {
const sendButton = $('#send_picture .extensionsMenuExtensionButton'); const sendButton = $('#send_picture .extensionsMenuExtensionButton');
sendButton.addClass('fa-image'); sendButton.addClass('fa-image');
sendButton.removeClass('fa-hourglass-half'); sendButton.removeClass('fa-hourglass-half');
} } catch (error) {
catch (error) {
console.log(error); console.log(error);
} }
} }
@@ -82,8 +81,7 @@ async function setSpinnerIcon() {
const sendButton = $('#send_picture .extensionsMenuExtensionButton'); const sendButton = $('#send_picture .extensionsMenuExtensionButton');
sendButton.removeClass('fa-image'); sendButton.removeClass('fa-image');
sendButton.addClass('fa-hourglass-half'); sendButton.addClass('fa-hourglass-half');
} } catch (error) {
catch (error) {
console.log(error); console.log(error);
} }
} }
@@ -376,14 +374,12 @@ async function getCaptionForFile(file, prompt, quiet) {
await sendCaptionedMessage(caption, imagePath, file.type); await sendCaptionedMessage(caption, imagePath, file.type);
} }
return caption; return caption;
} } catch (error) {
catch (error) {
const errorMessage = error.message || 'Unknown error'; const errorMessage = error.message || 'Unknown error';
toastr.error(errorMessage, 'Failed to caption'); toastr.error(errorMessage, 'Failed to caption');
console.error(error); console.error(error);
return ''; return '';
} } finally {
finally {
setImageIcon(); setImageIcon();
} }
} }
+15 -26
View File
@@ -363,8 +363,7 @@ export async function visualNovelUpdateLayers(container) {
if (power_user.reduced_motion) { if (power_user.reduced_motion) {
element.css('left', currentPosition + 'px'); element.css('left', currentPosition + 'px');
requestAnimationFrame(() => resolve()); requestAnimationFrame(() => resolve());
} } else {
else {
element.animate({ left: currentPosition + 'px' }, 500, () => { element.animate({ left: currentPosition + 'px' }, 500, () => {
resolve(); resolve();
}); });
@@ -525,8 +524,7 @@ async function moduleWorker({ newChat = false } = {}) {
} }
return; return;
} } else {
else {
// force reload expressions list on connect to API // force reload expressions list on connect to API
if (offlineMode.is(':visible')) { if (offlineMode.is(':visible')) {
expressionsList = null; expressionsList = null;
@@ -599,11 +597,9 @@ async function moduleWorker({ newChat = false } = {}) {
} }
await sendExpressionCall(spriteFolderName, expression, { force: force, vnMode: vnMode }); await sendExpressionCall(spriteFolderName, expression, { force: force, vnMode: vnMode });
} } catch (error) {
catch (error) {
console.log(error); console.log(error);
} } finally {
finally {
inApiCall = false; inApiCall = false;
lastCharacter = context.groupId || context.characterId; lastCharacter = context.groupId || context.characterId;
lastMessage = currentLastMessage.mes; lastMessage = currentLastMessage.mes;
@@ -631,8 +627,7 @@ function getFolderNameByMessage(message) {
if (context.groupId) { if (context.groupId) {
avatarPath = message.original_avatar || context.characters.find(x => message.force_avatar && message.force_avatar.includes(encodeURIComponent(x.avatar)))?.avatar; avatarPath = message.original_avatar || context.characters.find(x => message.force_avatar && message.force_avatar.includes(encodeURIComponent(x.avatar)))?.avatar;
} } else if (context.characterId !== undefined) {
else if (context.characterId !== undefined) {
avatarPath = getCharaFilename(); avatarPath = getCharaFilename();
} }
@@ -1303,8 +1298,7 @@ async function getSpritesList(name) {
} }
return grouped; return grouped;
} } catch (err) {
catch (err) {
console.log(err); console.log(err);
return []; return [];
} }
@@ -1476,9 +1470,8 @@ function chooseSpriteForExpression(spriteFolderName, expression, { prevExpressio
const searched = sprite.files.find(x => x.fileName === overrideSpriteFile); const searched = sprite.files.find(x => x.fileName === overrideSpriteFile);
if (searched) spriteFile = searched; if (searched) spriteFile = searched;
else toastr.warning(t`Couldn't find sprite file ${overrideSpriteFile} for expression ${expression}.`, t`Sprite Not Found`); else toastr.warning(t`Couldn't find sprite file ${overrideSpriteFile} for expression ${expression}.`, t`Sprite Not Found`);
} } else if (extension_settings.expressions.allowMultiple && sprite.files.length > 1) {
// Else calculate next expression, if multiple are allowed // Else calculate next expression, if multiple are allowed
else if (extension_settings.expressions.allowMultiple && sprite.files.length > 1) {
let possibleFiles = sprite.files; let possibleFiles = sprite.files;
if (extension_settings.expressions.rerollIfSame) { if (extension_settings.expressions.rerollIfSame) {
possibleFiles = possibleFiles.filter(x => !prevExpressionSrc || x.imageSrc !== prevExpressionSrc); possibleFiles = possibleFiles.filter(x => !prevExpressionSrc || x.imageSrc !== prevExpressionSrc);
@@ -1593,8 +1586,7 @@ async function setExpression(spriteFolderName, expression, { force = false, over
} }
console.info('Expression set', { expression: spriteFile.expression, file: spriteFile.fileName }); console.info('Expression set', { expression: spriteFile.expression, file: spriteFile.fileName });
} } else {
else {
img.attr('data-sprite-folder-name', spriteFolderName); img.attr('data-sprite-folder-name', spriteFolderName);
img.off('error'); img.off('error');
@@ -1844,19 +1836,16 @@ async function onClickExpressionUpload(event) {
const fileNameWithoutExtension = withoutExtension(file.name); const fileNameWithoutExtension = withoutExtension(file.name);
const validFileName = validateExpressionSpriteName(expression, fileNameWithoutExtension); const validFileName = validateExpressionSpriteName(expression, fileNameWithoutExtension);
// If there is no expression yet and it's a valid expression, we just take it
if (!clickedFileName && validFileName) { if (!clickedFileName && validFileName) {
// If there is no expression yet and it's a valid expression, we just take it
spriteName = fileNameWithoutExtension; spriteName = fileNameWithoutExtension;
} } else if (clickedFileName === file.name) {
// If the filename matches the one that was clicked, we just take it and replace it // If the filename matches the one that was clicked, we just take it and replace it
else if (clickedFileName === file.name) {
spriteName = fileNameWithoutExtension; spriteName = fileNameWithoutExtension;
} } else if (!matchesExisting && validFileName) {
// If it's a valid filename and there's no existing file with the same name, we just take it // If it's a valid filename and there's no existing file with the same name, we just take it
else if (!matchesExisting && validFileName) {
spriteName = fileNameWithoutExtension; spriteName = fileNameWithoutExtension;
} } else {
else {
/** @type {import('../../popup.js').CustomPopupButton[]} */ /** @type {import('../../popup.js').CustomPopupButton[]} */
const customButtons = []; const customButtons = [];
if (clickedFileName) { if (clickedFileName) {
+2 -4
View File
@@ -881,11 +881,9 @@ async function summarizeChatExtras(context) {
} }
setMemoryContext(summary, true); setMemoryContext(summary, true);
} } catch (error) {
catch (error) {
console.log(error); console.log(error);
} } finally {
finally {
inApiCall = false; inApiCall = false;
} }
} }
@@ -398,8 +398,7 @@ export class QuickReply {
if (this.icon) { if (this.icon) {
icon.classList.add('fa-solid'); icon.classList.add('fa-solid');
icon.classList.add(this.icon); icon.classList.add(this.icon);
} } else {
else {
icon.textContent = '…'; icon.textContent = '…';
} }
icon.addEventListener('click', async () => { icon.addEventListener('click', async () => {
@@ -3021,8 +3021,7 @@ async function generatePicture(initiator, args, trigger, message, callback) {
const errorText = 'SD prompt text generation failed. ' + reason; const errorText = 'SD prompt text generation failed. ' + reason;
toastr.error(errorText, 'Image Generation'); toastr.error(errorText, 'Image Generation');
throw new Error(errorText); throw new Error(errorText);
} } finally {
finally {
$(stopButton).hide(); $(stopButton).hide();
restoreOriginalDimensions(dimensions); restoreOriginalDimensions(dimensions);
eventSource.removeListener(CUSTOM_STOP_EVENT, stopListener); eventSource.removeListener(CUSTOM_STOP_EVENT, stopListener);
+4 -8
View File
@@ -497,8 +497,7 @@ class CoquiTtsProvider {
const language_label = JSON.stringify(model_settings.languages[i]).replaceAll('"', ''); const language_label = JSON.stringify(model_settings.languages[i]).replaceAll('"', '');
$('#coqui_api_model_settings_language').append(new Option(language_label, i)); $('#coqui_api_model_settings_language').append(new Option(language_label, i));
} }
} } else {
else {
$('#coqui_api_model_settings_language').hide(); $('#coqui_api_model_settings_language').hide();
} }
@@ -516,8 +515,7 @@ class CoquiTtsProvider {
const speaker_label = JSON.stringify(model_settings.speakers[i]).replaceAll('"', ''); const speaker_label = JSON.stringify(model_settings.speakers[i]).replaceAll('"', '');
$('#coqui_api_model_settings_speaker').append(new Option(speaker_label, i)); $('#coqui_api_model_settings_speaker').append(new Option(speaker_label, i));
} }
} } else {
else {
$('#coqui_api_model_settings_speaker').hide(); $('#coqui_api_model_settings_speaker').hide();
} }
@@ -536,15 +534,13 @@ class CoquiTtsProvider {
if (model_state == 'installed') { if (model_state == 'installed') {
$('#coqui_api_model_install_status').text('Model already installed on extras server'); $('#coqui_api_model_install_status').text('Model already installed on extras server');
$('#coqui_api_model_install_button').hide(); $('#coqui_api_model_install_button').hide();
} } else {
else {
let action = 'download'; let action = 'download';
if (model_state == 'corrupted') { if (model_state == 'corrupted') {
action = 'repare'; action = 'repare';
//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 }); //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 });
$('#coqui_api_model_install_status').text('Model found but incomplete try install again (maybe still downloading)'); // (remove and download again) $('#coqui_api_model_install_status').text('Model found but incomplete try install again (maybe still downloading)'); // (remove and download again)
} } else {
else {
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 }); 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 });
$('#coqui_api_model_install_status').text('Model not found on extras server'); $('#coqui_api_model_install_status').text('Model not found on extras server');
} }
+2 -4
View File
@@ -346,8 +346,7 @@ globalThis.tts_preview = function (id) {
if (audio instanceof HTMLAudioElement && !$(audio).data('disabled')) { if (audio instanceof HTMLAudioElement && !$(audio).data('disabled')) {
audio.play(); audio.play();
} } else {
else {
ttsProvider.previewTtsVoice(id); ttsProvider.previewTtsVoice(id);
} }
}; };
@@ -1452,8 +1451,7 @@ async function initVoiceMapInternal(unrestricted) {
let voiceIdsFromProvider; let voiceIdsFromProvider;
try { try {
voiceIdsFromProvider = await ttsProvider.fetchTtsVoiceObjects(); voiceIdsFromProvider = await ttsProvider.fetchTtsVoiceObjects();
} } catch {
catch {
toastr.error('TTS Provider failed to return voice ids.'); toastr.error('TTS Provider failed to return voice ids.');
} }
+1 -2
View File
@@ -29,8 +29,7 @@ var speechUtteranceChunker = function (utt, settings, callback) {
callback(); callback();
} }
}); });
} } else {
else {
var chunkLength = (settings && settings.chunkLength) || 160; var chunkLength = (settings && settings.chunkLength) || 160;
var pattRegex = new RegExp('^[\\s\\S]{' + Math.floor(chunkLength / 2) + ',' + chunkLength + '}[.!?,]{1}|^[\\s\\S]{1,' + chunkLength + '}$|^[\\s\\S]{1,' + chunkLength + '} '); var pattRegex = new RegExp('^[\\s\\S]{' + Math.floor(chunkLength / 2) + ',' + chunkLength + '}[.!?,]{1}|^[\\s\\S]{1,' + chunkLength + '}$|^[\\s\\S]{1,' + chunkLength + '} ');
var chunkArr = txt.match(pattRegex); var chunkArr = txt.match(pattRegex);
+2 -4
View File
@@ -325,8 +325,7 @@ class VITSTtsProvider {
if (streaming) { if (streaming) {
params.append('streaming', streaming); params.append('streaming', streaming);
// Streaming response only supports MP3 // Streaming response only supports MP3
} } else {
else {
params.append('format', this.settings.format); params.append('format', this.settings.format);
} }
params.append('lang', lang ?? this.settings.lang); params.append('lang', lang ?? this.settings.lang);
@@ -337,8 +336,7 @@ class VITSTtsProvider {
if (model_type == this.modelTypes.W2V2_VITS) { if (model_type == this.modelTypes.W2V2_VITS) {
params.append('emotion', this.settings.dim_emotion); params.append('emotion', this.settings.dim_emotion);
} } else if (model_type == this.modelTypes.BERT_VITS2) {
else if (model_type == this.modelTypes.BERT_VITS2) {
params.append('sdp_ratio', this.settings.sdp_ratio); params.append('sdp_ratio', this.settings.sdp_ratio);
params.append('emotion', this.settings.emotion); params.append('emotion', this.settings.emotion);
if (this.settings.text_prompt) { if (this.settings.text_prompt) {
+2 -4
View File
@@ -251,8 +251,7 @@ async function summarizeExtra(element) {
const data = await apiResult.json(); const data = await apiResult.json();
element.text = data.summary; element.text = data.summary;
} }
} } catch (error) {
catch (error) {
console.log(error); console.log(error);
return false; return false;
} }
@@ -938,8 +937,7 @@ function throwIfSourceInvalid() {
if (!settings.alt_endpoint_url) { if (!settings.alt_endpoint_url) {
throw new Error('Vectors: API URL missing', { cause: 'api_url_missing' }); throw new Error('Vectors: API URL missing', { cause: 'api_url_missing' });
} }
} } else {
else {
if (settings.source === 'ollama' && !textgenerationwebui_settings.server_urls[textgen_types.OLLAMA] || if (settings.source === 'ollama' && !textgenerationwebui_settings.server_urls[textgen_types.OLLAMA] ||
settings.source === 'vllm' && !textgenerationwebui_settings.server_urls[textgen_types.VLLM] || settings.source === 'vllm' && !textgenerationwebui_settings.server_urls[textgen_types.VLLM] ||
settings.source === 'koboldcpp' && !textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP] || settings.source === 'koboldcpp' && !textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP] ||
+1 -2
View File
@@ -328,8 +328,7 @@ export class FilterHelper {
// We can filter easily by checking if we have saved a score // We can filter easily by checking if we have saved a score
const score = _this.getScore(FILTER_TYPES.SEARCH, `${entity.type}.${entity.id}`); const score = _this.getScore(FILTER_TYPES.SEARCH, `${entity.type}.${entity.id}`);
return score !== undefined; return score !== undefined;
} } else {
else {
// Compare insensitive and without accents // Compare insensitive and without accents
return includesIgnoreCaseAndAccents(entity.item?.name, searchValue); return includesIgnoreCaseAndAccents(entity.item?.name, searchValue);
} }
+13 -25
View File
@@ -173,9 +173,8 @@ async function regenerateGroup() {
// for new generations after the update // for new generations after the update
if ((generationId && this_generationId) && generationId !== this_generationId) { if ((generationId && this_generationId) && generationId !== this_generationId) {
break; break;
} } else if (lastMes.is_user || lastMes.is_system) {
// legacy for generations before the update // legacy for generations before the update
else if (lastMes.is_user || lastMes.is_system) {
break; break;
} }
@@ -392,8 +391,7 @@ export function findGroupMemberId(arg, full = false) {
console.log(`Targeting group member ${chid} (${arg}) from search result`, result[0]); console.log(`Targeting group member ${chid} (${arg}) from search result`, result[0]);
return !full ? chid : { ...{ id: chid }, ...result[0].item }; return !full ? chid : { ...{ id: chid }, ...result[0].item };
} } else {
else {
const memberAvatar = group.members[index]; const memberAvatar = group.members[index];
if (memberAvatar === undefined) { if (memberAvatar === undefined) {
@@ -744,8 +742,7 @@ export async function renameGroupMember(oldAvatar, newAvatar, newName) {
} }
} }
} }
} } catch (error) {
catch (error) {
console.log(`An error during renaming the character ${newName} in group: ${group.name}`); console.log(`An error during renaming the character ${newName} in group: ${group.name}`);
console.error(error); console.error(error);
} }
@@ -1011,28 +1008,22 @@ async function generateGroupWrapper(byAutoMode, type = null, params = {}) {
if (activatedMembers.length === 0) { if (activatedMembers.length === 0) {
activatedMembers = activateListOrder(group.members.slice(0, 1)); activatedMembers = activateListOrder(group.members.slice(0, 1));
} }
} } else if (type === 'swipe' || type === 'continue') {
else if (type === 'swipe' || type === 'continue') {
activatedMembers = activateSwipe(group.members, { allowSystem: false }); activatedMembers = activateSwipe(group.members, { allowSystem: false });
if (activatedMembers.length === 0) { if (activatedMembers.length === 0) {
toastr.warning(t`Deleted group member swiped. To get a reply, add them back to the group.`); toastr.warning(t`Deleted group member swiped. To get a reply, add them back to the group.`);
throw new Error('Deleted group member swiped'); throw new Error('Deleted group member swiped');
} }
} } else if (type === 'impersonate') {
else if (type === 'impersonate') {
activatedMembers = activateImpersonate(group.members); activatedMembers = activateImpersonate(group.members);
} } else if (activationStrategy === group_activation_strategy.NATURAL) {
else if (activationStrategy === group_activation_strategy.NATURAL) {
activatedMembers = activateNaturalOrder(enabledMembers, activationText, lastMessage, group.allow_self_responses, isUserInput); activatedMembers = activateNaturalOrder(enabledMembers, activationText, lastMessage, group.allow_self_responses, isUserInput);
} } else if (activationStrategy === group_activation_strategy.LIST) {
else if (activationStrategy === group_activation_strategy.LIST) {
activatedMembers = activateListOrder(enabledMembers); activatedMembers = activateListOrder(enabledMembers);
} } else if (activationStrategy === group_activation_strategy.POOLED) {
else if (activationStrategy === group_activation_strategy.POOLED) {
activatedMembers = activatePooledOrder(enabledMembers, lastMessage, isUserInput); activatedMembers = activatePooledOrder(enabledMembers, lastMessage, isUserInput);
} } else if (activationStrategy === group_activation_strategy.MANUAL && !isUserInput) {
else if (activationStrategy === group_activation_strategy.MANUAL && !isUserInput) {
activatedMembers = shuffle(enabledMembers).slice(0, 1).map(x => characters.findIndex(y => y.avatar === x)).filter(x => x !== -1); activatedMembers = shuffle(enabledMembers).slice(0, 1).map(x => characters.findIndex(y => y.avatar === x)).filter(x => x !== -1);
} }
@@ -1168,8 +1159,7 @@ function activateSwipe(members, { allowSystem = false } = {}) {
break; break;
} }
} }
} } else {
else {
activatedNames.push(lastMessage.original_avatar); activatedNames.push(lastMessage.original_avatar);
} }
@@ -1704,8 +1694,7 @@ function getGroupCharacterBlock(character) {
const auxFieldValue = (character.data && character.data[auxFieldName]) || ''; const auxFieldValue = (character.data && character.data[auxFieldName]) || '';
if (auxFieldValue) { if (auxFieldValue) {
template.find('.character_version').text(auxFieldValue); template.find('.character_version').text(auxFieldValue);
} } else {
else {
template.find('.character_version').hide(); template.find('.character_version').hide();
} }
@@ -1875,8 +1864,7 @@ function select_group_chats(groupId, skipAnimation) {
if (group) { if (group) {
$('#rm_group_automode_label').show(); $('#rm_group_automode_label').show();
$('#rm_button_selected_ch').children('h2').text(groupName); $('#rm_button_selected_ch').children('h2').text(groupName);
} } else {
else {
$('#rm_group_automode_label').hide(); $('#rm_group_automode_label').hide();
} }
+1 -2
View File
@@ -126,8 +126,7 @@ export async function getStatusHorde() {
try { try {
const hordeStatus = await checkHordeStatus(); const hordeStatus = await checkHordeStatus();
setOnlineStatus(hordeStatus ? t`Connected` : 'no_connection'); setOnlineStatus(hordeStatus ? t`Connected` : 'no_connection');
} } catch {
catch {
setOnlineStatus('no_connection'); setOnlineStatus('no_connection');
} }
+1 -2
View File
@@ -220,8 +220,7 @@ function tryParseStreamingError(response, decoded) {
toastr.error(data.error.message || response.statusText, 'KoboldAI API'); toastr.error(data.error.message || response.statusText, 'KoboldAI API');
throw new Error(data); throw new Error(data);
} }
} } catch {
catch {
// No JSON. Do nothing. // No JSON. Do nothing.
} }
} }
+4 -10
View File
@@ -117,11 +117,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
if (text.startsWith('{') && text.endsWith('}')) { if (text.startsWith('{') && text.endsWith('}')) {
const tokens = getTextTokens(tokenizerType, text.slice(1, -1)); const tokens = getTextTokens(tokenizerType, text.slice(1, -1));
result.push(getBiasObject(entry.value, tokens)); result.push(getBiasObject(entry.value, tokens));
} } else if (text.startsWith('[') && text.endsWith(']')) {
// Raw token ids, JSON serialized
// Raw token ids, JSON serialized
else if (text.startsWith('[') && text.endsWith(']')) {
try { try {
const tokens = JSON.parse(text); const tokens = JSON.parse(text);
@@ -133,11 +130,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
} catch (err) { } catch (err) {
console.log(`Failed to parse logit bias token list: ${text}`, err); console.log(`Failed to parse logit bias token list: ${text}`, err);
} }
} } else {
// Text with a leading space
// Text with a leading space
else {
const biasText = ` ${text}`; const biasText = ` ${text}`;
const tokens = getTextTokens(tokenizerType, biasText); const tokens = getTextTokens(tokenizerType, biasText);
result.push(getBiasObject(entry.value, tokens)); result.push(getBiasObject(entry.value, tokens));
@@ -1001,9 +1001,8 @@ class MacroCstWalker {
endOffset: element.endOffset ?? element.startOffset, endOffset: element.endOffset ?? element.startOffset,
token: element, token: element,
}); });
} } else if ('children' in element) {
// Handle nested CstNode (macro or argument) // Handle nested CstNode (macro or argument)
else if ('children' in element) {
const nestedChildren = element.children || {}; const nestedChildren = element.children || {};
const nestedEnd = /** @type {IToken?} */ ((nestedChildren['Macro.End'] || [])[0]); const nestedEnd = /** @type {IToken?} */ ((nestedChildren['Macro.End'] || [])[0]);
const nestedStart = /** @type {IToken?} */ ((nestedChildren['Macro.Start'] || [])[0]); const nestedStart = /** @type {IToken?} */ ((nestedChildren['Macro.Start'] || [])[0]);
+6 -12
View File
@@ -180,8 +180,7 @@ export function loadNovelPreset(preset) {
$('#amount_gen').val(preset.max_length).trigger('input'); $('#amount_gen').val(preset.max_length).trigger('input');
$('#max_context_unlocked').prop('checked', needsUnlock).trigger('change'); $('#max_context_unlocked').prop('checked', needsUnlock).trigger('change');
$('#max_context').val(preset.max_context).trigger('input'); $('#max_context').val(preset.max_context).trigger('input');
} } else {
else {
setGenerationParamsFromPreset(preset); setGenerationParamsFromPreset(preset);
} }
@@ -459,10 +458,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
if (trimmed.startsWith('{') && trimmed.endsWith('}')) { if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
const tokens = getTextTokens(tokenizerType, trimmed.slice(1, -1)); const tokens = getTextTokens(tokenizerType, trimmed.slice(1, -1));
result.push(tokens); result.push(tokens);
} } else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
// Raw token ids, JSON serialized
// Raw token ids, JSON serialized
else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
try { try {
const tokens = JSON.parse(trimmed); const tokens = JSON.parse(trimmed);
@@ -474,10 +471,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
} catch (err) { } catch (err) {
console.log(`Failed to parse bad word token list: ${trimmed}`, err); console.log(`Failed to parse bad word token list: ${trimmed}`, err);
} }
} } else {
// Apply permutations
// Apply permutations
else {
const permutations = getBadWordPermutations(trimmed).map(t => getTextTokens(tokenizerType, t)); const permutations = getBadWordPermutations(trimmed).map(t => getTextTokens(tokenizerType, t));
result.push(...permutations); result.push(...permutations);
} }
@@ -738,8 +733,7 @@ function tryParseStreamingError(response, decoded) {
toastr.error(data.message || data.error?.message || response.statusText, 'NovelAI API'); toastr.error(data.message || data.error?.message || response.statusText, 'NovelAI API');
throw new Error(data); throw new Error(data);
} }
} } catch {
catch {
// No JSON. Do nothing. // No JSON. Do nothing.
} }
} }
+61 -122
View File
@@ -495,8 +495,7 @@ async function validateReverseProxy() {
try { try {
new URL(oai_settings.reverse_proxy); new URL(oai_settings.reverse_proxy);
} } catch (err) {
catch (err) {
toastr.error(t`Entered reverse proxy address is not a valid URL`); toastr.error(t`Entered reverse proxy address is not a valid URL`);
setOnlineStatus('no_connection'); setOnlineStatus('no_connection');
resultCheckStatus(); resultCheckStatus();
@@ -1551,8 +1550,7 @@ export function tryParseStreamingError(response, decoded, { quiet = false } = {}
!quiet && toastr.error(data.detail?.error?.message || response.statusText, 'Chat Completion API'); !quiet && toastr.error(data.detail?.error?.message || response.statusText, 'Chat Completion API');
throw new Error(data); throw new Error(data);
} }
} } catch {
catch {
// No JSON. Do nothing. // No JSON. Do nothing.
} }
} }
@@ -2868,8 +2866,7 @@ async function sendOpenAIRequest(type, messages, signal, { jsonSchema = null } =
yield { text, swipes: swipes, logprobs: parseChatCompletionLogprobs(parsed), toolCalls: toolCalls, state: state }; yield { text, swipes: swipes, logprobs: parseChatCompletionLogprobs(parsed), toolCalls: toolCalls, state: state };
} }
}; };
} } else {
else {
const data = await response.json(); const data = await response.json();
checkQuotaError(data); checkQuotaError(data);
@@ -3081,8 +3078,7 @@ async function calculateLogitBias() {
}); });
result = await reply.json(); result = await reply.json();
} } catch (err) {
catch (err) {
result = {}; result = {};
console.error(err); console.error(err);
} }
@@ -3602,13 +3598,11 @@ export class ChatCompletion {
if (lastMessage && shouldSquash(lastMessage)) { if (lastMessage && shouldSquash(lastMessage)) {
lastMessage.content += '\n' + message.content; lastMessage.content += '\n' + message.content;
lastMessage.tokens = await tokenHandler.countAsync({ role: lastMessage.role, content: lastMessage.content }); lastMessage.tokens = await tokenHandler.countAsync({ role: lastMessage.role, content: lastMessage.content });
} } else {
else {
squashedMessages.push(message); squashedMessages.push(message);
lastMessage = message; lastMessage = message;
} }
} } else {
else {
squashedMessages.push(message); squashedMessages.push(message);
lastMessage = message; lastMessage = message;
} }
@@ -4242,8 +4236,7 @@ async function saveOpenAIPreset(name, settings, triggerUi = true) {
Object.assign(openai_settings[value], presetBody); Object.assign(openai_settings[value], presetBody);
$(`#settings_preset_openai option[value="${value}"]`).prop('selected', true); $(`#settings_preset_openai option[value="${value}"]`).prop('selected', true);
if (triggerUi) $('#settings_preset_openai').trigger('change'); if (triggerUi) $('#settings_preset_openai').trigger('change');
} } else {
else {
openai_settings.push(presetBody); openai_settings.push(presetBody);
openai_setting_names[data.name] = openai_settings.length - 1; openai_setting_names[data.name] = openai_settings.length - 1;
const option = document.createElement('option'); const option = document.createElement('option');
@@ -4692,47 +4685,33 @@ function onSettingsPresetChange() {
function getMaxContextOpenAI(value) { function getMaxContextOpenAI(value) {
if (oai_settings.max_context_unlocked) { if (oai_settings.max_context_unlocked) {
return unlocked_max; return unlocked_max;
} } else if (value.startsWith('gpt-5')) {
else if (value.startsWith('gpt-5')) {
return max_400k; return max_400k;
} } else if (value.includes('gpt-4.1')) {
else if (value.includes('gpt-4.1')) {
return max_1mil; return max_1mil;
} } else if (value.includes('gpt-audio')) {
else if (value.includes('gpt-audio')) {
return max_128k; return max_128k;
} } else if (value.startsWith('o1')) {
else if (value.startsWith('o1')) {
return max_128k; return max_128k;
} } else if (value.startsWith('o4') || value.startsWith('o3')) {
else if (value.startsWith('o4') || value.startsWith('o3')) {
return max_200k; return max_200k;
} } 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')) {
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')) {
return max_128k; return max_128k;
} } else if (value.includes('gpt-3.5-turbo-1106')) {
else if (value.includes('gpt-3.5-turbo-1106')) {
return max_16k; return max_16k;
} } else if (['gpt-4', 'gpt-4-0314', 'gpt-4-0613'].includes(value)) {
else if (['gpt-4', 'gpt-4-0314', 'gpt-4-0613'].includes(value)) {
return max_8k; return max_8k;
} } else if (['gpt-4-32k', 'gpt-4-32k-0314', 'gpt-4-32k-0613'].includes(value)) {
else if (['gpt-4-32k', 'gpt-4-32k-0314', 'gpt-4-32k-0613'].includes(value)) {
return max_32k; return max_32k;
} } else if (value.includes('gpt-realtime')) {
else if (value.includes('gpt-realtime')) {
return max_32k; return max_32k;
} } else if (['gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613'].includes(value)) {
else if (['gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613'].includes(value)) {
return max_16k; return max_16k;
} } else if (value == 'code-davinci-002') {
else if (value == 'code-davinci-002') {
return max_8k; return max_8k;
} } else if (['text-curie-001', 'text-babbage-001', 'text-ada-001'].includes(value)) {
else if (['text-curie-001', 'text-babbage-001', 'text-ada-001'].includes(value)) {
return max_2k; return max_2k;
} } else {
else {
// default to gpt-3 (4095 tokens) // default to gpt-3 (4095 tokens)
return max_4k; return max_4k;
} }
@@ -5269,8 +5248,7 @@ async function onModelChange() {
if (value && (value.includes('claude') || value.includes('palm-2'))) { if (value && (value.includes('claude') || value.includes('palm-2'))) {
oai_settings.temp_openai = Math.min(claude_max_temp, oai_settings.temp_openai); oai_settings.temp_openai = Math.min(claude_max_temp, oai_settings.temp_openai);
$('#temp_openai').attr('max', claude_max_temp).val(oai_settings.temp_openai).trigger('input'); $('#temp_openai').attr('max', claude_max_temp).val(oai_settings.temp_openai).trigger('input');
} } else {
else {
oai_settings.temp_openai = Math.min(oai_max_temp, oai_settings.temp_openai); oai_settings.temp_openai = Math.min(oai_max_temp, oai_settings.temp_openai);
$('#temp_openai').attr('max', oai_max_temp).val(oai_settings.temp_openai).trigger('input'); $('#temp_openai').attr('max', oai_max_temp).val(oai_settings.temp_openai).trigger('input');
} }
@@ -5281,17 +5259,13 @@ async function onModelChange() {
if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) { if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
if (oai_settings.max_context_unlocked) { if (oai_settings.max_context_unlocked) {
$('#openai_max_context').attr('max', unlocked_max); $('#openai_max_context').attr('max', unlocked_max);
} } else if (value.startsWith('claude-sonnet-4-5') || value.startsWith('claude-opus-4-6')) {
else if (value.startsWith('claude-sonnet-4-5') || value.startsWith('claude-opus-4-6')) {
$('#openai_max_context').attr('max', max_1mil); $('#openai_max_context').attr('max', max_1mil);
} } else if (value == 'claude-2.1' || value.startsWith('claude-3') || value.startsWith('claude-opus') || value.startsWith('claude-haiku') || value.startsWith('claude-sonnet')) {
else if (value == 'claude-2.1' || value.startsWith('claude-3') || value.startsWith('claude-opus') || value.startsWith('claude-haiku') || value.startsWith('claude-sonnet')) {
$('#openai_max_context').attr('max', max_200k); $('#openai_max_context').attr('max', max_200k);
} } else if (value.endsWith('100k') || value.startsWith('claude-2') || value === 'claude-instant-1.2') {
else if (value.endsWith('100k') || value.startsWith('claude-2') || value === 'claude-instant-1.2') {
$('#openai_max_context').attr('max', claude_100k_max); $('#openai_max_context').attr('max', claude_100k_max);
} } else {
else {
$('#openai_max_context').attr('max', claude_max); $('#openai_max_context').attr('max', claude_max);
} }
@@ -5327,23 +5301,17 @@ async function onModelChange() {
if (oai_settings.chat_completion_source === chat_completion_sources.COHERE) { if (oai_settings.chat_completion_source === chat_completion_sources.COHERE) {
if (oai_settings.max_context_unlocked) { if (oai_settings.max_context_unlocked) {
$('#openai_max_context').attr('max', unlocked_max); $('#openai_max_context').attr('max', unlocked_max);
} } else if (['command-light-nightly', 'command-light', 'command'].includes(oai_settings.cohere_model)) {
else if (['command-light-nightly', 'command-light', 'command'].includes(oai_settings.cohere_model)) {
$('#openai_max_context').attr('max', max_4k); $('#openai_max_context').attr('max', max_4k);
} } 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)) {
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)) {
$('#openai_max_context').attr('max', max_128k); $('#openai_max_context').attr('max', max_128k);
} } else if (['command-a-03-2025'].includes(oai_settings.cohere_model)) {
else if (['command-a-03-2025'].includes(oai_settings.cohere_model)) {
$('#openai_max_context').attr('max', max_256k); $('#openai_max_context').attr('max', max_256k);
} } else if (['c4ai-aya-23-8b', 'c4ai-aya-expanse-8b'].includes(oai_settings.cohere_model)) {
else if (['c4ai-aya-23-8b', 'c4ai-aya-expanse-8b'].includes(oai_settings.cohere_model)) {
$('#openai_max_context').attr('max', max_8k); $('#openai_max_context').attr('max', max_8k);
} } else if (['c4ai-aya-vision-8b', 'c4ai-aya-vision-32b'].includes(oai_settings.cohere_model)) {
else if (['c4ai-aya-vision-8b', 'c4ai-aya-vision-32b'].includes(oai_settings.cohere_model)) {
$('#openai_max_context').attr('max', max_16k); $('#openai_max_context').attr('max', max_16k);
} } else {
else {
$('#openai_max_context').attr('max', max_4k); $('#openai_max_context').attr('max', max_4k);
} }
oai_settings.openai_max_context = Math.min(Number($('#openai_max_context').attr('max')), oai_settings.openai_max_context); 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() {
if (oai_settings.chat_completion_source === chat_completion_sources.PERPLEXITY) { if (oai_settings.chat_completion_source === chat_completion_sources.PERPLEXITY) {
if (oai_settings.max_context_unlocked) { if (oai_settings.max_context_unlocked) {
$('#openai_max_context').attr('max', unlocked_max); $('#openai_max_context').attr('max', unlocked_max);
} } else if (['sonar', 'sonar-reasoning', 'sonar-reasoning-pro', 'r1-1776'].includes(oai_settings.perplexity_model)) {
else if (['sonar', 'sonar-reasoning', 'sonar-reasoning-pro', 'r1-1776'].includes(oai_settings.perplexity_model)) {
$('#openai_max_context').attr('max', 127000); $('#openai_max_context').attr('max', 127000);
} } else if (['sonar-pro'].includes(oai_settings.perplexity_model)) {
else if (['sonar-pro'].includes(oai_settings.perplexity_model)) {
$('#openai_max_context').attr('max', 200000); $('#openai_max_context').attr('max', 200000);
} } else if (oai_settings.perplexity_model.includes('llama-3.1')) {
else if (oai_settings.perplexity_model.includes('llama-3.1')) {
const isOnline = oai_settings.perplexity_model.includes('online'); const isOnline = oai_settings.perplexity_model.includes('online');
const contextSize = isOnline ? 128 * 1024 - 4000 : 128 * 1024; const contextSize = isOnline ? 128 * 1024 - 4000 : 128 * 1024;
$('#openai_max_context').attr('max', contextSize); $('#openai_max_context').attr('max', contextSize);
} } else {
else {
$('#openai_max_context').attr('max', max_128k); $('#openai_max_context').attr('max', max_128k);
} }
oai_settings.openai_max_context = Math.min(Number($('#openai_max_context').attr('max')), oai_settings.openai_max_context); 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) {
function toggleChatCompletionForms() { function toggleChatCompletionForms() {
if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) { if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
$('#model_claude_select').trigger('change'); $('#model_claude_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.OPENAI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.OPENAI) {
if (oai_settings.show_external_models && (!Array.isArray(model_list) || model_list.length == 0)) { if (oai_settings.show_external_models && (!Array.isArray(model_list) || model_list.length == 0)) {
// Wait until the models list is loaded so that we could show a proper saved model // Wait until the models list is loaded so that we could show a proper saved model
} } else {
else {
$('#model_openai_select').trigger('change'); $('#model_openai_select').trigger('change');
} }
} } else if (oai_settings.chat_completion_source == chat_completion_sources.MAKERSUITE) {
else if (oai_settings.chat_completion_source == chat_completion_sources.MAKERSUITE) {
$('#model_google_select').trigger('change'); $('#model_google_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.VERTEXAI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.VERTEXAI) {
$('#model_vertexai_select').trigger('change'); $('#model_vertexai_select').trigger('change');
// Update UI based on authentication mode // Update UI based on authentication mode
onVertexAIAuthModeChange.call($('#vertexai_auth_mode')[0]); onVertexAIAuthModeChange.call($('#vertexai_auth_mode')[0]);
} } else if (oai_settings.chat_completion_source == chat_completion_sources.OPENROUTER) {
else if (oai_settings.chat_completion_source == chat_completion_sources.OPENROUTER) {
$('#model_openrouter_select').trigger('change'); $('#model_openrouter_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.AI21) {
else if (oai_settings.chat_completion_source == chat_completion_sources.AI21) {
$('#model_ai21_select').trigger('change'); $('#model_ai21_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.MISTRALAI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.MISTRALAI) {
$('#model_mistralai_select').trigger('change'); $('#model_mistralai_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.COHERE) {
else if (oai_settings.chat_completion_source == chat_completion_sources.COHERE) {
$('#model_cohere_select').trigger('change'); $('#model_cohere_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.PERPLEXITY) {
else if (oai_settings.chat_completion_source == chat_completion_sources.PERPLEXITY) {
$('#model_perplexity_select').trigger('change'); $('#model_perplexity_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.GROQ) {
else if (oai_settings.chat_completion_source == chat_completion_sources.GROQ) {
$('#model_groq_select').trigger('change'); $('#model_groq_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.CHUTES) {
else if (oai_settings.chat_completion_source == chat_completion_sources.CHUTES) {
$('#model_chutes_select').trigger('change'); $('#model_chutes_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.SILICONFLOW) {
else if (oai_settings.chat_completion_source == chat_completion_sources.SILICONFLOW) {
$('#model_siliconflow_select').trigger('change'); $('#model_siliconflow_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB) {
else if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB) {
$('#model_electronhub_select').trigger('change'); $('#model_electronhub_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.NANOGPT) {
else if (oai_settings.chat_completion_source == chat_completion_sources.NANOGPT) {
$('#model_nanogpt_select').trigger('change'); $('#model_nanogpt_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.CUSTOM) {
else if (oai_settings.chat_completion_source == chat_completion_sources.CUSTOM) {
$('#model_custom_select').trigger('change'); $('#model_custom_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.DEEPSEEK) {
else if (oai_settings.chat_completion_source == chat_completion_sources.DEEPSEEK) {
$('#model_deepseek_select').trigger('change'); $('#model_deepseek_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.AIMLAPI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.AIMLAPI) {
$('#model_aimlapi_select').trigger('change'); $('#model_aimlapi_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.XAI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.XAI) {
$('#model_xai_select').trigger('change'); $('#model_xai_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.POLLINATIONS) {
else if (oai_settings.chat_completion_source == chat_completion_sources.POLLINATIONS) {
$('#model_pollinations_select').trigger('change'); $('#model_pollinations_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.MOONSHOT) {
else if (oai_settings.chat_completion_source == chat_completion_sources.MOONSHOT) {
$('#model_moonshot_select').trigger('change'); $('#model_moonshot_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.FIREWORKS) {
else if (oai_settings.chat_completion_source == chat_completion_sources.FIREWORKS) {
$('#model_fireworks_select').trigger('change'); $('#model_fireworks_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.COMETAPI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.COMETAPI) {
$('#model_cometapi_select').trigger('change'); $('#model_cometapi_select').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.AZURE_OPENAI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.AZURE_OPENAI) {
$('#azure_openai_model').trigger('change'); $('#azure_openai_model').trigger('change');
} } else if (oai_settings.chat_completion_source == chat_completion_sources.ZAI) {
else if (oai_settings.chat_completion_source == chat_completion_sources.ZAI) {
$('#model_zai_select').trigger('change'); $('#model_zai_select').trigger('change');
} }
@@ -5757,8 +5697,7 @@ async function testApiConnection() {
const reply = await sendOpenAIRequest('quiet', [{ 'role': 'user', 'content': 'Hi' }], new AbortController().signal); const reply = await sendOpenAIRequest('quiet', [{ 'role': 'user', 'content': 'Hi' }], new AbortController().signal);
console.log(reply); console.log(reply);
toastr.success(t`API connection successful!`); toastr.success(t`API connection successful!`);
} } catch (err) {
catch (err) {
toastr.error(t`Could not get a reply from API. Check your connection settings / API key and try again.`); toastr.error(t`Could not get a reply from API. Check your connection settings / API key and try again.`);
} }
} }
+2 -3
View File
@@ -1552,9 +1552,8 @@ async function loadPersonaForCurrentChat({ doRender = false } = {}) {
} }
toastr.success(message, t`Persona Auto Selected`, { escapeHtml: false }); toastr.success(message, t`Persona Auto Selected`, { escapeHtml: false });
} }
} } else if (chatPersona && power_user.persona_auto_lock && !chat_metadata.persona) {
// Even if it's the same persona, we still might need to auto-lock to chat if that's enabled // Even if it's the same persona, we still might need to auto-lock to chat if that's enabled
else if (chatPersona && power_user.persona_auto_lock && !chat_metadata.persona) {
await lockPersona('chat'); await lockPersona('chat');
} }
+18 -30
View File
@@ -810,9 +810,8 @@ async function CreateZenSliders(elmnt) {
handle.text(handleText) handle.text(handleText)
.css('margin-left', `${leftMargin}px`); .css('margin-left', `${leftMargin}px`);
//console.log(`${newSlider.attr('id')} initial value:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`) //console.log(`${newSlider.attr('id')} initial value:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)
} } else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
//handling creation of rep_pen_range for ooba //handling creation of rep_pen_range for ooba
else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
if ($('#rep_pen_range_textgenerationwebui_zensliders').length !== 0) { if ($('#rep_pen_range_textgenerationwebui_zensliders').length !== 0) {
$('#rep_pen_range_textgenerationwebui_zensliders').remove(); $('#rep_pen_range_textgenerationwebui_zensliders').remove();
} }
@@ -821,22 +820,19 @@ async function CreateZenSliders(elmnt) {
leftMargin = ((stepNumber) / numSteps) * 50 * -1; leftMargin = ((stepNumber) / numSteps) * 50 * -1;
if (sliderValue === offVal) { if (sliderValue === offVal) {
handleText = 'Off'; handleText = 'Off';
handle.css('color', 'rgba(128,128,128,0.5'); handle.css('color', 'rgba(128,128,128,0.5)');
} } else if (sliderValue === allVal) { handleText = 'All'; } else { handle.css('color', ''); }
else if (sliderValue === allVal) { handleText = 'All'; }
else { handle.css('color', ''); }
handle.text(handleText) handle.text(handleText)
.css('margin-left', `${leftMargin}px`); .css('margin-left', `${leftMargin}px`);
//console.log(sliderValue, handleText, offVal, allVal) //console.log(sliderValue, handleText, offVal, allVal)
//console.log(`${newSlider.attr('id')} sliderValue = ${sliderValue}, handleText:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`) //console.log(`${newSlider.attr('id')} sliderValue = ${sliderValue}, handleText:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)
originalSlider.val(steps[sliderValue]); originalSlider.val(steps[sliderValue]);
} } else {
//create all other sliders //create all other sliders
else {
var numVal = Number(sliderValue).toFixed(decimals); var numVal = Number(sliderValue).toFixed(decimals);
offVal = Number(offVal).toFixed(decimals); offVal = Number(offVal).toFixed(decimals);
if (numVal === offVal) { if (numVal === offVal) {
handle.text('Off').css('color', 'rgba(128,128,128,0.5'); handle.text('Off').css('color', 'rgba(128,128,128,0.5)');
} else { } else {
handle.text(numVal).css('color', ''); handle.text(numVal).css('color', '');
} }
@@ -928,29 +924,24 @@ async function CreateZenSliders(elmnt) {
width: ${newSlider.width()} width: ${newSlider.width()}
percent of max: ${percentOfMax} percent of max: ${percentOfMax}
left: ${leftPos}`) */ left: ${leftPos}`) */
//special handling for response length slider, pulls text aliases for step values from an array
if (newSlider.attr('id') == 'amount_gen_zenslider') { if (newSlider.attr('id') == 'amount_gen_zenslider') {
//special handling for response length slider, pulls text aliases for step values from an array
handleText = steps[stepNumber]; handleText = steps[stepNumber];
handle.text(handleText); handle.text(handleText);
newSlider.val(stepNumber); newSlider.val(stepNumber);
numVal = steps[stepNumber]; numVal = steps[stepNumber];
} } else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
//special handling for TextCompletion rep pen range slider, pulls text aliases for step values from an array //special handling for TextCompletion rep pen range slider, pulls text aliases for step values from an array
else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
handleText = steps[stepNumber]; handleText = steps[stepNumber];
handle.text(handleText); handle.text(handleText);
newSlider.val(stepNumber); newSlider.val(stepNumber);
if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5'); } 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', ''); }
else if (numVal === allVal) { handle.text('All'); }
else { handle.css('color', ''); }
numVal = steps[stepNumber]; numVal = steps[stepNumber];
} } else {
//everything else uses the flat slider value //everything else uses the flat slider value
//also note: the above sliders are not custom inputtable due to the array aliasing //also note: the above sliders are not custom inputtable due to the array aliasing
else {
//show 'off' if disabled value is set //show 'off' if disabled value is set
if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5'); } if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5)'); } else { handle.text(ui.value.toFixed(decimals)).css('color', ''); }
else { handle.text(ui.value.toFixed(decimals)).css('color', ''); }
newSlider.val(handleText); newSlider.val(handleText);
} }
//for manually typed-in values we must adjust left position because JQUI doesn't do it for us //for manually typed-in values we must adjust left position because JQUI doesn't do it for us
@@ -991,8 +982,7 @@ function switchSpoilerMode() {
$('#firstMessageWrapper').hide(); $('#firstMessageWrapper').hide();
$('#spoiler_free_desc').addClass('flex1'); $('#spoiler_free_desc').addClass('flex1');
$('#creators_note_desc_hidden').show(); $('#creators_note_desc_hidden').show();
} } else {
else {
$('#descriptionWrapper').show(); $('#descriptionWrapper').show();
$('#firstMessageWrapper').show(); $('#firstMessageWrapper').show();
$('#spoiler_free_desc').removeClass('flex1'); $('#spoiler_free_desc').removeClass('flex1');
@@ -2524,8 +2514,7 @@ async function saveTheme(name = undefined, theme = undefined) {
option.value = name; option.value = name;
option.innerText = name; option.innerText = name;
$('#themes').append(option); $('#themes').append(option);
} } else {
else {
themes[themeIndex] = theme; themes[themeIndex] = theme;
$(`#themes option[value="${name}"]`).prop('selected', true); $(`#themes option[value="${name}"]`).prop('selected', true);
} }
@@ -2632,8 +2621,7 @@ async function saveMovingUI() {
option.value = name; option.value = name;
option.innerText = name; option.innerText = name;
$('#movingUIPresets').append(option); $('#movingUIPresets').append(option);
} } else {
else {
movingUIPresets[movingUIPresetIndex] = movingUIPreset; movingUIPresets[movingUIPresetIndex] = movingUIPreset;
$(`#movingUIPresets option[value="${name}"]`).prop('selected', true); $(`#movingUIPresets option[value="${name}"]`).prop('selected', true);
} }
+2 -4
View File
@@ -608,15 +608,13 @@ class PresetManager {
presets[preset_names.indexOf(name)] = preset; presets[preset_names.indexOf(name)] = preset;
$(this.select).find(`option[value="${name}"]`).prop('selected', true); $(this.select).find(`option[value="${name}"]`).prop('selected', true);
$(this.select).val(name).trigger('change'); $(this.select).val(name).trigger('change');
} } else {
else {
const value = preset_names[name]; const value = preset_names[name];
presets[value] = preset; presets[value] = preset;
$(this.select).find(`option[value="${value}"]`).prop('selected', true); $(this.select).find(`option[value="${value}"]`).prop('selected', true);
$(this.select).val(value).trigger('change'); $(this.select).val(value).trigger('change');
} }
} } else {
else {
presets.push(preset); presets.push(preset);
const value = presets.length - 1; const value = presets.length - 1;
+1 -3
View File
@@ -246,9 +246,7 @@ async function listSamplers(main_api, arrayOnly = false) {
if (prioritizeManualSamplerSelect) { if (prioritizeManualSamplerSelect) {
finalState = isManuallyActivated; finalState = isManuallyActivated;
} } else if (!isInDefaultState) {
else if (!isInDefaultState) {
finalState = displayModified === SELECT_SAMPLER.SHOWN; finalState = displayModified === SELECT_SAMPLER.SHOWN;
customColor = finalState ? forcedOnColoring : forcedOffColoring; customColor = finalState ? forcedOnColoring : forcedOffColoring;
} }
+4 -8
View File
@@ -3026,8 +3026,7 @@ export function initDefaultSlashCommands() {
try { try {
const text = await navigator.clipboard.readText(); const text = await navigator.clipboard.readText();
return text; return text;
} } catch (error) {
catch (error) {
console.error('Error reading clipboard:', error); console.error('Error reading clipboard:', error);
toastr.warning(t`Failed to read clipboard text. Have you granted the permission?`); toastr.warning(t`Failed to read clipboard text. Have you granted the permission?`);
return ''; return '';
@@ -4432,8 +4431,7 @@ async function sendUserMessageCallback(args, text) {
const name = args.name || ''; const name = args.name || '';
const avatar = findPersonaByName(name) || user_avatar; const avatar = findPersonaByName(name) || user_avatar;
message = await sendMessageAsUser(text, bias, insertAt, compact, name, avatar); message = await sendMessageAsUser(text, bias, insertAt, compact, name, avatar);
} } else {
else {
message = await sendMessageAsUser(text, bias, insertAt, compact); message = await sendMessageAsUser(text, bias, insertAt, compact);
} }
@@ -4640,12 +4638,10 @@ export function getNameAndAvatarForMessage(character, name = null) {
let force_avatar, original_avatar; let force_avatar, original_avatar;
if (character?.avatar === currentChar?.avatar || isNeutralCharacter) { if (character?.avatar === currentChar?.avatar || isNeutralCharacter) {
// If the targeted character is the currently selected one in a solo chat, we don't need to force any avatars // If the targeted character is the currently selected one in a solo chat, we don't need to force any avatars
} } else if (character && character.avatar !== 'none') {
else if (character && character.avatar !== 'none') {
force_avatar = getThumbnailUrl('avatar', character.avatar); force_avatar = getThumbnailUrl('avatar', character.avatar);
original_avatar = character.avatar; original_avatar = character.avatar;
} } else {
else {
force_avatar = default_avatar; force_avatar = default_avatar;
original_avatar = default_avatar; original_avatar = default_avatar;
} }
+20 -32
View File
@@ -111,8 +111,8 @@ function getDelay(s) {
* @returns {AsyncGenerator<{data: object, chunk: string, reasoning?: boolean}>} The parsed data and the chunk to be sent. * @returns {AsyncGenerator<{data: object, chunk: string, reasoning?: boolean}>} The parsed data and the chunk to be sent.
*/ */
async function* parseStreamData(json) { async function* parseStreamData(json) {
// Cohere
if (typeof json.delta === 'object' && typeof json.delta.message === 'object' && ['tool-plan-delta', 'content-delta'].includes(json.type)) { if (typeof json.delta === 'object' && typeof json.delta.message === 'object' && ['tool-plan-delta', 'content-delta'].includes(json.type)) {
// Cohere
const text = json?.delta?.message?.content?.text ?? ''; const text = json?.delta?.message?.content?.text ?? '';
for (let i = 0; i < text.length; i++) { for (let i = 0; i < text.length; i++) {
const str = json.delta.message.content.text[i]; const str = json.delta.message.content.text[i];
@@ -122,9 +122,8 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
// Claude // Claude
else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
if (json.delta.text.length > 0) { if (json.delta.text.length > 0) {
for (let i = 0; i < json.delta.text.length; i++) { for (let i = 0; i < json.delta.text.length; i++) {
const str = json.delta.text[i]; const str = json.delta.text[i];
@@ -135,8 +134,8 @@ async function* parseStreamData(json) {
} }
} }
return; return;
} } else if (typeof json.delta === 'object' && typeof json.delta.thinking === 'string') {
else if (typeof json.delta === 'object' && typeof json.delta.thinking === 'string') { // Claude (reasoning content)
if (json.delta.thinking.length > 0) { if (json.delta.thinking.length > 0) {
for (let i = 0; i < json.delta.thinking.length; i++) { for (let i = 0; i < json.delta.thinking.length; i++) {
const str = json.delta.thinking[i]; const str = json.delta.thinking[i];
@@ -148,9 +147,8 @@ async function* parseStreamData(json) {
} }
} }
return; return;
} } else if (Array.isArray(json.candidates)) {
// MakerSuite // Google VertexAI / AI Studio
else if (Array.isArray(json.candidates)) {
for (let i = 0; i < json.candidates.length; i++) { for (let i = 0; i < json.candidates.length; i++) {
const isNotPrimary = json.candidates?.[0]?.index > 0; const isNotPrimary = json.candidates?.[0]?.index > 0;
const hasToolCalls = json?.candidates?.[0]?.content?.parts?.some(p => p?.functionCall); const hasToolCalls = json?.candidates?.[0]?.content?.parts?.some(p => p?.functionCall);
@@ -187,9 +185,8 @@ async function* parseStreamData(json) {
} }
} }
return; return;
} } else if (typeof json.token === 'string' && json.token.length > 0) {
// NovelAI / KoboldCpp Classic // NovelAI / KoboldCpp Classic
else if (typeof json.token === 'string' && json.token.length > 0) {
for (let i = 0; i < json.token.length; i++) { for (let i = 0; i < json.token.length; i++) {
const str = json.token[i]; const str = json.token[i];
yield { yield {
@@ -198,9 +195,8 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
// llama.cpp? // llama.cpp?
else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
const isNotPrimary = json?.index > 0; const isNotPrimary = json?.index > 0;
if (isNotPrimary) { if (isNotPrimary) {
throw new Error('Not a primary swipe', { cause: NOT_PRIMARY }); throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -213,9 +209,8 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (Array.isArray(json.choices)) {
// OpenAI-likes // OpenAI-likes and friends
else if (Array.isArray(json.choices)) {
const isNotPrimary = json?.choices?.[0]?.index > 0; const isNotPrimary = json?.choices?.[0]?.index > 0;
if (isNotPrimary || json.choices.length === 0) { if (isNotPrimary || json.choices.length === 0) {
throw new Error('Not a primary swipe', { cause: NOT_PRIMARY }); throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -233,8 +228,7 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (typeof json.choices[0].thinking === 'string' && json.choices[0].thinking.length > 0) {
else if (typeof json.choices[0].thinking === 'string' && json.choices[0].thinking.length > 0) {
for (let j = 0; j < json.choices[0].thinking.length; j++) { for (let j = 0; j < json.choices[0].thinking.length; j++) {
const str = json.choices[0].thinking[j]; const str = json.choices[0].thinking[j];
const choiceClone = structuredClone(json.choices[0]); const choiceClone = structuredClone(json.choices[0]);
@@ -247,8 +241,7 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (typeof json.choices[0].delta === 'object') {
else if (typeof json.choices[0].delta === 'object') {
if (typeof json.choices[0].delta.text === 'string' && json.choices[0].delta.text.length > 0) { if (typeof json.choices[0].delta.text === 'string' && json.choices[0].delta.text.length > 0) {
for (let j = 0; j < json.choices[0].delta.text.length; j++) { for (let j = 0; j < json.choices[0].delta.text.length; j++) {
const str = json.choices[0].delta.text[j]; const str = json.choices[0].delta.text[j];
@@ -261,8 +254,7 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (typeof json.choices[0].delta.reasoning_content === 'string' && json.choices[0].delta.reasoning_content.length > 0) {
else if (typeof json.choices[0].delta.reasoning_content === 'string' && json.choices[0].delta.reasoning_content.length > 0) {
for (let j = 0; j < json.choices[0].delta.reasoning_content.length; j++) { for (let j = 0; j < json.choices[0].delta.reasoning_content.length; j++) {
const str = json.choices[0].delta.reasoning_content[j]; const str = json.choices[0].delta.reasoning_content[j];
const isLastSymbol = j === json.choices[0].delta.reasoning_content.length - 1; const isLastSymbol = j === json.choices[0].delta.reasoning_content.length - 1;
@@ -277,8 +269,7 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (typeof json.choices[0].delta.reasoning === 'string' && json.choices[0].delta.reasoning.length > 0) {
else if (typeof json.choices[0].delta.reasoning === 'string' && json.choices[0].delta.reasoning.length > 0) {
for (let j = 0; j < json.choices[0].delta.reasoning.length; j++) { for (let j = 0; j < json.choices[0].delta.reasoning.length; j++) {
const str = json.choices[0].delta.reasoning[j]; const str = json.choices[0].delta.reasoning[j];
const isLastSymbol = j === json.choices[0].delta.reasoning.length - 1; const isLastSymbol = j === json.choices[0].delta.reasoning.length - 1;
@@ -293,8 +284,7 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (typeof json.choices[0].delta.content === 'string' && json.choices[0].delta.content.length > 0) {
else if (typeof json.choices[0].delta.content === 'string' && json.choices[0].delta.content.length > 0) {
for (let j = 0; j < json.choices[0].delta.content.length; j++) { for (let j = 0; j < json.choices[0].delta.content.length; j++) {
const str = json.choices[0].delta.content[j]; const str = json.choices[0].delta.content[j];
const choiceClone = structuredClone(json.choices[0]); const choiceClone = structuredClone(json.choices[0]);
@@ -306,8 +296,7 @@ async function* parseStreamData(json) {
}; };
} }
return; return;
} } else if (Array.isArray(json.choices[0].delta.content) && json.choices[0].delta.content.length > 0) {
else if (Array.isArray(json.choices[0].delta.content) && json.choices[0].delta.content.length > 0) {
if (Array.isArray(json.choices[0].delta.content[0].thinking) && json.choices[0].delta.content[0].thinking.length > 0) { if (Array.isArray(json.choices[0].delta.content[0].thinking) && json.choices[0].delta.content[0].thinking.length > 0) {
if (typeof json.choices[0].delta.content[0].thinking[0].text === 'string' && json.choices[0].delta.content[0].thinking[0].text.length > 0) { if (typeof json.choices[0].delta.content[0].thinking[0].text === 'string' && json.choices[0].delta.content[0].thinking[0].text.length > 0) {
for (let j = 0; j < json.choices[0].delta.content[0].thinking[0].text.length; j++) { for (let j = 0; j < json.choices[0].delta.content[0].thinking[0].text.length; j++) {
@@ -325,8 +314,7 @@ async function* parseStreamData(json) {
} }
} }
} }
} } else if (typeof json.choices[0].message === 'object') {
else if (typeof json.choices[0].message === 'object') {
if (typeof json.choices[0].message.content === 'string' && json.choices[0].message.content.length > 0) { if (typeof json.choices[0].message.content === 'string' && json.choices[0].message.content.length > 0) {
for (let j = 0; j < json.choices[0].message.content.length; j++) { for (let j = 0; j < json.choices[0].message.content.length; j++) {
const str = json.choices[0].message.content[j]; const str = json.choices[0].message.content[j];
+1 -2
View File
@@ -209,8 +209,7 @@ async function recreateStats() {
if (!response.ok) { if (!response.ok) {
toastr.error('Stats could not be loaded. Try reloading the page.'); toastr.error('Stats could not be loaded. Try reloading the page.');
throw new Error('Error getting stats'); throw new Error('Error getting stats');
} } else {
else {
toastr.success('Stats file recreated successfully!'); toastr.success('Stats file recreated successfully!');
} }
} }
+2 -4
View File
@@ -858,8 +858,7 @@ function addTagToMap(tagId, characterId = null) {
if (!Array.isArray(tag_map[key])) { if (!Array.isArray(tag_map[key])) {
tag_map[key] = [tagId]; tag_map[key] = [tagId];
return true; return true;
} } else {
else {
if (tag_map[key].includes(tagId)) if (tag_map[key].includes(tagId))
return false; return false;
@@ -885,8 +884,7 @@ function removeTagFromMap(tagId, characterId = null) {
if (!Array.isArray(tag_map[key])) { if (!Array.isArray(tag_map[key])) {
tag_map[key] = []; tag_map[key] = [];
return false; return false;
} } else {
else {
const indexOf = tag_map[key].indexOf(tagId); const indexOf = tag_map[key].indexOf(tagId);
tag_map[key].splice(indexOf, 1); tag_map[key].splice(indexOf, 1);
return indexOf !== -1; return indexOf !== -1;
+3 -6
View File
@@ -541,14 +541,11 @@ export async function loadFeatherlessModels(data) {
if (selectedCategory === 'All') { if (selectedCategory === 'All') {
return matchesSearch && matchesClass; return matchesSearch && matchesClass;
} } else if (selectedCategory === 'Top') {
else if (selectedCategory === 'Top') {
return matchesSearch && matchesClass && matchesTop; return matchesSearch && matchesClass && matchesTop;
} } else if (selectedCategory === 'New') {
else if (selectedCategory === 'New') {
return matchesSearch && matchesClass && matchesNew; return matchesSearch && matchesClass && matchesNew;
} } else {
else {
return matchesSearch && matchesClass; return matchesSearch && matchesClass;
} }
}); });
+4 -8
View File
@@ -1040,12 +1040,10 @@ export function initTextGenSettings() {
if (isCheckbox) { if (isCheckbox) {
const value = $(this).prop('checked'); const value = $(this).prop('checked');
textgenerationwebui_settings[id] = value; textgenerationwebui_settings[id] = value;
} } else if (isText) {
else if (isText) {
const value = $(this).val(); const value = $(this).val();
textgenerationwebui_settings[id] = value; textgenerationwebui_settings[id] = value;
} } else {
else {
const value = Number($(this).val()); const value = Number($(this).val());
$(`#${id}_counter_textgenerationwebui`).val(value); $(`#${id}_counter_textgenerationwebui`).val(value);
textgenerationwebui_settings[id] = value; textgenerationwebui_settings[id] = value;
@@ -1254,11 +1252,9 @@ function setSettingByName(setting, value, trigger) {
if ('send_banned_tokens' === setting) { if ('send_banned_tokens' === setting) {
$(`#${setting}_textgenerationwebui`).trigger('change'); $(`#${setting}_textgenerationwebui`).trigger('change');
} }
} } else if (isText) {
else if (isText) {
$(`#${setting}_textgenerationwebui`).val(value); $(`#${setting}_textgenerationwebui`).val(value);
} } else {
else {
const val = parseFloat(value); const val = parseFloat(value);
$(`#${setting}_textgenerationwebui`).val(val); $(`#${setting}_textgenerationwebui`).val(val);
$(`#${setting}_counter_textgenerationwebui`).val(val); $(`#${setting}_counter_textgenerationwebui`).val(val);
+31 -64
View File
@@ -603,47 +603,34 @@ export function getTokenizerModel() {
if (model?.architecture?.tokenizer === 'Llama2') { if (model?.architecture?.tokenizer === 'Llama2') {
return llamaTokenizer; return llamaTokenizer;
} } else if (model?.architecture?.tokenizer === 'Llama3') {
else if (model?.architecture?.tokenizer === 'Llama3') {
return llama3Tokenizer; return llama3Tokenizer;
} } else if (model?.architecture?.tokenizer === 'Mistral') {
else if (model?.architecture?.tokenizer === 'Mistral') {
return mistralTokenizer; return mistralTokenizer;
} } else if (model?.architecture?.tokenizer === 'Yi') {
else if (model?.architecture?.tokenizer === 'Yi') {
return yiTokenizer; return yiTokenizer;
} } else if (model?.architecture?.tokenizer === 'Gemini') {
else if (model?.architecture?.tokenizer === 'Gemini') {
return gemmaTokenizer; return gemmaTokenizer;
} } else if (model?.architecture?.tokenizer === 'Qwen') {
else if (model?.architecture?.tokenizer === 'Qwen') {
return qwen2Tokenizer; return qwen2Tokenizer;
} } else if (model?.architecture?.tokenizer === 'Cohere') {
else if (model?.architecture?.tokenizer === 'Cohere') {
if (model?.id && model?.id.includes('command-a')) { if (model?.id && model?.id.includes('command-a')) {
return commandATokenizer; return commandATokenizer;
} }
return commandRTokenizer; return commandRTokenizer;
} } else if (oai_settings.openrouter_model.includes('gpt-4o')) {
else if (oai_settings.openrouter_model.includes('gpt-4o')) {
return gpt4oTokenizer; return gpt4oTokenizer;
} } else if (oai_settings.openrouter_model.includes('gpt-4')) {
else if (oai_settings.openrouter_model.includes('gpt-4')) {
return gpt4Tokenizer; return gpt4Tokenizer;
} } else if (oai_settings.openrouter_model.includes('gpt-3.5-turbo')) {
else if (oai_settings.openrouter_model.includes('gpt-3.5-turbo')) {
return turboTokenizer; return turboTokenizer;
} } else if (oai_settings.openrouter_model.includes('claude')) {
else if (oai_settings.openrouter_model.includes('claude')) {
return claudeTokenizer; return claudeTokenizer;
} } else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
return gpt2Tokenizer; return gpt2Tokenizer;
} } else if (oai_settings.openrouter_model.includes('jamba')) {
else if (oai_settings.openrouter_model.includes('jamba')) {
return jambaTokenizer; return jambaTokenizer;
} } else if (oai_settings.openrouter_model.includes('deepseek')) {
else if (oai_settings.openrouter_model.includes('deepseek')) {
return deepseekTokenizer; return deepseekTokenizer;
} }
} }
@@ -651,50 +638,35 @@ export function getTokenizerModel() {
if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB && oai_settings.electronhub_model) { if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB && oai_settings.electronhub_model) {
if (oai_settings.electronhub_model.includes('gpt-4o') || oai_settings.electronhub_model.includes('gpt-5')) { if (oai_settings.electronhub_model.includes('gpt-4o') || oai_settings.electronhub_model.includes('gpt-5')) {
return gpt4oTokenizer; return gpt4oTokenizer;
} } else if (oai_settings.electronhub_model.includes('gpt-4.1') || oai_settings.electronhub_model.includes('gpt-4.5')) {
else if (oai_settings.electronhub_model.includes('gpt-4.1') || oai_settings.electronhub_model.includes('gpt-4.5')) {
return gpt4oTokenizer; return gpt4oTokenizer;
} } else if (oai_settings.electronhub_model.includes('gpt-4')) {
else if (oai_settings.electronhub_model.includes('gpt-4')) {
return gpt4Tokenizer; return gpt4Tokenizer;
} } else if (oai_settings.electronhub_model.includes('gpt-3.5-turbo')) {
else if (oai_settings.electronhub_model.includes('gpt-3.5-turbo')) {
return turboTokenizer; return turboTokenizer;
} } else if (oai_settings.electronhub_model.includes('claude')) {
else if (oai_settings.electronhub_model.includes('claude')) {
return claudeTokenizer; return claudeTokenizer;
} } else if (oai_settings.electronhub_model.includes('jamba')) {
else if (oai_settings.electronhub_model.includes('jamba')) {
return jambaTokenizer; return jambaTokenizer;
} } else if (oai_settings.electronhub_model.includes('deepseek') || oai_settings.electronhub_model.includes('sonar-reasoning') || oai_settings.electronhub_model.includes('r1')) {
else if (oai_settings.electronhub_model.includes('deepseek') || oai_settings.electronhub_model.includes('sonar-reasoning') || oai_settings.electronhub_model.includes('r1')) {
return deepseekTokenizer; return deepseekTokenizer;
} } else if (oai_settings.electronhub_model.includes('qwen')) {
else if (oai_settings.electronhub_model.includes('qwen')) {
return qwen2Tokenizer; return qwen2Tokenizer;
} } else if (oai_settings.electronhub_model.includes('gemma')) {
else if (oai_settings.electronhub_model.includes('gemma')) {
return gemmaTokenizer; return gemmaTokenizer;
} } else if (oai_settings.electronhub_model.includes('mistral')) {
else if (oai_settings.electronhub_model.includes('mistral')) {
return mistralTokenizer; return mistralTokenizer;
} } else if (oai_settings.electronhub_model.includes('yi')) {
else if (oai_settings.electronhub_model.includes('yi')) {
return yiTokenizer; return yiTokenizer;
} } else if (oai_settings.electronhub_model.includes('llama3') || oai_settings.electronhub_model.includes('llama-3') || oai_settings.electronhub_model.startsWith('l3')) {
else if (oai_settings.electronhub_model.includes('llama3') || oai_settings.electronhub_model.includes('llama-3') || oai_settings.electronhub_model.startsWith('l3')) {
return llama3Tokenizer; return llama3Tokenizer;
} } else if (oai_settings.electronhub_model.includes('llama')) {
else if (oai_settings.electronhub_model.includes('llama')) {
return llamaTokenizer; return llamaTokenizer;
} } else if (oai_settings.electronhub_model.includes('command-a')) {
else if (oai_settings.electronhub_model.includes('command-a')) {
return commandATokenizer; return commandATokenizer;
} } else if (oai_settings.electronhub_model.includes('command-r')) {
else if (oai_settings.electronhub_model.includes('command-r')) {
return commandRTokenizer; return commandRTokenizer;
} } else if (oai_settings.electronhub_model.includes('nemo')) {
else if (oai_settings.electronhub_model.includes('nemo')) {
return nemoTokenizer; return nemoTokenizer;
} }
} }
@@ -814,9 +786,7 @@ export function countTokensOpenAI(messages, full = false) {
if (typeof cachedCount === 'number') { if (typeof cachedCount === 'number') {
token_count += cachedCount; token_count += cachedCount;
} } else {
else {
jQuery.ajax({ jQuery.ajax({
async: false, async: false,
type: 'POST', // type: 'POST', //
@@ -866,9 +836,7 @@ export async function countTokensOpenAIAsync(messages, full = false) {
if (typeof cachedCount === 'number') { if (typeof cachedCount === 'number') {
token_count += cachedCount; token_count += cachedCount;
} } else {
else {
const data = await jQuery.ajax({ const data = await jQuery.ajax({
async: true, async: true,
type: 'POST', // type: 'POST', //
@@ -898,8 +866,7 @@ function getTokenCacheObject() {
try { try {
if (selected_group) { if (selected_group) {
chatId = groups.find(x => x.id == selected_group)?.chat_id; chatId = groups.find(x => x.id == selected_group)?.chat_id;
} } else if (this_chid !== undefined) {
else if (this_chid !== undefined) {
chatId = characters[this_chid].chat; chatId = characters[this_chid].chat;
} }
} catch { } catch {
+1 -2
View File
@@ -327,8 +327,7 @@ async function changePassword(handle, callback) {
toastr.success('Password changed successfully', 'Password Changed'); toastr.success('Password changed successfully', 'Password Changed');
callback(); callback();
} } catch (error) {
catch (error) {
console.error('Error changing password:', error); console.error('Error changing password:', error);
} }
} }
+1 -2
View File
@@ -36,8 +36,7 @@ export class SimpleMutex {
try { try {
this.isBusy = true; this.isBusy = true;
await this.callback(...args); await this.callback(...args);
} } finally {
finally {
this.isBusy = false; this.isBusy = false;
} }
} }
+1 -2
View File
@@ -388,8 +388,7 @@ async function timesCallback(args, value) {
command.breakController = new SlashCommandBreakController(); command.breakController = new SlashCommandBreakController();
command.scope.setMacro('timesIndex', i); command.scope.setMacro('timesIndex', i);
result = await command.execute(); result = await command.execute();
} } else {
else {
result = await executeSubCommands(command.replace(/\{\{timesIndex\}\}/g, i.toString()), args._scope, args._parserFlags, args._abortController); result = await executeSubCommands(command.replace(/\{\{timesIndex\}\}/g, i.toString()), args._scope, args._parserFlags, args._abortController);
} }
if (result.isAborted) break; if (result.isAborted) break;
+1 -2
View File
@@ -716,8 +716,7 @@ export async function openPermanentAssistantChat({ tryCreate = true, created = f
console.log(`Character not found for avatar ID: ${avatar}. Creating new assistant.`); console.log(`Character not found for avatar ID: ${avatar}. Creating new assistant.`);
await createPermanentAssistant(); await createPermanentAssistant();
return openPermanentAssistantChat({ tryCreate: false, created: true }); return openPermanentAssistantChat({ tryCreate: false, created: true });
} } catch (error) {
catch (error) {
console.error('Error creating permanent assistant:', error); console.error('Error creating permanent assistant:', error);
toastr.error(t`Failed to create ${neutralCharacterName}. See console for details.`); toastr.error(t`Failed to create ${neutralCharacterName}. See console for details.`);
return; return;
+7 -14
View File
@@ -351,8 +351,7 @@ class WorldInfoBuffer {
if (keyWords.length > 1) { if (keyWords.length > 1) {
return haystack.includes(transformedString); return haystack.includes(transformedString);
} } else {
else {
// Use custom boundaries to include punctuation and other non-alphanumeric characters // Use custom boundaries to include punctuation and other non-alphanumeric characters
const regex = new RegExp(`(?:^|\\W)(${escapeRegex(transformedString)})(?:$|\\W)`); const regex = new RegExp(`(?:^|\\W)(${escapeRegex(transformedString)})(?:$|\\W)`);
if (regex.test(haystack)) { if (regex.test(haystack)) {
@@ -1141,8 +1140,7 @@ function registerWorldInfoSlashCommands() {
// Also assign the book now - additional if requested, otherwise as primary // Also assign the book now - additional if requested, otherwise as primary
if (type === 'additional') { if (type === 'additional') {
await charUpdateAddAuxWorld(character.avatar, newName); await charUpdateAddAuxWorld(character.avatar, newName);
} } else {
else {
await charUpdatePrimaryWorld(newName); await charUpdatePrimaryWorld(newName);
} }
// Refresh UI, if needed // Refresh UI, if needed
@@ -2169,8 +2167,7 @@ export function sortWorldInfoEntries(data, { customSort = null } = {}) {
const bScore = worldInfoFilter.getScore(FILTER_TYPES.WORLD_INFO_SEARCH, b.uid); const bScore = worldInfoFilter.getScore(FILTER_TYPES.WORLD_INFO_SEARCH, b.uid);
return aScore - bScore; return aScore - bScore;
}; };
} } else if (sortRule === 'custom') {
else if (sortRule === 'custom') {
// First by display index // First by display index
primarySort = (a, b) => { primarySort = (a, b) => {
const aValue = a.displayIndex; const aValue = a.displayIndex;
@@ -4434,8 +4431,7 @@ export async function getSortedEntries() {
// Need to deep clone the entries to avoid modifying the cached data // Need to deep clone the entries to avoid modifying the cached data
return structuredClone(entries); return structuredClone(entries);
} } catch (e) {
catch (e) {
console.error(e); console.error(e);
return []; return [];
} }
@@ -4481,8 +4477,7 @@ function parseDecorators(content) {
if (isKnownDecorator(splited[i])) { if (isKnownDecorator(splited[i])) {
decorators.push(splited[i].startsWith('@@@') ? splited[i].substring(1) : splited[i]); decorators.push(splited[i].startsWith('@@@') ? splited[i].substring(1) : splited[i]);
fallbacked = false; fallbacked = false;
} } else {
else {
fallbacked = true; fallbacked = true;
} }
} else { } else {
@@ -5506,8 +5501,7 @@ export function checkEmbeddedWorld(chid) {
} }
}; };
callGenericPopup(html, POPUP_TYPE.CONFIRM, '', { okButton: 'Yes' }).then(checkResult); callGenericPopup(html, POPUP_TYPE.CONFIRM, '', { okButton: 'Yes' }).then(checkResult);
} } else {
else {
toastr.info( toastr.info(
'To import and use it, select "Import Card Lore" in the "More..." dropdown menu on the character panel.', 'To import and use it, select "Import Card Lore" in the "More..." dropdown menu on the character panel.',
`${characters[chid].name} has an embedded World/Lorebook`, `${characters[chid].name} has an embedded World/Lorebook`,
@@ -6121,8 +6115,7 @@ export function initWorldInfo() {
} else if (hasEmbed && !event.shiftKey) { } else if (hasEmbed && !event.shiftKey) {
await importEmbeddedWorldInfo(); await importEmbeddedWorldInfo();
saveCharacterDebounced(); saveCharacterDebounced();
} } else {
else {
openSetWorldMenu(); openSetWorldMenu();
} }
}); });
+5 -10
View File
@@ -173,8 +173,7 @@ router.post('/get', async (request, response) => {
} }
} }
} }
} } catch (err) {
catch (err) {
console.error(err); console.error(err);
} }
return response.send(output); return response.send(output);
@@ -255,8 +254,7 @@ router.post('/download', async (request, response) => {
fs.copyFileSync(temp_path, file_path); fs.copyFileSync(temp_path, file_path);
fs.unlinkSync(temp_path); fs.unlinkSync(temp_path);
response.sendStatus(200); response.sendStatus(200);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
response.sendStatus(500); response.sendStatus(500);
} }
@@ -299,15 +297,13 @@ router.post('/delete', async (request, response) => {
if (err) throw err; if (err) throw err;
}); });
console.info('Asset deleted.'); console.info('Asset deleted.');
} } else {
else {
console.error('Asset not found.'); console.error('Asset not found.');
response.sendStatus(400); response.sendStatus(400);
} }
// Move into asset place // Move into asset place
response.sendStatus(200); response.sendStatus(200);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
response.sendStatus(500); response.sendStatus(500);
} }
@@ -372,8 +368,7 @@ router.post('/character', async (request, response) => {
output.push(`/characters/${name}/${category}/${i}`); output.push(`/characters/${name}/${category}/${i}`);
} }
return response.send(output); return response.send(output);
} } catch (err) {
catch (err) {
console.error(err); console.error(err);
return response.sendStatus(500); return response.sendStatus(500);
} }
+3 -6
View File
@@ -1425,8 +1425,7 @@ async function sendElectronHubRequest(request, response) {
console.debug('Electron Hub response:', generateResponseJson); console.debug('Electron Hub response:', generateResponseJson);
return response.send(generateResponseJson); return response.send(generateResponseJson);
} }
} } catch (error) {
catch (error) {
console.error('Error communicating with Electron Hub: ', error); console.error('Error communicating with Electron Hub: ', error);
if (!response.headersSent) { if (!response.headersSent) {
response.send({ error: true }); response.send({ error: true });
@@ -1527,8 +1526,7 @@ async function sendChutesRequest(request, response) {
console.debug('Chutes response:', generateResponseJson); console.debug('Chutes response:', generateResponseJson);
return response.send(generateResponseJson); return response.send(generateResponseJson);
} }
} } catch (error) {
catch (error) {
console.error('Error communicating with Chutes: ', error); console.error('Error communicating with Chutes: ', error);
if (!response.headersSent) { if (!response.headersSent) {
response.send({ error: true }); response.send({ error: true });
@@ -1910,8 +1908,7 @@ router.post('/status', async function (request, statusResponse) {
console.warn('Chat Completion endpoint did not return a list of models.'); console.warn('Chat Completion endpoint did not return a list of models.');
} }
} }
} } else {
else {
console.error('Chat Completion status check failed. Either Access Token is incorrect or API endpoint is down.'); console.error('Chat Completion status check failed. Either Access Token is incorrect or API endpoint is down.');
statusResponse.send({ error: true, data: { data: [] } }); statusResponse.send({ error: true, data: { data: [] } });
} }
+1 -2
View File
@@ -405,8 +405,7 @@ router.post('/generate', async function (request, response) {
const completionsStream = await fetch(url, args); const completionsStream = await fetch(url, args);
// Pipe remote SSE stream to Express response // Pipe remote SSE stream to Express response
forwardFetchResponse(completionsStream, response); forwardFetchResponse(completionsStream, response);
} } else {
else {
const completionsReply = await fetch(url, args); const completionsReply = await fetch(url, args);
if (completionsReply.ok) { if (completionsReply.ok) {
+2 -4
View File
@@ -45,8 +45,7 @@ router.post('/chat/delete', async (request, response) => {
await fsPromises.unlink(filePath); await fsPromises.unlink(filePath);
return response.sendStatus(200); return response.sendStatus(200);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.sendStatus(500); return response.sendStatus(500);
} }
@@ -67,8 +66,7 @@ router.post('/chat/download', async (request, response) => {
} }
return response.download(filePath); return response.download(filePath);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.sendStatus(500); return response.sendStatus(500);
} }
+6 -11
View File
@@ -326,9 +326,8 @@ async function tryReadImage(imgPath, crop) {
try { try {
const rawImg = await Jimp.read(imgPath); const rawImg = await Jimp.read(imgPath);
return await applyAvatarCropResize(rawImg, crop); return await applyAvatarCropResize(rawImg, crop);
} } catch (error) {
// If it's an unsupported type of image (APNG) - just read the file as buffer // If it's an unsupported type of image (APNG) - just read the file as buffer
catch (error) {
console.error(`Failed to read image: ${imgPath}`, error); console.error(`Failed to read image: ${imgPath}`, error);
return fs.readFileSync(imgPath); return fs.readFileSync(imgPath);
} }
@@ -423,8 +422,7 @@ const processCharacter = async (item, directories, { shallow }) => {
character.date_last_chat = dateLastChat; character.date_last_chat = dateLastChat;
character.data_size = calculateDataSize(jsonObject?.data); character.data_size = calculateDataSize(jsonObject?.data);
return shallow ? toShallow(character) : character; return shallow ? toShallow(character) : character;
} } catch (err) {
catch (err) {
console.error(`Could not process character: ${item}`); console.error(`Could not process character: ${item}`);
if (err instanceof SyntaxError) { if (err instanceof SyntaxError) {
@@ -1081,8 +1079,7 @@ router.post('/rename', validateAvatarUrlMiddleware, async function (request, res
// Return new avatar name to ST // Return new avatar name to ST
return response.send({ avatar: newAvatarName }); return response.send({ avatar: newAvatarName });
} } catch (err) {
catch (err) {
console.error(err); console.error(err);
return response.sendStatus(500); return response.sendStatus(500);
} }
@@ -1495,8 +1492,7 @@ router.post('/duplicate', validateAvatarUrlMiddleware, async function (request,
fs.copyFileSync(filename, newFilename); fs.copyFileSync(filename, newFilename);
console.info(`${filename} was copied to ${newFilename}`); console.info(`${filename} was copied to ${newFilename}`);
response.send({ path: path.parse(newFilename).base }); response.send({ path: path.parse(newFilename).base });
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.send({ error: true }); return response.send({ error: true });
} }
@@ -1532,8 +1528,7 @@ router.post('/export', validateAvatarUrlMiddleware, async function (request, res
const jsonObject = getCharaCardV2(JSON.parse(json), request.user.directories); const jsonObject = getCharaCardV2(JSON.parse(json), request.user.directories);
unsetPrivateFields(jsonObject); unsetPrivateFields(jsonObject);
return response.type('json').send(JSON.stringify(jsonObject, null, 4)); return response.type('json').send(JSON.stringify(jsonObject, null, 4));
} } catch {
catch {
return response.sendStatus(400); return response.sendStatus(400);
} }
} }
+1 -2
View File
@@ -837,8 +837,7 @@ router.post('/group/save', async function (request, response) {
if (Array.isArray(chatData)) { if (Array.isArray(chatData)) {
await trySaveChat(chatData, chatFilePath, request.body.force, handle, String(id), request.user.directories.backups); await trySaveChat(chatData, chatFilePath, request.body.force, handle, String(id), request.user.directories.backups);
return response.send({ ok: true }); return response.send({ ok: true });
} } else {
else {
return response.status(400).send({ error: 'The request\'s body.chat is not an array.' }); return response.status(400).send({ error: 'The request\'s body.chat is not an array.' });
} }
} catch (error) { } catch (error) {
+4 -8
View File
@@ -941,12 +941,10 @@ router.post('/importURL', async (request, response) => {
if (chubParsed?.type === 'character') { if (chubParsed?.type === 'character') {
console.info('Downloading chub character:', chubParsed.id); console.info('Downloading chub character:', chubParsed.id);
result = await downloadChubCharacter(chubParsed.id); result = await downloadChubCharacter(chubParsed.id);
} } else if (chubParsed?.type === 'lorebook') {
else if (chubParsed?.type === 'lorebook') {
console.info('Downloading chub lorebook:', chubParsed.id); console.info('Downloading chub lorebook:', chubParsed.id);
result = await downloadChubLorebook(chubParsed.id); result = await downloadChubLorebook(chubParsed.id);
} } else {
else {
return response.sendStatus(404); return response.sendStatus(404);
} }
} else if (isRisu) { } else if (isRisu) {
@@ -1020,12 +1018,10 @@ router.post('/importUUID', async (request, response) => {
if (uuidType === 'character') { if (uuidType === 'character') {
console.info('Downloading chub character:', uuid); console.info('Downloading chub character:', uuid);
result = await downloadChubCharacter(uuid); result = await downloadChubCharacter(uuid);
} } else if (uuidType === 'lorebook') {
else if (uuidType === 'lorebook') {
console.info('Downloading chub lorebook:', uuid); console.info('Downloading chub lorebook:', uuid);
result = await downloadChubLorebook(uuid); result = await downloadChubLorebook(uuid);
} } else {
else {
return response.sendStatus(404); return response.sendStatus(404);
} }
} }
+1 -2
View File
@@ -145,8 +145,7 @@ router.post('/all', (request, response) => {
group.date_last_chat = date_last_chat; group.date_last_chat = date_last_chat;
group.chat_size = chat_size; group.chat_size = chat_size;
groups.push(group); groups.push(group);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
} }
}); });
+1 -2
View File
@@ -113,8 +113,7 @@ router.post('/text-models', async (request, response) => {
try { try {
const metadata = await getHordeTextModelMetadata(); const metadata = await getHordeTextModelMetadata();
data = await mergeModelsAndMetadata(data, metadata); data = await mergeModelsAndMetadata(data, metadata);
} } catch (error) {
catch (error) {
console.error('Failed to fetch metadata:', error); console.error('Failed to fetch metadata:', error);
} }
+3 -6
View File
@@ -154,8 +154,7 @@ router.post('/status', async function (req, res) {
} else if (response.status == 401) { } else if (response.status == 401) {
console.error('NovelAI Access Token is incorrect.'); console.error('NovelAI Access Token is incorrect.');
return res.send({ error: true }); return res.send({ error: true });
} } else {
else {
console.warn('NovelAI returned an error:', response.statusText); console.warn('NovelAI returned an error:', response.statusText);
return res.send({ error: true }); return res.send({ error: true });
} }
@@ -281,8 +280,7 @@ router.post('/generate', async function (req, res) {
try { try {
const data = JSON.parse(text); const data = JSON.parse(text);
message = data.message; message = data.message;
} } catch {
catch {
// ignore // ignore
} }
@@ -476,8 +474,7 @@ router.post('/generate-voice', async (request, response) => {
const buffer = Buffer.concat(chunks.map(chunk => new Uint8Array(chunk))); const buffer = Buffer.concat(chunks.map(chunk => new Uint8Array(chunk)));
response.setHeader('Content-Type', 'audio/mpeg'); response.setHeader('Content-Type', 'audio/mpeg');
return response.send(buffer); return response.send(buffer);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.sendStatus(500); return response.sendStatus(500);
} }
+1 -2
View File
@@ -262,8 +262,7 @@ router.post('/caption-image', async (request, response) => {
} }
return response.json({ caption }); return response.json({ caption });
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
response.status(500).send('Internal server error'); response.status(500).send('Internal server error');
} }
+1 -2
View File
@@ -58,8 +58,7 @@ function readAndParseFromDirectory(directoryPath, fileExtension = '.json') {
try { try {
const file = fs.readFileSync(path.join(directoryPath, item), 'utf-8'); const file = fs.readFileSync(path.join(directoryPath, item), 'utf-8');
parsedFiles.push(fileExtension == '.json' ? JSON.parse(file) : file); parsedFiles.push(fileExtension == '.json' ? JSON.parse(file) : file);
} } catch {
catch {
// skip // skip
} }
}); });
+1 -2
View File
@@ -143,8 +143,7 @@ router.get('/get', function (request, response) {
}; };
}); });
} }
} } catch (err) {
catch (err) {
console.error(err); console.error(err);
} }
return response.send(sprites); return response.send(sprites);
+4 -8
View File
@@ -1316,8 +1316,7 @@ chutes.post('/models', async (request, response) => {
const chutesData = /** @type {{items: Array<{name: string}>}} */ (data); const chutesData = /** @type {{items: Array<{name: string}>}} */ (data);
const models = chutesData.items.map(x => ({ value: x.name, text: x.name })).sort((a, b) => a?.text?.localeCompare(b?.text)); const models = chutesData.items.map(x => ({ value: x.name, text: x.name })).sort((a, b) => a?.text?.localeCompare(b?.text));
return response.send(models); return response.send(models);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.sendStatus(500); return response.sendStatus(500);
} }
@@ -1363,8 +1362,7 @@ chutes.post('/generate', async (request, response) => {
const base64 = Buffer.from(buffer).toString('base64'); const base64 = Buffer.from(buffer).toString('base64');
return response.send({ image: base64 }); return response.send({ image: base64 });
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.sendStatus(500); return response.sendStatus(500);
} }
@@ -1405,8 +1403,7 @@ nanogpt.post('/models', async (request, response) => {
const models = Object.values(imageModels).map(x => ({ value: x.model, text: x.name })); const models = Object.values(imageModels).map(x => ({ value: x.model, text: x.name }));
return response.send(models); return response.send(models);
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.sendStatus(500); return response.sendStatus(500);
} }
@@ -1447,8 +1444,7 @@ nanogpt.post('/generate', async (request, response) => {
} }
return response.send({ image }); return response.send({ image });
} } catch (error) {
catch (error) {
console.error(error); console.error(error);
return response.sendStatus(500); return response.sendStatus(500);
} }
+3 -6
View File
@@ -939,8 +939,7 @@ export function mergeMessages(messages, names, { strict = false, placeholders =
if (mergedMessages.length && placeholders) { if (mergedMessages.length && placeholders) {
if (mergedMessages[0].role === 'system' && (mergedMessages.length === 1 || mergedMessages[1].role !== 'user')) { if (mergedMessages[0].role === 'system' && (mergedMessages.length === 1 || mergedMessages[1].role !== 'user')) {
mergedMessages.splice(1, 0, { role: 'user', content: PROMPT_PLACEHOLDER }); mergedMessages.splice(1, 0, { role: 'user', content: PROMPT_PLACEHOLDER });
} } else if (mergedMessages[0].role !== 'system' && mergedMessages[0].role !== 'user') {
else if (mergedMessages[0].role !== 'system' && mergedMessages[0].role !== 'user') {
mergedMessages.unshift({ role: 'user', content: PROMPT_PLACEHOLDER }); mergedMessages.unshift({ role: 'user', content: PROMPT_PLACEHOLDER });
} }
} }
@@ -964,11 +963,9 @@ export function convertTextCompletionPrompt(messages) {
messages.forEach(m => { messages.forEach(m => {
if (m.role === 'system' && m.name === undefined) { if (m.role === 'system' && m.name === undefined) {
messageStrings.push('System: ' + m.content); messageStrings.push('System: ' + m.content);
} } else if (m.role === 'system' && m.name !== undefined) {
else if (m.role === 'system' && m.name !== undefined) {
messageStrings.push(m.name + ': ' + m.content); messageStrings.push(m.name + ': ' + m.content);
} } else {
else {
messageStrings.push(m.role + ': ' + m.content); messageStrings.push(m.role + ': ' + m.content);
} }
}); });
+1 -2
View File
@@ -680,8 +680,7 @@ export async function getUserAvatar(handle) {
const mimeType = mime.lookup(avatarPath); const mimeType = mime.lookup(avatarPath);
const base64Content = fs.readFileSync(avatarPath, 'base64'); const base64Content = fs.readFileSync(avatarPath, 'base64');
return `data:${mimeType};base64,${base64Content}`; return `data:${mimeType};base64,${base64Content}`;
} } catch {
catch {
// Ignore errors // Ignore errors
return PUBLIC_USER_AVATAR; return PUBLIC_USER_AVATAR;
} }
+3 -6
View File
@@ -157,8 +157,7 @@ export async function getVersion() {
const remoteLatest = await git.revparse([trackingBranch]); const remoteLatest = await git.revparse([trackingBranch]);
isLatest = localLatest === remoteLatest; isLatest = localLatest === remoteLatest;
} }
} } catch {
catch {
// suppress exception // suppress exception
} }
@@ -821,8 +820,7 @@ export function mergeObjectWithYaml(obj, yamlString) {
Object.assign(obj, item); Object.assign(obj, item);
} }
} }
} } else if (parsedObject && typeof parsedObject === 'object') {
else if (parsedObject && typeof parsedObject === 'object') {
Object.assign(obj, parsedObject); Object.assign(obj, parsedObject);
} }
} catch { } catch {
@@ -1307,8 +1305,7 @@ export function safeReadFileSync(filePath, options = { encoding: 'utf-8' }) {
export function setWindowTitle(title) { export function setWindowTitle(title) {
if (process.platform === 'win32') { if (process.platform === 'win32') {
process.title = title; process.title = title;
} } else {
else {
process.stdout.write(`\x1b]2;${title}\x1b\x5c`); process.stdout.write(`\x1b]2;${title}\x1b\x5c`);
} }
} }
+1 -2
View File
@@ -34,8 +34,7 @@ async function getExtrasVectorImpl(text, apiUrl, apiKey) {
try { try {
url = new URL(apiUrl); url = new URL(apiUrl);
url.pathname = '/api/embeddings/compute'; url.pathname = '/api/embeddings/compute';
} } catch (error) {
catch (error) {
console.error('Failed to set up Extras API call:', error); console.error('Failed to set up Extras API call:', error);
console.debug('Extras API URL given was:', apiUrl); console.debug('Extras API URL given was:', apiUrl);
throw error; throw error;