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.
'no-async-promise-executor': 'off',
'no-inner-declarations': 'off',
'brace-style': 'off',
// Additional formatting rules based on codebase conventions
'brace-style': ['error', '1tbs', { allowSingleLine: true }],
'array-bracket-spacing': ['error', 'never'],
'computed-property-spacing': ['error', 'never'],
'block-spacing': ['error', 'always'],
+1 -2
View File
@@ -89,8 +89,7 @@ async function installPlugin(pluginName) {
await git().clone(pluginName, pluginPath, { '--depth': 1 });
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);
}
}
+57 -121
View File
@@ -512,8 +512,7 @@ export function reloadMarkdownProcessor() {
export function getCurrentChatId() {
if (selected_group) {
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;
}
}
@@ -910,8 +909,7 @@ function getCharacterBlock(item, id) {
const description = item.data?.creator_notes || '';
if (description) {
template.find('.ch_description').text(description);
}
else {
} else {
template.find('.ch_description').hide();
}
@@ -919,8 +917,7 @@ function getCharacterBlock(item, id) {
const auxFieldValue = (item.data && item.data[auxFieldName]) || '';
if (auxFieldValue) {
template.find('.character_version').text(auxFieldValue);
}
else {
} else {
template.find('.character_version').hide();
}
@@ -1364,16 +1361,14 @@ export async function replaceCurrentChat() {
const chats = Object.values(await chatsResponse.json());
chats.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes)));
// pick existing chat
if (chats.length && typeof chats[0] === 'object') {
// pick existing chat
characters[this_chid].chat = chats[0].file_name.replace('.jsonl', '');
$('#selected_chat_pole').val(characters[this_chid].chat);
saveCharacterDebounced();
await getChat();
}
// start new chat
else {
} else {
// start new chat
characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
$('#selected_chat_pole').val(characters[this_chid].chat);
saveCharacterDebounced();
@@ -1640,11 +1635,9 @@ export async function reloadCurrentChatUnsafe() {
if (selected_group) {
await getGroupChat(selected_group, true);
}
else if (this_chid !== undefined) {
} else if (this_chid !== undefined) {
await getChat();
}
else {
} else {
resetChatState();
restoreNeutralChat();
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.
*
* 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 {ChatMessageExtra} extra - Contains the API and model details.
*/
function insertSVGIcon(mes, extra) {
// Determine the SVG filename
let modelName;
let modelName = extra?.api || '';
// Claude on OpenRouter or Anthropic
if (extra.api === 'openai' && extra.model?.toLowerCase().includes('claude')) {
modelName = 'claude';
}
// 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;
// If there's no API information, we can't determine which SVG to use
if (!modelName) {
return;
}
const insertOrReplaceSVG = (image, className, targetSelector, insertBefore) => {
@@ -3755,8 +3732,7 @@ class StreamingProcessor {
}
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`);
}
catch (err) {
} catch (err) {
// in the case of a self-inflicted abort, we have already cleaned up
if (!this.isFinished) {
console.error(err);
@@ -4236,8 +4212,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
textareaText = '';
if (chat.length && lastMessage.is_user) {
//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);
chat.length = chat.length - 1;
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 (messageBias && !removeMacros(textareaText)) {
sendSystemMessage(system_message_types.GENERIC, ' ', { bias: messageBias });
}
else {
} else {
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
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)) {
try {
adjustedParams = await adjustHordeGenerationParams(max_context, amount_gen);
}
catch {
} catch {
unblockGeneration(type);
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
if (isContinue) {
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
coreChat.push({ mes: jailbreak, is_user: true });
// 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) {
itemizedPrompts[itemizedIndex] = additionalPromptStuff;
}
else {
} else {
itemizedPrompts.push(additionalPromptStuff);
}
@@ -5350,17 +5320,14 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
if (isImpersonate) {
$('#send_textarea').val(getMessage)[0].dispatchEvent(new Event('input', { bubbles: true }));
await eventSource.emit(event_types.IMPERSONATE_READY, getMessage);
}
else if (type == 'quiet') {
} else if (type == 'quiet') {
unblockGeneration(type);
return getMessage;
}
else {
} else {
// Without streaming we'll be having a full message on continuation. Treat it as a last chunk.
if (originalType !== 'continue') {
({ 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 }));
}
@@ -5829,9 +5796,7 @@ function addChatsPreamble(mesSendString) {
function addChatsSeparator(mesSendString) {
if (power_user.context.chat_start) {
return substituteParams(power_user.context.chat_start + '\n') + mesSendString;
}
else {
} else {
return mesSendString;
}
}
@@ -7055,16 +7020,13 @@ export async function renameCharacter(name = null, { silent = false, renameChats
} else {
toastr.success(t`Character renamed!`, t`Rename Character`);
}
}
else {
} else {
throw new Error('Newly renamed character was lost?');
}
}
else {
} else {
throw new Error('Could not rename the character');
}
}
catch (error) {
} catch (error) {
// Reloading to prevent data corruption
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`);
@@ -7356,8 +7318,7 @@ export function buildAvatarList(block, entities, { templateId = 'inline_avatar_t
avatarTemplate.append(grpTemplate.children());
avatarTemplate.attr({ 'data-grid': id, 'data-chid': null });
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.find('img').attr('src', getThumbnailUrl('persona', 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);
if (messageId == this_edit_mes_id) {
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.`);
}
@@ -8134,8 +8094,7 @@ async function messageEditMove(sourceId, targetId) {
if (sourceId <= targetId) {
sourceMessageDiv.insertAfter(targetMessageDiv);
}
else {
} else {
sourceMessageDiv.insertBefore(targetMessageDiv);
}
@@ -8951,11 +8910,13 @@ export function isMessageSwipeable(messageId, message = undefined) {
//User messages are not swipeable.
!message.is_user
)
)
//The message is swipeable.
{ return true; }
//The message is not swipeable.
else { return false; }
) {
// The message is swipeable.
return true;
} else {
// The message is not swipeable.
return false;
}
}
/**
@@ -9145,8 +9106,7 @@ export async function saveChatConditional() {
if (selected_group) {
await saveGroupChat(selected_group, true);
}
else {
} else {
await saveChat();
}
@@ -9252,8 +9212,7 @@ export function closeMessageEditor(what = 'all') {
export function setGenerationProgress(progress) {
if (!progress) {
$('#send_textarea').css({ 'background': '', 'transition': '' });
}
else {
} else {
$('#send_textarea').css({
'background': `linear-gradient(90deg, #008000d6 ${progress}%, transparent ${progress}%)`,
'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';
await generation;
}
}
catch (error) {
} catch (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.
await loadFromSwipeId(mesId, chat[mesId].swipe_id);
await redisplayChat({ startIndex: mesId });
}
else {
} else {
await Popup.show.confirm(
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>`,
@@ -10104,9 +10061,8 @@ export async function swipe(event, direction, { source, repeated, message = chat
}
await standardSwipe(newSwipeId);
return;
}
//If swiping right.
else if (direction === SWIPE_DIRECTION.RIGHT) {
} else if (direction === SWIPE_DIRECTION.RIGHT) {
//If swiping right.
// make new slot in array
if (forceSwipeId == null) newSwipeId++;
@@ -10133,18 +10089,16 @@ export async function swipe(event, direction, { source, repeated, message = chat
chat[mesId].swipe_id = originalSwipeId;
await endSwipe();
return;
}
//Regenerate the message
else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
} else if (overswipe == OVERSWIPE_BEHAVIOR.REGENERATE) {
//Regenerate the message
clearMessageData(chat[mesId]);
let run_generate = true;
//Generate.
await animateSwipe(run_generate);
await endSwipe();
return;
}
// Loop to the first swipe.
else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
} else if (overswipe == OVERSWIPE_BEHAVIOR.LOOP || overswipe == OVERSWIPE_BEHAVIOR.PRISTINE_GREETING) {
// Loop to the first swipe.
newSwipeId = 0;
}
}
@@ -10363,8 +10317,7 @@ export async function doNewChat({ deleteCurrentChat = false } = {}) {
if (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
}
else {
} else {
//RossAscends: added character name to new chat filenames and replaced Date.now() with humanizedDateTime;
chat_metadata = {};
characters[this_chid].chat = `${name2} - ${humanizedDateTime()}`;
@@ -10427,8 +10380,7 @@ export async function renameGroupOrCharacterChat({ characterId, groupId, oldFile
if (groupId) {
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;
$('#selected_chat_pole').val(characters[characterId].chat);
await createOrEditCharacter();
@@ -11080,8 +11032,7 @@ jQuery(async function () {
if (popup_type == 'input') {
dialogueResolve($('#dialogue_popup_input').val());
$('#dialogue_popup_input').val('');
}
else {
} else {
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) {
let deleteCurrentChat = false;
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;
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.
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.`);
@@ -11345,22 +11292,17 @@ jQuery(async function () {
if (is_send_press == false) {
if (selected_group) {
regenerateGroup();
}
else {
} else {
is_send_press = true;
Generate('regenerate', buildOrFillAdditionalArgs());
}
}
}
else if (id == 'option_impersonate') {
} else if (id == 'option_impersonate') {
if (is_send_press == false || fromSlashCommand) {
is_send_press = true;
Generate('impersonate', buildOrFillAdditionalArgs());
}
}
else if (id == 'option_continue') {
} else if (id == 'option_continue') {
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.`);
return;
@@ -11374,17 +11316,11 @@ jQuery(async function () {
is_send_press = true;
Generate('continue', buildOrFillAdditionalArgs());
}
}
else if (id == 'option_delete_mes') {
} else if (id == 'option_delete_mes') {
setTimeout(() => openMessageDelete(fromSlashCommand), animation_duration);
}
else if (id == 'option_close_chat') {
} else if (id == 'option_close_chat') {
await closeCurrentChat();
}
else if (id === 'option_settings') {
} else if (id === 'option_settings') {
//var checkBox = document.getElementById("waifuMode");
var topBar = document.getElementById('top-bar');
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])
) {
$('#api_button_textgenerationwebui').trigger('click');
}
else if (isValidUrl(getTextGenServer())) {
} else if (isValidUrl(getTextGenServer())) {
$('#api_button_textgenerationwebui').trigger('click');
}
break;
@@ -1053,8 +1052,7 @@ export function initRossMods() {
$('#send_textarea').trigger('focus');
reasoningMesDone.trigger('click');
return;
}
else if (is_send_press == false) {
} else if (is_send_press == false) {
const skipConfirmKey = 'RegenerateWithCtrlEnter';
const skipConfirm = accountStorage.getItem(skipConfirmKey) === 'true';
function doRegenerate() {
+2 -4
View File
@@ -231,11 +231,9 @@ function onExtensionFloatingCharaPromptInput() {
!existingCharaNote.useChara
) {
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);
}
else if (avatarName && tempPrompt.length > 0) {
} else if (avatarName && tempPrompt.length > 0) {
if (!extension_settings.note.chara) {
extension_settings.note.chara = [];
}
+4 -7
View File
@@ -111,12 +111,10 @@ function getMainChatName() {
if (chat_metadata) {
if (chat_metadata.main_chat) {
return chat_metadata.main_chat;
}
// groups didn't support bookmarks before chat metadata was introduced
else if (selected_group) {
} else if (selected_group) {
// groups didn't support bookmarks before chat metadata was introduced
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);
chat_metadata.main_chat = characters[this_chid].chat.substring(0, tokenIndex).trim();
return chat_metadata.main_chat;
@@ -146,8 +144,7 @@ export function showBookmarksButtons() {
$('#option_back_to_main').hide();
$('#option_new_bookmark').show();
}
}
catch {
} catch {
$('#option_back_to_main').hide();
$('#option_new_bookmark').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)) {
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);
}
else {
} else {
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`);
callback();
}
catch (error) {
} catch (error) {
console.error('Scraping failed', error);
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');
if (isHover && isFocus) {
// 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();
hoverRules.push({ baseSelector, rule, wrappers: [...wrappers] });
} else if (isFocus) {
+3 -6
View File
@@ -278,12 +278,10 @@ async function discoverExtensions() {
if (response.ok) {
const extensions = await response.json();
return extensions;
}
else {
} else {
return [];
}
}
catch (err) {
} catch (err) {
console.error(err);
return [];
}
@@ -627,8 +625,7 @@ async function connectToApi(baseUrl) {
}
updateStatus(getExtensionsResult.ok);
}
catch {
} catch {
updateStatus(false);
}
}
+6 -12
View File
@@ -82,8 +82,7 @@ function getAuthorFromUrl(url) {
result.name = pathSegments[0];
result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`;
}
}
catch (error) {
} catch (error) {
console.debug(DEBUG_PREFIX, 'Error parsing URL:', error);
}
@@ -199,8 +198,7 @@ async function downloadAssetsList(url) {
label.removeClass('fa-trash');
label.removeClass('redOverlayGlow');
});
}
else {
} else {
console.debug(DEBUG_PREFIX, 'not installed, unchecked');
element.prop('checked', false);
element.on('click', assetInstall);
@@ -346,8 +344,7 @@ async function installAsset(url, assetType, filename) {
console.debug(DEBUG_PREFIX, 'Character downloaded.');
}
}
}
catch (err) {
} catch (err) {
console.log(err);
return [];
}
@@ -373,8 +370,7 @@ async function deleteAsset(assetType, filename) {
if (result.ok) {
console.debug(DEBUG_PREFIX, 'Deletion success.');
}
}
catch (err) {
} catch (err) {
console.log(err);
return [];
}
@@ -427,8 +423,7 @@ async function updateCurrentAssets() {
headers: getRequestHeaders({ omitContentType: true }),
});
currentAssets = result.ok ? (await result.json()) : {};
}
catch (err) {
} catch (err) {
console.log(err);
}
console.debug(DEBUG_PREFIX, 'Current assets found:', currentAssets);
@@ -490,8 +485,7 @@ jQuery(async () => {
connectButton.addClass('fa-plug-circle-exclamation');
connectButton.removeClass('redOverlayGlow');
}
}
else {
} else {
console.debug(DEBUG_PREFIX, 'Connection refused by user');
}
});
+4 -8
View File
@@ -68,8 +68,7 @@ async function setImageIcon() {
const sendButton = $('#send_picture .extensionsMenuExtensionButton');
sendButton.addClass('fa-image');
sendButton.removeClass('fa-hourglass-half');
}
catch (error) {
} catch (error) {
console.log(error);
}
}
@@ -82,8 +81,7 @@ async function setSpinnerIcon() {
const sendButton = $('#send_picture .extensionsMenuExtensionButton');
sendButton.removeClass('fa-image');
sendButton.addClass('fa-hourglass-half');
}
catch (error) {
} catch (error) {
console.log(error);
}
}
@@ -376,14 +374,12 @@ async function getCaptionForFile(file, prompt, quiet) {
await sendCaptionedMessage(caption, imagePath, file.type);
}
return caption;
}
catch (error) {
} catch (error) {
const errorMessage = error.message || 'Unknown error';
toastr.error(errorMessage, 'Failed to caption');
console.error(error);
return '';
}
finally {
} finally {
setImageIcon();
}
}
+15 -26
View File
@@ -363,8 +363,7 @@ export async function visualNovelUpdateLayers(container) {
if (power_user.reduced_motion) {
element.css('left', currentPosition + 'px');
requestAnimationFrame(() => resolve());
}
else {
} else {
element.animate({ left: currentPosition + 'px' }, 500, () => {
resolve();
});
@@ -525,8 +524,7 @@ async function moduleWorker({ newChat = false } = {}) {
}
return;
}
else {
} else {
// force reload expressions list on connect to API
if (offlineMode.is(':visible')) {
expressionsList = null;
@@ -599,11 +597,9 @@ async function moduleWorker({ newChat = false } = {}) {
}
await sendExpressionCall(spriteFolderName, expression, { force: force, vnMode: vnMode });
}
catch (error) {
} catch (error) {
console.log(error);
}
finally {
} finally {
inApiCall = false;
lastCharacter = context.groupId || context.characterId;
lastMessage = currentLastMessage.mes;
@@ -631,8 +627,7 @@ function getFolderNameByMessage(message) {
if (context.groupId) {
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();
}
@@ -1303,8 +1298,7 @@ async function getSpritesList(name) {
}
return grouped;
}
catch (err) {
} catch (err) {
console.log(err);
return [];
}
@@ -1476,9 +1470,8 @@ function chooseSpriteForExpression(spriteFolderName, expression, { prevExpressio
const searched = sprite.files.find(x => x.fileName === overrideSpriteFile);
if (searched) spriteFile = searched;
else toastr.warning(t`Couldn't find sprite file ${overrideSpriteFile} for expression ${expression}.`, t`Sprite Not Found`);
}
// Else calculate next expression, if multiple are allowed
else if (extension_settings.expressions.allowMultiple && sprite.files.length > 1) {
} else if (extension_settings.expressions.allowMultiple && sprite.files.length > 1) {
// Else calculate next expression, if multiple are allowed
let possibleFiles = sprite.files;
if (extension_settings.expressions.rerollIfSame) {
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 });
}
else {
} else {
img.attr('data-sprite-folder-name', spriteFolderName);
img.off('error');
@@ -1844,19 +1836,16 @@ async function onClickExpressionUpload(event) {
const fileNameWithoutExtension = withoutExtension(file.name);
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 there is no expression yet and it's a valid expression, we just take it
spriteName = fileNameWithoutExtension;
}
// If the filename matches the one that was clicked, we just take it and replace it
else if (clickedFileName === file.name) {
} else if (clickedFileName === file.name) {
// If the filename matches the one that was clicked, we just take it and replace it
spriteName = fileNameWithoutExtension;
}
// If it's a valid filename and there's no existing file with the same name, we just take it
else if (!matchesExisting && validFileName) {
} else if (!matchesExisting && validFileName) {
// If it's a valid filename and there's no existing file with the same name, we just take it
spriteName = fileNameWithoutExtension;
}
else {
} else {
/** @type {import('../../popup.js').CustomPopupButton[]} */
const customButtons = [];
if (clickedFileName) {
+2 -4
View File
@@ -881,11 +881,9 @@ async function summarizeChatExtras(context) {
}
setMemoryContext(summary, true);
}
catch (error) {
} catch (error) {
console.log(error);
}
finally {
} finally {
inApiCall = false;
}
}
@@ -398,8 +398,7 @@ export class QuickReply {
if (this.icon) {
icon.classList.add('fa-solid');
icon.classList.add(this.icon);
}
else {
} else {
icon.textContent = '…';
}
icon.addEventListener('click', async () => {
@@ -3021,8 +3021,7 @@ async function generatePicture(initiator, args, trigger, message, callback) {
const errorText = 'SD prompt text generation failed. ' + reason;
toastr.error(errorText, 'Image Generation');
throw new Error(errorText);
}
finally {
} finally {
$(stopButton).hide();
restoreOriginalDimensions(dimensions);
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('"', '');
$('#coqui_api_model_settings_language').append(new Option(language_label, i));
}
}
else {
} else {
$('#coqui_api_model_settings_language').hide();
}
@@ -516,8 +515,7 @@ class CoquiTtsProvider {
const speaker_label = JSON.stringify(model_settings.speakers[i]).replaceAll('"', '');
$('#coqui_api_model_settings_speaker').append(new Option(speaker_label, i));
}
}
else {
} else {
$('#coqui_api_model_settings_speaker').hide();
}
@@ -536,15 +534,13 @@ class CoquiTtsProvider {
if (model_state == 'installed') {
$('#coqui_api_model_install_status').text('Model already installed on extras server');
$('#coqui_api_model_install_button').hide();
}
else {
} else {
let action = 'download';
if (model_state == 'corrupted') {
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 });
$('#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 });
$('#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')) {
audio.play();
}
else {
} else {
ttsProvider.previewTtsVoice(id);
}
};
@@ -1452,8 +1451,7 @@ async function initVoiceMapInternal(unrestricted) {
let voiceIdsFromProvider;
try {
voiceIdsFromProvider = await ttsProvider.fetchTtsVoiceObjects();
}
catch {
} catch {
toastr.error('TTS Provider failed to return voice ids.');
}
+1 -2
View File
@@ -29,8 +29,7 @@ var speechUtteranceChunker = function (utt, settings, callback) {
callback();
}
});
}
else {
} else {
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 chunkArr = txt.match(pattRegex);
+2 -4
View File
@@ -325,8 +325,7 @@ class VITSTtsProvider {
if (streaming) {
params.append('streaming', streaming);
// Streaming response only supports MP3
}
else {
} else {
params.append('format', this.settings.format);
}
params.append('lang', lang ?? this.settings.lang);
@@ -337,8 +336,7 @@ class VITSTtsProvider {
if (model_type == this.modelTypes.W2V2_VITS) {
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('emotion', this.settings.emotion);
if (this.settings.text_prompt) {
+2 -4
View File
@@ -251,8 +251,7 @@ async function summarizeExtra(element) {
const data = await apiResult.json();
element.text = data.summary;
}
}
catch (error) {
} catch (error) {
console.log(error);
return false;
}
@@ -938,8 +937,7 @@ function throwIfSourceInvalid() {
if (!settings.alt_endpoint_url) {
throw new Error('Vectors: API URL missing', { cause: 'api_url_missing' });
}
}
else {
} else {
if (settings.source === 'ollama' && !textgenerationwebui_settings.server_urls[textgen_types.OLLAMA] ||
settings.source === 'vllm' && !textgenerationwebui_settings.server_urls[textgen_types.VLLM] ||
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
const score = _this.getScore(FILTER_TYPES.SEARCH, `${entity.type}.${entity.id}`);
return score !== undefined;
}
else {
} else {
// Compare insensitive and without accents
return includesIgnoreCaseAndAccents(entity.item?.name, searchValue);
}
+13 -25
View File
@@ -173,9 +173,8 @@ async function regenerateGroup() {
// for new generations after the update
if ((generationId && this_generationId) && generationId !== this_generationId) {
break;
}
// legacy for generations before the update
else if (lastMes.is_user || lastMes.is_system) {
} else if (lastMes.is_user || lastMes.is_system) {
// legacy for generations before the update
break;
}
@@ -392,8 +391,7 @@ export function findGroupMemberId(arg, full = false) {
console.log(`Targeting group member ${chid} (${arg}) from search result`, result[0]);
return !full ? chid : { ...{ id: chid }, ...result[0].item };
}
else {
} else {
const memberAvatar = group.members[index];
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.error(error);
}
@@ -1011,28 +1008,22 @@ async function generateGroupWrapper(byAutoMode, type = null, params = {}) {
if (activatedMembers.length === 0) {
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 });
if (activatedMembers.length === 0) {
toastr.warning(t`Deleted group member swiped. To get a reply, add them back to the group.`);
throw new Error('Deleted group member swiped');
}
}
else if (type === 'impersonate') {
} else if (type === 'impersonate') {
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);
}
else if (activationStrategy === group_activation_strategy.LIST) {
} else if (activationStrategy === group_activation_strategy.LIST) {
activatedMembers = activateListOrder(enabledMembers);
}
else if (activationStrategy === group_activation_strategy.POOLED) {
} else if (activationStrategy === group_activation_strategy.POOLED) {
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);
}
@@ -1168,8 +1159,7 @@ function activateSwipe(members, { allowSystem = false } = {}) {
break;
}
}
}
else {
} else {
activatedNames.push(lastMessage.original_avatar);
}
@@ -1704,8 +1694,7 @@ function getGroupCharacterBlock(character) {
const auxFieldValue = (character.data && character.data[auxFieldName]) || '';
if (auxFieldValue) {
template.find('.character_version').text(auxFieldValue);
}
else {
} else {
template.find('.character_version').hide();
}
@@ -1875,8 +1864,7 @@ function select_group_chats(groupId, skipAnimation) {
if (group) {
$('#rm_group_automode_label').show();
$('#rm_button_selected_ch').children('h2').text(groupName);
}
else {
} else {
$('#rm_group_automode_label').hide();
}
+1 -2
View File
@@ -126,8 +126,7 @@ export async function getStatusHorde() {
try {
const hordeStatus = await checkHordeStatus();
setOnlineStatus(hordeStatus ? t`Connected` : 'no_connection');
}
catch {
} catch {
setOnlineStatus('no_connection');
}
+1 -2
View File
@@ -220,8 +220,7 @@ function tryParseStreamingError(response, decoded) {
toastr.error(data.error.message || response.statusText, 'KoboldAI API');
throw new Error(data);
}
}
catch {
} catch {
// No JSON. Do nothing.
}
}
+4 -10
View File
@@ -117,11 +117,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
if (text.startsWith('{') && text.endsWith('}')) {
const tokens = getTextTokens(tokenizerType, text.slice(1, -1));
result.push(getBiasObject(entry.value, tokens));
}
// Raw token ids, JSON serialized
else if (text.startsWith('[') && text.endsWith(']')) {
} else if (text.startsWith('[') && text.endsWith(']')) {
// Raw token ids, JSON serialized
try {
const tokens = JSON.parse(text);
@@ -133,11 +130,8 @@ export function getLogitBiasListResult(biasPreset, tokenizerType, getBiasObject)
} catch (err) {
console.log(`Failed to parse logit bias token list: ${text}`, err);
}
}
// Text with a leading space
else {
} else {
// Text with a leading space
const biasText = ` ${text}`;
const tokens = getTextTokens(tokenizerType, biasText);
result.push(getBiasObject(entry.value, tokens));
@@ -1001,9 +1001,8 @@ class MacroCstWalker {
endOffset: element.endOffset ?? element.startOffset,
token: element,
});
}
// Handle nested CstNode (macro or argument)
else if ('children' in element) {
} else if ('children' in element) {
// Handle nested CstNode (macro or argument)
const nestedChildren = element.children || {};
const nestedEnd = /** @type {IToken?} */ ((nestedChildren['Macro.End'] || [])[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');
$('#max_context_unlocked').prop('checked', needsUnlock).trigger('change');
$('#max_context').val(preset.max_context).trigger('input');
}
else {
} else {
setGenerationParamsFromPreset(preset);
}
@@ -459,10 +458,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
const tokens = getTextTokens(tokenizerType, trimmed.slice(1, -1));
result.push(tokens);
}
// Raw token ids, JSON serialized
else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
} else if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
// Raw token ids, JSON serialized
try {
const tokens = JSON.parse(trimmed);
@@ -474,10 +471,8 @@ function getBadWordIds(banned_tokens, tokenizerType) {
} catch (err) {
console.log(`Failed to parse bad word token list: ${trimmed}`, err);
}
}
// Apply permutations
else {
} else {
// Apply permutations
const permutations = getBadWordPermutations(trimmed).map(t => getTextTokens(tokenizerType, t));
result.push(...permutations);
}
@@ -738,8 +733,7 @@ function tryParseStreamingError(response, decoded) {
toastr.error(data.message || data.error?.message || response.statusText, 'NovelAI API');
throw new Error(data);
}
}
catch {
} catch {
// No JSON. Do nothing.
}
}
+61 -122
View File
@@ -495,8 +495,7 @@ async function validateReverseProxy() {
try {
new URL(oai_settings.reverse_proxy);
}
catch (err) {
} catch (err) {
toastr.error(t`Entered reverse proxy address is not a valid URL`);
setOnlineStatus('no_connection');
resultCheckStatus();
@@ -1551,8 +1550,7 @@ export function tryParseStreamingError(response, decoded, { quiet = false } = {}
!quiet && toastr.error(data.detail?.error?.message || response.statusText, 'Chat Completion API');
throw new Error(data);
}
}
catch {
} catch {
// 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 };
}
};
}
else {
} else {
const data = await response.json();
checkQuotaError(data);
@@ -3081,8 +3078,7 @@ async function calculateLogitBias() {
});
result = await reply.json();
}
catch (err) {
} catch (err) {
result = {};
console.error(err);
}
@@ -3602,13 +3598,11 @@ export class ChatCompletion {
if (lastMessage && shouldSquash(lastMessage)) {
lastMessage.content += '\n' + message.content;
lastMessage.tokens = await tokenHandler.countAsync({ role: lastMessage.role, content: lastMessage.content });
}
else {
} else {
squashedMessages.push(message);
lastMessage = message;
}
}
else {
} else {
squashedMessages.push(message);
lastMessage = message;
}
@@ -4242,8 +4236,7 @@ async function saveOpenAIPreset(name, settings, triggerUi = true) {
Object.assign(openai_settings[value], presetBody);
$(`#settings_preset_openai option[value="${value}"]`).prop('selected', true);
if (triggerUi) $('#settings_preset_openai').trigger('change');
}
else {
} else {
openai_settings.push(presetBody);
openai_setting_names[data.name] = openai_settings.length - 1;
const option = document.createElement('option');
@@ -4692,47 +4685,33 @@ function onSettingsPresetChange() {
function getMaxContextOpenAI(value) {
if (oai_settings.max_context_unlocked) {
return unlocked_max;
}
else if (value.startsWith('gpt-5')) {
} else if (value.startsWith('gpt-5')) {
return max_400k;
}
else if (value.includes('gpt-4.1')) {
} else if (value.includes('gpt-4.1')) {
return max_1mil;
}
else if (value.includes('gpt-audio')) {
} else if (value.includes('gpt-audio')) {
return max_128k;
}
else if (value.startsWith('o1')) {
} else if (value.startsWith('o1')) {
return max_128k;
}
else if (value.startsWith('o4') || value.startsWith('o3')) {
} else if (value.startsWith('o4') || value.startsWith('o3')) {
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;
}
else if (value.includes('gpt-3.5-turbo-1106')) {
} else if (value.includes('gpt-3.5-turbo-1106')) {
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;
}
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;
}
else if (value.includes('gpt-realtime')) {
} else if (value.includes('gpt-realtime')) {
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;
}
else if (value == 'code-davinci-002') {
} else if (value == 'code-davinci-002') {
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;
}
else {
} else {
// default to gpt-3 (4095 tokens)
return max_4k;
}
@@ -5269,8 +5248,7 @@ async function onModelChange() {
if (value && (value.includes('claude') || value.includes('palm-2'))) {
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');
}
else {
} else {
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');
}
@@ -5281,17 +5259,13 @@ async function onModelChange() {
if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
if (oai_settings.max_context_unlocked) {
$('#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);
}
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);
}
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);
}
else {
} else {
$('#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.max_context_unlocked) {
$('#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);
}
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);
}
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);
}
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);
}
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);
}
else {
} else {
$('#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);
@@ -5354,19 +5322,15 @@ async function onModelChange() {
if (oai_settings.chat_completion_source === chat_completion_sources.PERPLEXITY) {
if (oai_settings.max_context_unlocked) {
$('#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);
}
else if (['sonar-pro'].includes(oai_settings.perplexity_model)) {
} else if (['sonar-pro'].includes(oai_settings.perplexity_model)) {
$('#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 contextSize = isOnline ? 128 * 1024 - 4000 : 128 * 1024;
$('#openai_max_context').attr('max', contextSize);
}
else {
} else {
$('#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);
@@ -5660,81 +5624,57 @@ async function onConnectButtonClick(e) {
function toggleChatCompletionForms() {
if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
$('#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)) {
// Wait until the models list is loaded so that we could show a proper saved model
}
else {
} else {
$('#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');
}
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');
// Update UI based on authentication mode
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
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');
}
@@ -5757,8 +5697,7 @@ async function testApiConnection() {
const reply = await sendOpenAIRequest('quiet', [{ 'role': 'user', 'content': 'Hi' }], new AbortController().signal);
console.log(reply);
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.`);
}
}
+2 -3
View File
@@ -1552,9 +1552,8 @@ async function loadPersonaForCurrentChat({ doRender = false } = {}) {
}
toastr.success(message, t`Persona Auto Selected`, { escapeHtml: false });
}
}
// 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) {
} 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
await lockPersona('chat');
}
+18 -30
View File
@@ -810,9 +810,8 @@ async function CreateZenSliders(elmnt) {
handle.text(handleText)
.css('margin-left', `${leftMargin}px`);
//console.log(`${newSlider.attr('id')} initial value:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)
}
//handling creation of rep_pen_range for ooba
else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
} else if (newSlider.attr('id') == 'rep_pen_range_textgenerationwebui_zenslider') {
//handling creation of rep_pen_range for ooba
if ($('#rep_pen_range_textgenerationwebui_zensliders').length !== 0) {
$('#rep_pen_range_textgenerationwebui_zensliders').remove();
}
@@ -821,22 +820,19 @@ async function CreateZenSliders(elmnt) {
leftMargin = ((stepNumber) / numSteps) * 50 * -1;
if (sliderValue === offVal) {
handleText = 'Off';
handle.css('color', 'rgba(128,128,128,0.5');
}
else if (sliderValue === allVal) { handleText = 'All'; }
else { handle.css('color', ''); }
handle.css('color', 'rgba(128,128,128,0.5)');
} else if (sliderValue === allVal) { handleText = 'All'; } else { handle.css('color', ''); }
handle.text(handleText)
.css('margin-left', `${leftMargin}px`);
//console.log(sliderValue, handleText, offVal, allVal)
//console.log(`${newSlider.attr('id')} sliderValue = ${sliderValue}, handleText:${handleText}, stepNum:${stepNumber}, numSteps:${numSteps}, left-margin:${leftMargin}`)
originalSlider.val(steps[sliderValue]);
}
//create all other sliders
else {
} else {
//create all other sliders
var numVal = Number(sliderValue).toFixed(decimals);
offVal = Number(offVal).toFixed(decimals);
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 {
handle.text(numVal).css('color', '');
}
@@ -928,29 +924,24 @@ async function CreateZenSliders(elmnt) {
width: ${newSlider.width()}
percent of max: ${percentOfMax}
left: ${leftPos}`) */
//special handling for response length slider, pulls text aliases for step values from an array
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];
handle.text(handleText);
newSlider.val(stepNumber);
numVal = steps[stepNumber];
}
//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') {
} 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
handleText = steps[stepNumber];
handle.text(handleText);
newSlider.val(stepNumber);
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', ''); }
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', ''); }
numVal = steps[stepNumber];
}
//everything else uses the flat slider value
//also note: the above sliders are not custom inputtable due to the array aliasing
else {
} else {
//everything else uses the flat slider value
//also note: the above sliders are not custom inputtable due to the array aliasing
//show 'off' if disabled value is set
if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5'); }
else { handle.text(ui.value.toFixed(decimals)).css('color', ''); }
if (numVal === offVal) { handle.text('Off').css('color', 'rgba(128,128,128,0.5)'); } else { handle.text(ui.value.toFixed(decimals)).css('color', ''); }
newSlider.val(handleText);
}
//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();
$('#spoiler_free_desc').addClass('flex1');
$('#creators_note_desc_hidden').show();
}
else {
} else {
$('#descriptionWrapper').show();
$('#firstMessageWrapper').show();
$('#spoiler_free_desc').removeClass('flex1');
@@ -2524,8 +2514,7 @@ async function saveTheme(name = undefined, theme = undefined) {
option.value = name;
option.innerText = name;
$('#themes').append(option);
}
else {
} else {
themes[themeIndex] = theme;
$(`#themes option[value="${name}"]`).prop('selected', true);
}
@@ -2632,8 +2621,7 @@ async function saveMovingUI() {
option.value = name;
option.innerText = name;
$('#movingUIPresets').append(option);
}
else {
} else {
movingUIPresets[movingUIPresetIndex] = movingUIPreset;
$(`#movingUIPresets option[value="${name}"]`).prop('selected', true);
}
+2 -4
View File
@@ -608,15 +608,13 @@ class PresetManager {
presets[preset_names.indexOf(name)] = preset;
$(this.select).find(`option[value="${name}"]`).prop('selected', true);
$(this.select).val(name).trigger('change');
}
else {
} else {
const value = preset_names[name];
presets[value] = preset;
$(this.select).find(`option[value="${value}"]`).prop('selected', true);
$(this.select).val(value).trigger('change');
}
}
else {
} else {
presets.push(preset);
const value = presets.length - 1;
+1 -3
View File
@@ -246,9 +246,7 @@ async function listSamplers(main_api, arrayOnly = false) {
if (prioritizeManualSamplerSelect) {
finalState = isManuallyActivated;
}
else if (!isInDefaultState) {
} else if (!isInDefaultState) {
finalState = displayModified === SELECT_SAMPLER.SHOWN;
customColor = finalState ? forcedOnColoring : forcedOffColoring;
}
+4 -8
View File
@@ -3026,8 +3026,7 @@ export function initDefaultSlashCommands() {
try {
const text = await navigator.clipboard.readText();
return text;
}
catch (error) {
} catch (error) {
console.error('Error reading clipboard:', error);
toastr.warning(t`Failed to read clipboard text. Have you granted the permission?`);
return '';
@@ -4432,8 +4431,7 @@ async function sendUserMessageCallback(args, text) {
const name = args.name || '';
const avatar = findPersonaByName(name) || user_avatar;
message = await sendMessageAsUser(text, bias, insertAt, compact, name, avatar);
}
else {
} else {
message = await sendMessageAsUser(text, bias, insertAt, compact);
}
@@ -4640,12 +4638,10 @@ export function getNameAndAvatarForMessage(character, name = null) {
let force_avatar, original_avatar;
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
}
else if (character && character.avatar !== 'none') {
} else if (character && character.avatar !== 'none') {
force_avatar = getThumbnailUrl('avatar', character.avatar);
original_avatar = character.avatar;
}
else {
} else {
force_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.
*/
async function* parseStreamData(json) {
// Cohere
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 ?? '';
for (let i = 0; i < text.length; i++) {
const str = json.delta.message.content.text[i];
@@ -122,9 +122,8 @@ async function* parseStreamData(json) {
};
}
return;
}
// Claude
else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
} else if (typeof json.delta === 'object' && typeof json.delta.text === 'string') {
// Claude
if (json.delta.text.length > 0) {
for (let i = 0; i < json.delta.text.length; i++) {
const str = json.delta.text[i];
@@ -135,8 +134,8 @@ async function* parseStreamData(json) {
}
}
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) {
for (let i = 0; i < json.delta.thinking.length; i++) {
const str = json.delta.thinking[i];
@@ -148,9 +147,8 @@ async function* parseStreamData(json) {
}
}
return;
}
// MakerSuite
else if (Array.isArray(json.candidates)) {
} else if (Array.isArray(json.candidates)) {
// Google VertexAI / AI Studio
for (let i = 0; i < json.candidates.length; i++) {
const isNotPrimary = json.candidates?.[0]?.index > 0;
const hasToolCalls = json?.candidates?.[0]?.content?.parts?.some(p => p?.functionCall);
@@ -187,9 +185,8 @@ async function* parseStreamData(json) {
}
}
return;
}
// NovelAI / KoboldCpp Classic
else if (typeof json.token === 'string' && json.token.length > 0) {
} else if (typeof json.token === 'string' && json.token.length > 0) {
// NovelAI / KoboldCpp Classic
for (let i = 0; i < json.token.length; i++) {
const str = json.token[i];
yield {
@@ -198,9 +195,8 @@ async function* parseStreamData(json) {
};
}
return;
}
// llama.cpp?
else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
} else if (typeof json.content === 'string' && json.content.length > 0 && json.object !== 'chat.completion.chunk') {
// llama.cpp?
const isNotPrimary = json?.index > 0;
if (isNotPrimary) {
throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -213,9 +209,8 @@ async function* parseStreamData(json) {
};
}
return;
}
// OpenAI-likes
else if (Array.isArray(json.choices)) {
} else if (Array.isArray(json.choices)) {
// OpenAI-likes and friends
const isNotPrimary = json?.choices?.[0]?.index > 0;
if (isNotPrimary || json.choices.length === 0) {
throw new Error('Not a primary swipe', { cause: NOT_PRIMARY });
@@ -233,8 +228,7 @@ async function* parseStreamData(json) {
};
}
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++) {
const str = json.choices[0].thinking[j];
const choiceClone = structuredClone(json.choices[0]);
@@ -247,8 +241,7 @@ async function* parseStreamData(json) {
};
}
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) {
for (let j = 0; j < json.choices[0].delta.text.length; j++) {
const str = json.choices[0].delta.text[j];
@@ -261,8 +254,7 @@ async function* parseStreamData(json) {
};
}
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++) {
const str = json.choices[0].delta.reasoning_content[j];
const isLastSymbol = j === json.choices[0].delta.reasoning_content.length - 1;
@@ -277,8 +269,7 @@ async function* parseStreamData(json) {
};
}
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++) {
const str = json.choices[0].delta.reasoning[j];
const isLastSymbol = j === json.choices[0].delta.reasoning.length - 1;
@@ -293,8 +284,7 @@ async function* parseStreamData(json) {
};
}
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++) {
const str = json.choices[0].delta.content[j];
const choiceClone = structuredClone(json.choices[0]);
@@ -306,8 +296,7 @@ async function* parseStreamData(json) {
};
}
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 (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++) {
@@ -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) {
for (let j = 0; j < json.choices[0].message.content.length; j++) {
const str = json.choices[0].message.content[j];
+1 -2
View File
@@ -209,8 +209,7 @@ async function recreateStats() {
if (!response.ok) {
toastr.error('Stats could not be loaded. Try reloading the page.');
throw new Error('Error getting stats');
}
else {
} else {
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])) {
tag_map[key] = [tagId];
return true;
}
else {
} else {
if (tag_map[key].includes(tagId))
return false;
@@ -885,8 +884,7 @@ function removeTagFromMap(tagId, characterId = null) {
if (!Array.isArray(tag_map[key])) {
tag_map[key] = [];
return false;
}
else {
} else {
const indexOf = tag_map[key].indexOf(tagId);
tag_map[key].splice(indexOf, 1);
return indexOf !== -1;
+3 -6
View File
@@ -541,14 +541,11 @@ export async function loadFeatherlessModels(data) {
if (selectedCategory === 'All') {
return matchesSearch && matchesClass;
}
else if (selectedCategory === 'Top') {
} else if (selectedCategory === 'Top') {
return matchesSearch && matchesClass && matchesTop;
}
else if (selectedCategory === 'New') {
} else if (selectedCategory === 'New') {
return matchesSearch && matchesClass && matchesNew;
}
else {
} else {
return matchesSearch && matchesClass;
}
});
+4 -8
View File
@@ -1040,12 +1040,10 @@ export function initTextGenSettings() {
if (isCheckbox) {
const value = $(this).prop('checked');
textgenerationwebui_settings[id] = value;
}
else if (isText) {
} else if (isText) {
const value = $(this).val();
textgenerationwebui_settings[id] = value;
}
else {
} else {
const value = Number($(this).val());
$(`#${id}_counter_textgenerationwebui`).val(value);
textgenerationwebui_settings[id] = value;
@@ -1254,11 +1252,9 @@ function setSettingByName(setting, value, trigger) {
if ('send_banned_tokens' === setting) {
$(`#${setting}_textgenerationwebui`).trigger('change');
}
}
else if (isText) {
} else if (isText) {
$(`#${setting}_textgenerationwebui`).val(value);
}
else {
} else {
const val = parseFloat(value);
$(`#${setting}_textgenerationwebui`).val(val);
$(`#${setting}_counter_textgenerationwebui`).val(val);
+31 -64
View File
@@ -603,47 +603,34 @@ export function getTokenizerModel() {
if (model?.architecture?.tokenizer === 'Llama2') {
return llamaTokenizer;
}
else if (model?.architecture?.tokenizer === 'Llama3') {
} else if (model?.architecture?.tokenizer === 'Llama3') {
return llama3Tokenizer;
}
else if (model?.architecture?.tokenizer === 'Mistral') {
} else if (model?.architecture?.tokenizer === 'Mistral') {
return mistralTokenizer;
}
else if (model?.architecture?.tokenizer === 'Yi') {
} else if (model?.architecture?.tokenizer === 'Yi') {
return yiTokenizer;
}
else if (model?.architecture?.tokenizer === 'Gemini') {
} else if (model?.architecture?.tokenizer === 'Gemini') {
return gemmaTokenizer;
}
else if (model?.architecture?.tokenizer === 'Qwen') {
} else if (model?.architecture?.tokenizer === 'Qwen') {
return qwen2Tokenizer;
}
else if (model?.architecture?.tokenizer === 'Cohere') {
} else if (model?.architecture?.tokenizer === 'Cohere') {
if (model?.id && model?.id.includes('command-a')) {
return commandATokenizer;
}
return commandRTokenizer;
}
else if (oai_settings.openrouter_model.includes('gpt-4o')) {
} else if (oai_settings.openrouter_model.includes('gpt-4o')) {
return gpt4oTokenizer;
}
else if (oai_settings.openrouter_model.includes('gpt-4')) {
} else if (oai_settings.openrouter_model.includes('gpt-4')) {
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;
}
else if (oai_settings.openrouter_model.includes('claude')) {
} else if (oai_settings.openrouter_model.includes('claude')) {
return claudeTokenizer;
}
else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
} else if (oai_settings.openrouter_model.includes('GPT-NeoXT')) {
return gpt2Tokenizer;
}
else if (oai_settings.openrouter_model.includes('jamba')) {
} else if (oai_settings.openrouter_model.includes('jamba')) {
return jambaTokenizer;
}
else if (oai_settings.openrouter_model.includes('deepseek')) {
} else if (oai_settings.openrouter_model.includes('deepseek')) {
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.electronhub_model.includes('gpt-4o') || oai_settings.electronhub_model.includes('gpt-5')) {
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;
}
else if (oai_settings.electronhub_model.includes('gpt-4')) {
} else if (oai_settings.electronhub_model.includes('gpt-4')) {
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;
}
else if (oai_settings.electronhub_model.includes('claude')) {
} else if (oai_settings.electronhub_model.includes('claude')) {
return claudeTokenizer;
}
else if (oai_settings.electronhub_model.includes('jamba')) {
} else if (oai_settings.electronhub_model.includes('jamba')) {
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;
}
else if (oai_settings.electronhub_model.includes('qwen')) {
} else if (oai_settings.electronhub_model.includes('qwen')) {
return qwen2Tokenizer;
}
else if (oai_settings.electronhub_model.includes('gemma')) {
} else if (oai_settings.electronhub_model.includes('gemma')) {
return gemmaTokenizer;
}
else if (oai_settings.electronhub_model.includes('mistral')) {
} else if (oai_settings.electronhub_model.includes('mistral')) {
return mistralTokenizer;
}
else if (oai_settings.electronhub_model.includes('yi')) {
} else if (oai_settings.electronhub_model.includes('yi')) {
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;
}
else if (oai_settings.electronhub_model.includes('llama')) {
} else if (oai_settings.electronhub_model.includes('llama')) {
return llamaTokenizer;
}
else if (oai_settings.electronhub_model.includes('command-a')) {
} else if (oai_settings.electronhub_model.includes('command-a')) {
return commandATokenizer;
}
else if (oai_settings.electronhub_model.includes('command-r')) {
} else if (oai_settings.electronhub_model.includes('command-r')) {
return commandRTokenizer;
}
else if (oai_settings.electronhub_model.includes('nemo')) {
} else if (oai_settings.electronhub_model.includes('nemo')) {
return nemoTokenizer;
}
}
@@ -814,9 +786,7 @@ export function countTokensOpenAI(messages, full = false) {
if (typeof cachedCount === 'number') {
token_count += cachedCount;
}
else {
} else {
jQuery.ajax({
async: false,
type: 'POST', //
@@ -866,9 +836,7 @@ export async function countTokensOpenAIAsync(messages, full = false) {
if (typeof cachedCount === 'number') {
token_count += cachedCount;
}
else {
} else {
const data = await jQuery.ajax({
async: true,
type: 'POST', //
@@ -898,8 +866,7 @@ function getTokenCacheObject() {
try {
if (selected_group) {
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;
}
} catch {
+1 -2
View File
@@ -327,8 +327,7 @@ async function changePassword(handle, callback) {
toastr.success('Password changed successfully', 'Password Changed');
callback();
}
catch (error) {
} catch (error) {
console.error('Error changing password:', error);
}
}
+1 -2
View File
@@ -36,8 +36,7 @@ export class SimpleMutex {
try {
this.isBusy = true;
await this.callback(...args);
}
finally {
} finally {
this.isBusy = false;
}
}
+1 -2
View File
@@ -388,8 +388,7 @@ async function timesCallback(args, value) {
command.breakController = new SlashCommandBreakController();
command.scope.setMacro('timesIndex', i);
result = await command.execute();
}
else {
} else {
result = await executeSubCommands(command.replace(/\{\{timesIndex\}\}/g, i.toString()), args._scope, args._parserFlags, args._abortController);
}
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.`);
await createPermanentAssistant();
return openPermanentAssistantChat({ tryCreate: false, created: true });
}
catch (error) {
} catch (error) {
console.error('Error creating permanent assistant:', error);
toastr.error(t`Failed to create ${neutralCharacterName}. See console for details.`);
return;
+7 -14
View File
@@ -351,8 +351,7 @@ class WorldInfoBuffer {
if (keyWords.length > 1) {
return haystack.includes(transformedString);
}
else {
} else {
// Use custom boundaries to include punctuation and other non-alphanumeric characters
const regex = new RegExp(`(?:^|\\W)(${escapeRegex(transformedString)})(?:$|\\W)`);
if (regex.test(haystack)) {
@@ -1141,8 +1140,7 @@ function registerWorldInfoSlashCommands() {
// Also assign the book now - additional if requested, otherwise as primary
if (type === 'additional') {
await charUpdateAddAuxWorld(character.avatar, newName);
}
else {
} else {
await charUpdatePrimaryWorld(newName);
}
// 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);
return aScore - bScore;
};
}
else if (sortRule === 'custom') {
} else if (sortRule === 'custom') {
// First by display index
primarySort = (a, b) => {
const aValue = a.displayIndex;
@@ -4434,8 +4431,7 @@ export async function getSortedEntries() {
// Need to deep clone the entries to avoid modifying the cached data
return structuredClone(entries);
}
catch (e) {
} catch (e) {
console.error(e);
return [];
}
@@ -4481,8 +4477,7 @@ function parseDecorators(content) {
if (isKnownDecorator(splited[i])) {
decorators.push(splited[i].startsWith('@@@') ? splited[i].substring(1) : splited[i]);
fallbacked = false;
}
else {
} else {
fallbacked = true;
}
} else {
@@ -5506,8 +5501,7 @@ export function checkEmbeddedWorld(chid) {
}
};
callGenericPopup(html, POPUP_TYPE.CONFIRM, '', { okButton: 'Yes' }).then(checkResult);
}
else {
} else {
toastr.info(
'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`,
@@ -6121,8 +6115,7 @@ export function initWorldInfo() {
} else if (hasEmbed && !event.shiftKey) {
await importEmbeddedWorldInfo();
saveCharacterDebounced();
}
else {
} else {
openSetWorldMenu();
}
});
+5 -10
View File
@@ -173,8 +173,7 @@ router.post('/get', async (request, response) => {
}
}
}
}
catch (err) {
} catch (err) {
console.error(err);
}
return response.send(output);
@@ -255,8 +254,7 @@ router.post('/download', async (request, response) => {
fs.copyFileSync(temp_path, file_path);
fs.unlinkSync(temp_path);
response.sendStatus(200);
}
catch (error) {
} catch (error) {
console.error(error);
response.sendStatus(500);
}
@@ -299,15 +297,13 @@ router.post('/delete', async (request, response) => {
if (err) throw err;
});
console.info('Asset deleted.');
}
else {
} else {
console.error('Asset not found.');
response.sendStatus(400);
}
// Move into asset place
response.sendStatus(200);
}
catch (error) {
} catch (error) {
console.error(error);
response.sendStatus(500);
}
@@ -372,8 +368,7 @@ router.post('/character', async (request, response) => {
output.push(`/characters/${name}/${category}/${i}`);
}
return response.send(output);
}
catch (err) {
} catch (err) {
console.error(err);
return response.sendStatus(500);
}
+3 -6
View File
@@ -1425,8 +1425,7 @@ async function sendElectronHubRequest(request, response) {
console.debug('Electron Hub response:', generateResponseJson);
return response.send(generateResponseJson);
}
}
catch (error) {
} catch (error) {
console.error('Error communicating with Electron Hub: ', error);
if (!response.headersSent) {
response.send({ error: true });
@@ -1527,8 +1526,7 @@ async function sendChutesRequest(request, response) {
console.debug('Chutes response:', generateResponseJson);
return response.send(generateResponseJson);
}
}
catch (error) {
} catch (error) {
console.error('Error communicating with Chutes: ', error);
if (!response.headersSent) {
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.');
}
}
}
else {
} else {
console.error('Chat Completion status check failed. Either Access Token is incorrect or API endpoint is down.');
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);
// Pipe remote SSE stream to Express response
forwardFetchResponse(completionsStream, response);
}
else {
} else {
const completionsReply = await fetch(url, args);
if (completionsReply.ok) {
+2 -4
View File
@@ -45,8 +45,7 @@ router.post('/chat/delete', async (request, response) => {
await fsPromises.unlink(filePath);
return response.sendStatus(200);
}
catch (error) {
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
@@ -67,8 +66,7 @@ router.post('/chat/download', async (request, response) => {
}
return response.download(filePath);
}
catch (error) {
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
+6 -11
View File
@@ -326,9 +326,8 @@ async function tryReadImage(imgPath, crop) {
try {
const rawImg = await Jimp.read(imgPath);
return await applyAvatarCropResize(rawImg, crop);
}
// If it's an unsupported type of image (APNG) - just read the file as buffer
catch (error) {
} catch (error) {
// If it's an unsupported type of image (APNG) - just read the file as buffer
console.error(`Failed to read image: ${imgPath}`, error);
return fs.readFileSync(imgPath);
}
@@ -423,8 +422,7 @@ const processCharacter = async (item, directories, { shallow }) => {
character.date_last_chat = dateLastChat;
character.data_size = calculateDataSize(jsonObject?.data);
return shallow ? toShallow(character) : character;
}
catch (err) {
} catch (err) {
console.error(`Could not process character: ${item}`);
if (err instanceof SyntaxError) {
@@ -1081,8 +1079,7 @@ router.post('/rename', validateAvatarUrlMiddleware, async function (request, res
// Return new avatar name to ST
return response.send({ avatar: newAvatarName });
}
catch (err) {
} catch (err) {
console.error(err);
return response.sendStatus(500);
}
@@ -1495,8 +1492,7 @@ router.post('/duplicate', validateAvatarUrlMiddleware, async function (request,
fs.copyFileSync(filename, newFilename);
console.info(`${filename} was copied to ${newFilename}`);
response.send({ path: path.parse(newFilename).base });
}
catch (error) {
} catch (error) {
console.error(error);
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);
unsetPrivateFields(jsonObject);
return response.type('json').send(JSON.stringify(jsonObject, null, 4));
}
catch {
} catch {
return response.sendStatus(400);
}
}
+1 -2
View File
@@ -837,8 +837,7 @@ router.post('/group/save', async function (request, response) {
if (Array.isArray(chatData)) {
await trySaveChat(chatData, chatFilePath, request.body.force, handle, String(id), request.user.directories.backups);
return response.send({ ok: true });
}
else {
} else {
return response.status(400).send({ error: 'The request\'s body.chat is not an array.' });
}
} catch (error) {
+4 -8
View File
@@ -941,12 +941,10 @@ router.post('/importURL', async (request, response) => {
if (chubParsed?.type === 'character') {
console.info('Downloading chub character:', chubParsed.id);
result = await downloadChubCharacter(chubParsed.id);
}
else if (chubParsed?.type === 'lorebook') {
} else if (chubParsed?.type === 'lorebook') {
console.info('Downloading chub lorebook:', chubParsed.id);
result = await downloadChubLorebook(chubParsed.id);
}
else {
} else {
return response.sendStatus(404);
}
} else if (isRisu) {
@@ -1020,12 +1018,10 @@ router.post('/importUUID', async (request, response) => {
if (uuidType === 'character') {
console.info('Downloading chub character:', uuid);
result = await downloadChubCharacter(uuid);
}
else if (uuidType === 'lorebook') {
} else if (uuidType === 'lorebook') {
console.info('Downloading chub lorebook:', uuid);
result = await downloadChubLorebook(uuid);
}
else {
} else {
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.chat_size = chat_size;
groups.push(group);
}
catch (error) {
} catch (error) {
console.error(error);
}
});
+1 -2
View File
@@ -113,8 +113,7 @@ router.post('/text-models', async (request, response) => {
try {
const metadata = await getHordeTextModelMetadata();
data = await mergeModelsAndMetadata(data, metadata);
}
catch (error) {
} catch (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) {
console.error('NovelAI Access Token is incorrect.');
return res.send({ error: true });
}
else {
} else {
console.warn('NovelAI returned an error:', response.statusText);
return res.send({ error: true });
}
@@ -281,8 +280,7 @@ router.post('/generate', async function (req, res) {
try {
const data = JSON.parse(text);
message = data.message;
}
catch {
} catch {
// ignore
}
@@ -476,8 +474,7 @@ router.post('/generate-voice', async (request, response) => {
const buffer = Buffer.concat(chunks.map(chunk => new Uint8Array(chunk)));
response.setHeader('Content-Type', 'audio/mpeg');
return response.send(buffer);
}
catch (error) {
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
+1 -2
View File
@@ -262,8 +262,7 @@ router.post('/caption-image', async (request, response) => {
}
return response.json({ caption });
}
catch (error) {
} catch (error) {
console.error(error);
response.status(500).send('Internal server error');
}
+1 -2
View File
@@ -58,8 +58,7 @@ function readAndParseFromDirectory(directoryPath, fileExtension = '.json') {
try {
const file = fs.readFileSync(path.join(directoryPath, item), 'utf-8');
parsedFiles.push(fileExtension == '.json' ? JSON.parse(file) : file);
}
catch {
} catch {
// skip
}
});
+1 -2
View File
@@ -143,8 +143,7 @@ router.get('/get', function (request, response) {
};
});
}
}
catch (err) {
} catch (err) {
console.error(err);
}
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 models = chutesData.items.map(x => ({ value: x.name, text: x.name })).sort((a, b) => a?.text?.localeCompare(b?.text));
return response.send(models);
}
catch (error) {
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
@@ -1363,8 +1362,7 @@ chutes.post('/generate', async (request, response) => {
const base64 = Buffer.from(buffer).toString('base64');
return response.send({ image: base64 });
}
catch (error) {
} catch (error) {
console.error(error);
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 }));
return response.send(models);
}
catch (error) {
} catch (error) {
console.error(error);
return response.sendStatus(500);
}
@@ -1447,8 +1444,7 @@ nanogpt.post('/generate', async (request, response) => {
}
return response.send({ image });
}
catch (error) {
} catch (error) {
console.error(error);
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[0].role === 'system' && (mergedMessages.length === 1 || mergedMessages[1].role !== 'user')) {
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 });
}
}
@@ -964,11 +963,9 @@ export function convertTextCompletionPrompt(messages) {
messages.forEach(m => {
if (m.role === 'system' && m.name === undefined) {
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);
}
else {
} else {
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 base64Content = fs.readFileSync(avatarPath, 'base64');
return `data:${mimeType};base64,${base64Content}`;
}
catch {
} catch {
// Ignore errors
return PUBLIC_USER_AVATAR;
}
+3 -6
View File
@@ -157,8 +157,7 @@ export async function getVersion() {
const remoteLatest = await git.revparse([trackingBranch]);
isLatest = localLatest === remoteLatest;
}
}
catch {
} catch {
// suppress exception
}
@@ -821,8 +820,7 @@ export function mergeObjectWithYaml(obj, yamlString) {
Object.assign(obj, item);
}
}
}
else if (parsedObject && typeof parsedObject === 'object') {
} else if (parsedObject && typeof parsedObject === 'object') {
Object.assign(obj, parsedObject);
}
} catch {
@@ -1307,8 +1305,7 @@ export function safeReadFileSync(filePath, options = { encoding: 'utf-8' }) {
export function setWindowTitle(title) {
if (process.platform === 'win32') {
process.title = title;
}
else {
} else {
process.stdout.write(`\x1b]2;${title}\x1b\x5c`);
}
}
+1 -2
View File
@@ -34,8 +34,7 @@ async function getExtrasVectorImpl(text, apiUrl, apiKey) {
try {
url = new URL(apiUrl);
url.pathname = '/api/embeddings/compute';
}
catch (error) {
} catch (error) {
console.error('Failed to set up Extras API call:', error);
console.debug('Extras API URL given was:', apiUrl);
throw error;