Compare commits

..
Author SHA1 Message Date
Cohee 51ad27fb86 Merge pull request #5591 from SillyTavern/staging
Staging
2026-05-03 18:45:46 +03:00
20 changed files with 75 additions and 512 deletions
-6
View File
@@ -809,21 +809,18 @@
<div class="inline-drawer-content">
<div class="range-block m-t-1">
<div class="justifyLeft" data-i18n="Main">Main</div>
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="main_prompt_quick_edit_textarea" data-i18n="[title]Expand the editor"></i>
<div class="wide100p">
<textarea id="main_prompt_quick_edit_textarea" class="text_pole textarea_compact autoSetHeight" rows="6" placeholder="&mdash;" data-pm-prompt="main"></textarea>
</div>
</div>
<div class="range-block m-t-1">
<div class="justifyLeft" data-i18n="Auxiliary">Auxiliary</div>
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="nsfw_prompt_quick_edit_textarea" data-i18n="[title]Expand the editor"></i>
<div class="wide100p">
<textarea id="nsfw_prompt_quick_edit_textarea" class="text_pole textarea_compact autoSetHeight" rows="6" placeholder="&mdash;" data-pm-prompt="nsfw"></textarea>
</div>
</div>
<div class="range-block m-t-1">
<div class="justifyLeft" data-i18n="Post-History Instructions">Post-History Instructions</div>
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="jailbreak_prompt_quick_edit_textarea" data-i18n="[title]Expand the editor"></i>
<div class="wide100p">
<textarea id="jailbreak_prompt_quick_edit_textarea" class="text_pole textarea_compact autoSetHeight" rows="6" placeholder="&mdash;" data-pm-prompt="jailbreak"></textarea>
</div>
@@ -2147,9 +2144,6 @@
<span data-i18n="Allows the model to return its thinking process.">
Allows the model to return its thinking process.
</span>
<strong data-i18n="This setting enables or disables reasoning generation by the model." data-source="deepseek,zai,moonshot">
This setting enables or disables reasoning generation by the model.
</strong>
<strong data-i18n="This setting affects visibility only." data-source-mode="except" data-source="zai,moonshot,openrouter,deepseek">
This setting affects visibility only.
</strong>
+1 -1
View File
@@ -96,7 +96,7 @@ function setNotePositionCommand(_, text) {
return;
}
$(`input[name="extension_floating_position"][value="${position}"]`).prop('checked', true).trigger('input').trigger('change');
$(`input[name="extension_floating_position"][value="${position}"]`).prop('checked', true).trigger('input');
toastr.info(t`Author's Note position updated`);
}
return Object.keys(validPositions).find(key => validPositions[key] == chat_metadata[metadata_keys.position]);
+2 -10
View File
@@ -126,17 +126,9 @@ export class AutoComplete {
});
textarea.addEventListener('blur', () => this.hide());
if (isFloating) {
textarea.addEventListener('scroll', () => {
if (this.isActive) {
this.updateFloatingPositionDebounced();
}
});
textarea.addEventListener('scroll', () => this.updateFloatingPositionDebounced());
}
window.addEventListener('resize', () => {
if (this.isActive) {
this.updatePositionDebounced();
}
});
window.addEventListener('resize', () => this.updatePositionDebounced());
}
/**
+2 -2
View File
@@ -94,7 +94,7 @@ async function getBookmarkName({ isReplace = false, forceName = null } = {}) {
return `${cleanName} - ${bookmarkNameToken}${i}`;
}
const existingChats = await getExistingChatNames();
const suggestedName = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildCheckpointName, startIndex: 1 });
const suggestedName = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildCheckpointName });
const body = await renderTemplateAsync('createCheckpoint', { isReplace: isReplace, suggestedName: suggestedName });
let name = forceName ?? await Popup.show.input('Create Checkpoint', body, suggestedName);
@@ -212,7 +212,7 @@ export async function createBranch(mesId, { swipeId = null } = {}) {
return `${cleanName} - Branch #${i}`;
}
const existingChats = await getExistingChatNames();
const name = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildBranchName, startIndex: 1 });
const name = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildBranchName });
if (!name) {
console.error('Could not generate a unique branch name.');
toastr.error('Could not generate a unique branch name.', 'Branch creation failed');
-64
View File
@@ -2,7 +2,6 @@ import { throttle } from './utils.js';
export function initDomHandlers() {
handleInputWheel();
handleNumberInputConstraints();
}
/**
@@ -65,66 +64,3 @@ function handleInputWheel() {
}
}, { passive: false });
}
/**
* Enforces min/max constraints on number inputs when users manually type values.
* Browsers only enforce min/max when using the spinner arrows or keyboard, not on manual input.
* This listener catches the 'change' event (fires on blur after editing) and clamps the value.
*/
function handleNumberInputConstraints() {
document.addEventListener('change', (e) => {
const target = e.target;
// Only handle number inputs with both min and max defined
if (!(target instanceof HTMLInputElement) || target.type !== 'number') return;
const min = target.getAttribute('min');
const max = target.getAttribute('max');
if (min === null && max === null) return;
const minVal = min !== null ? parseFloat(min) : NaN;
const maxVal = max !== null ? parseFloat(max) : NaN;
const currentVal = parseFloat(target.value);
// Skip if current value is not a valid number
if (isNaN(currentVal)) return;
// Skip if min/max are defined but invalid
if ((min !== null && isNaN(minVal)) || (max !== null && isNaN(maxVal))) return;
// Check if value is out of bounds
let needsClamp = false;
let newValue = currentVal;
if (min !== null && currentVal < minVal) {
newValue = minVal;
needsClamp = true;
} else if (max !== null && currentVal > maxVal) {
newValue = maxVal;
needsClamp = true;
}
if (!needsClamp) return;
// Apply step alignment if step is defined (like browser native behavior)
const step = target.getAttribute('step');
if (step !== null) {
const stepVal = parseFloat(step);
if (!isNaN(stepVal) && stepVal > 0) {
newValue = Math.round(newValue / stepVal) * stepVal;
// Re-clamp after step alignment if bounds exist
if (min !== null) newValue = Math.max(minVal, newValue);
if (max !== null) newValue = Math.min(maxVal, newValue);
}
}
// Fix floating point precision
newValue = Math.round(newValue * 1e10) / 1e10;
// Update the value
target.value = newValue.toString();
// Trigger input event so existing handlers fire (e.g., sampler settings update)
// Use jQuery trigger to ensure both jQuery and native handlers are called
$(target).trigger('input');
}, { passive: true });
}
+33 -176
View File
@@ -18,8 +18,6 @@ import { generateWebLlmChatPrompt, isWebLlmSupported } from '../shared.js';
import { Popup, POPUP_RESULT } from '../../popup.js';
import { t } from '../../i18n.js';
import { removeReasoningFromString } from '../../reasoning.js';
import { macros } from '../../macros/macro-system.js';
import { MacrosParser } from '/scripts/macros.js';
export { MODULE_NAME };
/**
@@ -105,19 +103,6 @@ let lastServerResponseTime = 0;
/** @type {{[characterName: string]: string}} */
export let lastExpression = {};
/**
* Gets the current fallback expression, including the labels for when it is not set
* @returns {string|null}
*/
function getCurrentFallbackExpression() {
const expression = extension_settings?.expressions.fallback_expression;
const showEmojis = extension_settings?.expressions?.showDefault;
if (!expression && showEmojis) return OPTION_EMOJI_FALLBACK;
if (!expression) return OPTION_NO_FALLBACK;
return expression;
}
/**
* Returns a placeholder image object for a given expression
* @param {string} expression - The expression label
@@ -801,48 +786,13 @@ async function setSpriteSlashCommand({ type }, searchTerm) {
return label;
}
/**
* Get all the currently set expression labels.
* @param {Object} args
* @param {'true'|'false'|'only'} [args.custom] - Whether to filter out or return only custom expressions
* @param {'true'|'false'} [args.filter] - Filter the list to only include expressions that have available sprites for the current character
* @param {import('../../slash-commands/SlashCommandReturnHelper.js').SlashCommandReturnType} [args.return] - In which format must the expressions be returned
* @param {string} characterName
* @returns {Promise<string>}
*/
async function getExpressionListSlashCommand(args, characterName) {
const { custom, filter = 'true', return: returnType = 'pipe' } = args;
const expressions = await getExpressionsList({ filterAvailable: !isFalseBoolean(filter) });
const customExpressions = extension_settings?.expressions?.custom || [];
const expressionsMap = {
default: expressions.filter(expression => !customExpressions.includes(expression)),
custom: customExpressions,
all: expressions,
};
let expressionIndex = 'all';
if (custom === 'false') expressionIndex = 'default';
if (custom === 'only') expressionIndex = 'custom';
try {
return await slashCommandReturnHelper.doReturn(returnType, expressionsMap[expressionIndex], {
objectToStringFunc: list => list.join(', '),
});
} catch (err) {
console.error(err);
return '';
}
}
/**
* @param {string} expressionName - Label of the expression to set as fallback
*/
function setFallBackExpressionSlashCommand(args, expressionName) {
expressionName = expressionName.trim().toLowerCase();
if (!expressionName) return getCurrentFallbackExpression();
if (!expressionName) return extension_settings?.expressions?.fallback_expression || '';
const select = /** @type {HTMLSelectElement} */(document.getElementById('expression_fallback'));
const fallbackExpressions = Array
@@ -1201,24 +1151,15 @@ export async function getExpressionLabel(text, expressionsApi = extension_settin
}
}
/**
* @param {Object} [options]
* @param {string} [options.characterName] Filters last message to the one of the target character
*/
function getLastCharacterMessage({ characterName = '' } = {}) {
function getLastCharacterMessage() {
const context = getContext();
const reversedChat = context.chat.slice().reverse();
const ignoreCharName = !characterName;
for (let mes of reversedChat) {
if (mes.is_user || mes.is_system || mes.extra?.type === system_message_types.NARRATOR) {
continue;
}
if (!ignoreCharName && mes.name !== characterName) {
continue;
}
return { mes: mes.mes, name: mes.name, original_avatar: mes.original_avatar, force_avatar: mes.force_avatar };
}
@@ -1522,30 +1463,6 @@ export async function getExpressionsList({ filterAvailable = false } = {}) {
}
}
/**
* Gets the last expression used in the chat by the active character.
* @param {Object} [options]
* @param {string} [options.characterName] Filters last expression to the one of the target character instead
* @returns {string}
*/
function getLastExpression({ characterName = '' } = {}) {
if (typeof characterName !== 'string') throw new Error('Character name must be a string');
if (!characterName) {
characterName = characters[this_chid]?.avatar || '';
}
const char = findChar({ name: characterName, quiet: true });
const currentLastMessage = getLastCharacterMessage({ characterName });
const finalCharacterName = currentLastMessage?.name ?? char?.name ?? characterName;
const spriteFolderName = getSpriteFolderName(currentLastMessage, finalCharacterName);
const sprite = lastExpression[spriteFolderName.split('/')[0]] ?? '';
return sprite;
}
/**
* Selects a sprite from the given sprite folder for the given expression.
*
@@ -2434,15 +2351,15 @@ export async function init() {
typeList: [ARGUMENT_TYPE.STRING],
isRequired: false,
enumProvider: () => [
new SlashCommandEnumValue(OPTION_NO_FALLBACK, 'Sets the fallback expression to no image'),
new SlashCommandEnumValue(OPTION_EMOJI_FALLBACK, 'Sets the fallback expression to emojis'),
new SlashCommandEnumValue('#none', 'Sets the fallback expression to no image'),
new SlashCommandEnumValue('#emoji', 'Sets the fallback expression to emojis'),
...localEnumProviders.expressions(),
],
}),
],
helpString: `
<div>
Gets the currently selected global fallback expression.<br />
Gets the currently selected expression fallback for all characters.<br />
If a valid expression label is sent, it will be set as the new fallback.
</div>
<div>
@@ -2493,8 +2410,23 @@ export async function init() {
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'expression-last',
aliases: ['lastsprite'],
/** @type {(args: object, name: string) => string} */
callback: (_, name) => getLastExpression({ characterName: (name || '') }),
/** @type {(args: object, name: string) => Promise<string>} */
callback: async (_, name) => {
if (typeof name !== 'string') throw new Error('name must be a string');
if (!name) {
if (selected_group) {
toastr.error(t`In group chats, you must specify a character name.`, t`No character name specified`);
return '';
}
name = characters[this_chid]?.avatar;
}
const char = findChar({ name: name });
if (!char) toastr.warning(t`Couldn't find character ${name}.`, t`Character not found`);
const sprite = lastExpression[char?.name ?? name] ?? '';
return sprite;
},
returns: 'the last set expression for the named character.',
unnamedArgumentList: [
SlashCommandArgument.fromProps({
@@ -2508,14 +2440,23 @@ export async function init() {
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'expression-list',
aliases: ['expressions'],
callback: getExpressionListSlashCommand,
/** @type {(args: {return: string, filter: string}) => Promise<string>} */
callback: async (args) => {
let returnType =
/** @type {import('../../slash-commands/SlashCommandReturnHelper.js').SlashCommandReturnType} */
(args.return);
const list = await getExpressionsList({ filterAvailable: !isFalseBoolean(args.filter) });
return await slashCommandReturnHelper.doReturn(returnType ?? 'pipe', list, { objectToStringFunc: list => list.join(', ') });
},
namedArgumentList: [
SlashCommandNamedArgument.fromProps({
name: 'return',
description: 'The way how you want the return value to be provided',
typeList: [ARGUMENT_TYPE.STRING],
defaultValue: 'pipe',
enumList: slashCommandReturnHelper.enumList({ allowObject: true, allowPopup: true }),
enumList: slashCommandReturnHelper.enumList({ allowObject: true }),
forceEnum: true,
}),
SlashCommandNamedArgument.fromProps({
@@ -2525,21 +2466,6 @@ export async function init() {
enumList: commonEnumProviders.boolean('trueFalse')(),
defaultValue: 'true',
}),
SlashCommandNamedArgument.fromProps({
name: 'custom',
description: t`Whether to include, filter out or return only custom expressions`,
typeList: [
ARGUMENT_TYPE.STRING,
ARGUMENT_TYPE.BOOLEAN,
],
isRequired: false,
defaultValue: 'true',
enumList: [
new SlashCommandEnumValue('true', '(default) Custom expressions will be included in the result'),
new SlashCommandEnumValue('false', 'Custom expressions will not be included in the result'),
new SlashCommandEnumValue('only', 'Only custom expressions will be included in the result'),
],
}),
],
returns: 'The comma-separated list of available expressions, including custom expressions.',
helpString: 'Returns a list of available expressions, including custom expressions.',
@@ -2647,73 +2573,4 @@ export async function init() {
</div>
`,
}));
if (power_user.experimental_macro_engine) {
macros.register('defaultExpression', {
handler: getCurrentFallbackExpression,
category: macros.category.MISC,
description: 'Returns the global fallback expression.',
returns: 'Expression label',
exampleUsage: '{{defaultExpression}}',
});
macros.register('lastExpression', {
handler: function ({ args: [name = '{{char}}'], resolve }) {
try {
return getLastExpression({ characterName: resolve(name || '') });
} catch (error) {
console.error(error);
return '';
}
},
unnamedArgs: [{
name: 'name',
description: 'The name of the target character',
defaultValue: '{{char}}',
optional: true,
type: macros.valueType.STRING,
}],
delayArgResolution: true,
category: macros.category.MISC,
description: 'Returns the last expression used by the selected character. The currently active character is used if no character name is provided.',
returns: 'Expression label',
exampleUsage: [
'{{lastExpression}}',
'{{lastExpression::John}}',
'{{lastExpression::{{char}}}}',
],
});
macros.register('availableExpressions', {
handler: function () {
return getCachedExpressions().join(', ');
},
category: macros.category.MISC,
description: 'Returns a list with all the available expressions provided by the Classifier API.',
returns: 'Expression label list',
exampleUsage: '{{availableExpressions}}',
});
} else {
MacrosParser.registerMacro('defaultExpression',
getCurrentFallbackExpression,
t`Returns the global fallback expression.`,
);
MacrosParser.registerMacro('lastExpression',
() => {
try {
return getLastExpression();
} catch (error) {
console.error(error);
return '';
}
},
t`Returns the last expression used.`,
);
MacrosParser.registerMacro('availableExpressions',
() => getCachedExpressions().join(', '),
t`Returns a list with all the available expressions provided by the Classifier API.`,
);
}
}
+4 -4
View File
@@ -1,4 +1,4 @@
import { CONNECT_API_MAP, createModelIcon, getRequestHeaders, substituteParams } from '../../script.js';
import { CONNECT_API_MAP, createModelIcon, getRequestHeaders } from '../../script.js';
import { extension_settings, openThirdPartyExtensionMenu } from '../extensions.js';
import { t } from '../i18n.js';
import { oai_settings, proxies, ZAI_ENDPOINT } from '../openai.js';
@@ -117,9 +117,9 @@ export async function getMultimodalCaption(base64Img, prompt) {
}
requestBody.server_url = oai_settings.custom_url;
requestBody.custom_include_headers = substituteParams(oai_settings.custom_include_headers);
requestBody.custom_include_body = substituteParams(oai_settings.custom_include_body);
requestBody.custom_exclude_body = substituteParams(oai_settings.custom_exclude_body);
requestBody.custom_include_headers = oai_settings.custom_include_headers;
requestBody.custom_include_body = oai_settings.custom_include_body;
requestBody.custom_exclude_body = oai_settings.custom_exclude_body;
}
if (extension_settings.caption.multimodal_api === 'zai') {
-1
View File
@@ -52,7 +52,6 @@ export const macros = {
// enums
category: MacroCategory,
valueType: MacroValueType,
// shorthand functions
register: MacroRegistry.registerMacro.bind(MacroRegistry),
+4 -4
View File
@@ -2856,9 +2856,9 @@ export async function createGenerationParameters(settings, model, type, messages
if (settings.chat_completion_source === chat_completion_sources.CUSTOM) {
generate_data.custom_url = settings.custom_url;
generate_data.custom_include_body = substituteParams(settings.custom_include_body);
generate_data.custom_exclude_body = substituteParams(settings.custom_exclude_body);
generate_data.custom_include_headers = substituteParams(settings.custom_include_headers);
generate_data.custom_include_body = settings.custom_include_body;
generate_data.custom_exclude_body = settings.custom_exclude_body;
generate_data.custom_include_headers = settings.custom_include_headers;
}
if (settings.chat_completion_source === chat_completion_sources.COHERE) {
@@ -4407,7 +4407,7 @@ async function getStatusOpen() {
if (oai_settings.chat_completion_source === chat_completion_sources.CUSTOM) {
$('.model_custom_select').empty();
data.custom_url = oai_settings.custom_url;
data.custom_include_headers = substituteParams(oai_settings.custom_include_headers);
data.custom_include_headers = oai_settings.custom_include_headers;
}
if (oai_settings.chat_completion_source === chat_completion_sources.AZURE_OPENAI) {
+2 -2
View File
@@ -2970,9 +2970,9 @@ export function initDefaultSlashCommands() {
}));
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'tokens',
callback: async (_, text) => {
callback: (_, text) => {
if (text instanceof SlashCommandClosure || Array.isArray(text)) throw new Error(t`Unnamed argument cannot be a closure for command /tokens`);
return String(await getTokenCountAsync(text));
return getTokenCountAsync(text).then(count => String(count));
},
returns: t`number of tokens`,
unnamedArgumentList: [
+4 -4
View File
@@ -552,7 +552,7 @@ export function getTokenCount(str, padding = undefined) {
* @deprecated Use counterWrapperOpenAIAsync instead.
*/
function counterWrapperOpenAI(text) {
const message = { content: text };
const message = { role: 'system', content: text };
return countTokensOpenAI(message, true);
}
@@ -562,7 +562,7 @@ function counterWrapperOpenAI(text) {
* @returns {Promise<number>} Token count.
*/
function counterWrapperOpenAIAsync(text) {
const message = { content: text };
const message = { role: 'system', content: text };
return countTokensOpenAIAsync(message, true);
}
@@ -801,7 +801,7 @@ export function countTokensOpenAI(messages, full = false) {
messages = [messages];
}
let token_count = 0;
let token_count = -1;
for (const message of messages) {
const model = getTokenizerModel();
@@ -851,7 +851,7 @@ export async function countTokensOpenAIAsync(messages, full = false) {
messages = [messages];
}
let token_count = 0;
let token_count = -1;
for (const message of messages) {
const model = getTokenizerModel();
+4 -3
View File
@@ -692,12 +692,13 @@ export function isElementInViewport(el) {
* @param {{ (name: string): boolean; }} exists Function to check if name exists.
* @param {Object} [options] The options.
* @param {((baseName: string, i: number) => string)|null} [options.nameBuilder=null] Function to build the name.
* Starts with the index provided by `startIndex` (default is 0). If not provided, uses `baseName` for index 0 and "${baseName} (${i})" for higher indices.
* Starts with the index provided by `startIndex` (default is 1). If not provided, uses "${baseName} (${i})".
* @param {number} [options.maxTries=1000] The maximum number of tries to find a unique name. Default is 1000.
* @param {number} [options.startIndex=0] The index to start with when building the name. Default is 0.
* @param {number} [options.startIndex=1] The index to start with when building the name. Default is 1.
* When set to 0, the intention is to also check if the basename (without applied index) is free.
* @returns {string|null} A unique name. Null if no unique name could be found in `maxTries`.
*/
export function getUniqueName(baseName, exists, { nameBuilder = null, maxTries = 1000, startIndex = 0 } = {}) {
export function getUniqueName(baseName, exists, { nameBuilder = null, maxTries = 1000, startIndex = 1 } = {}) {
nameBuilder ??= (baseName, i) => i === 0 ? baseName : `${baseName} (${i})`;
let i = startIndex;
let name;
+2 -34
View File
@@ -4123,12 +4123,11 @@ async function renameWorldInfo(name, data) {
}
const entryPreviouslySelected = selected_world_info.findIndex((e) => e === oldName);
const retargetPersonaLore = power_user.persona_description_lorebook === oldName;
await saveWorldInfo(newName, data, true);
await deleteWorldInfo(oldName);
await updateWorldInfoLinks(oldName, newName, { retargetPersonaLore });
await updateWorldInfoLinks(oldName, newName);
if (entryPreviouslySelected !== -1) {
const wiElement = getWIElement(newName);
@@ -4146,10 +4145,9 @@ async function renameWorldInfo(name, data) {
* Retargets all character lore links from an old world info name to a new one, with an optional confirmation for primary lorebook links
* @param {string} oldName Previous WI file name
* @param {string} newName New WI file name
* @param {{ retargetPersonaLore?: boolean }} [options] Additional relink options
* @returns {Promise<void>}
*/
async function updateWorldInfoLinks(oldName, newName, { retargetPersonaLore } = {}) {
async function updateWorldInfoLinks(oldName, newName) {
const existingCharLores = world_info.charLore?.filter((e) => e.extraBooks.includes(oldName));
if (existingCharLores && existingCharLores.length > 0) {
existingCharLores.forEach((charLore) => {
@@ -4160,36 +4158,6 @@ async function updateWorldInfoLinks(oldName, newName, { retargetPersonaLore } =
saveSettingsDebounced();
}
// Update link for active persona
if (retargetPersonaLore) {
power_user.persona_description_lorebook = newName;
const object = getOrCreatePersonaDescriptor();
object.lorebook = newName;
setPersonaDescription();
saveSettingsDebounced();
}
// Update links for other personas
Object.keys(power_user.personas).forEach((persona) => {
if (user_avatar === persona) {
return;
}
const descriptor = power_user.persona_descriptions[persona];
if (!descriptor) {
return;
}
if (descriptor.lorebook === oldName) {
descriptor.lorebook = newName;
saveSettingsDebounced();
}
});
// update the world info key to the new name if it's still set to the old one
if (chat_metadata[METADATA_KEY] === oldName) {
chat_metadata[METADATA_KEY] = newName;
await saveMetadata();
}
// find all characters using the old lorebook name as their primary world
const linkedChIDs = [];
characters.forEach((character, chid) => {
+9 -9
View File
@@ -556,6 +556,11 @@ async function downloadPygmalionCharacter(id) {
*/
function parseChubUrl(str) {
const splitStr = str.split('/');
const length = splitStr.length;
if (length < 2) {
return null;
}
let domainIndex = -1;
@@ -565,25 +570,20 @@ function parseChubUrl(str) {
}
});
const cleanUrl = domainIndex !== -1 ? splitStr.slice(domainIndex + 1) : splitStr;
const length = cleanUrl.length;
const lastTwo = domainIndex !== -1 ? splitStr.slice(domainIndex + 1) : splitStr;
if (length < 2) {
return null;
}
const firstPart = cleanUrl[0].toLowerCase();
const firstPart = lastTwo[0].toLowerCase();
if (firstPart === 'characters' || firstPart === 'lorebooks') {
const type = firstPart === 'characters' ? 'character' : 'lorebook';
const id = type === 'character' ? cleanUrl.slice(1).join('/') : cleanUrl.join('/');
const id = type === 'character' ? lastTwo.slice(1).join('/') : lastTwo.join('/');
return {
id: id,
type: type,
};
} else if (length === 2) {
return {
id: cleanUrl.join('/'),
id: lastTwo.join('/'),
type: 'character',
};
}
+5 -3
View File
@@ -12,6 +12,7 @@ import { Tokenizer } from '@agnai/web-tokenizers';
import { SentencePieceProcessor } from '@agnai/sentencepiece-js';
import tiktoken from 'tiktoken';
import { convertClaudePrompt } from '../prompt-converters.js';
import { TEXTGEN_TYPES } from '../constants.js';
import { setAdditionalHeaders } from '../additional-headers.js';
import { getConfigValue, isValidUrl } from '../util.js';
@@ -544,14 +545,15 @@ export function getTiktokenTokenizer(model) {
* @returns {number} Number of tokens
*/
export function countWebTokenizerTokens(tokenizer, messages) {
const jsonBody = messages.flatMap(x => Object.values(x)).join('\n\n');
// Should be fine if we use the old conversion method instead of the messages API one i think?
const convertedPrompt = convertClaudePrompt(messages, false, '', false, false, '', false);
// Fallback to strlen estimation
if (!tokenizer) {
return guesstimate(jsonBody);
return guesstimate(convertedPrompt);
}
const count = tokenizer.encode(jsonBody).length;
const count = tokenizer.encode(convertedPrompt).length;
return count;
}
-2
View File
@@ -12,8 +12,6 @@ module.exports = {
env: {
es6: true,
node: true,
browser: true,
jquery: true,
'jest/globals': true,
},
parserOptions: {
@@ -1,79 +0,0 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
test.describe('World Info Rename Chat Lore', () => {
test.beforeEach(testSetup.awaitST);
test('should retarget chat lore metadata after lorebook rename', async ({ page }) => {
const oldName = 'STAGE_REPRO_ALPHA';
const newName = 'STAGE_REPRO_BETA';
const result = await page.evaluate(async ({ oldName, newName }) => {
const { createNewWorldInfo, deleteWorldInfo, openWorldInfoEditor, METADATA_KEY, world_names } = await import('./scripts/world-info.js');
const { chat_metadata } = await import('./script.js');
const { Popup, POPUP_RESULT } = await import('./scripts/popup.js');
async function waitFor(condition, timeoutMs = 5000, intervalMs = 50) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (condition()) return true;
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
return false;
}
const originalInput = Popup.show.input;
const originalConfirm = Popup.show.confirm;
try {
if (world_names.includes(oldName)) {
await deleteWorldInfo(oldName);
}
if (world_names.includes(newName)) {
await deleteWorldInfo(newName);
}
const created = await createNewWorldInfo(oldName, { interactive: false });
if (!created) {
throw new Error(`Failed to create world info '${oldName}'`);
}
chat_metadata[METADATA_KEY] = oldName;
await openWorldInfoEditor(oldName);
Popup.show.input = async () => newName;
Popup.show.confirm = async () => POPUP_RESULT.NEGATIVE;
const renameButton = document.querySelector('#world_popup_name_button');
if (!renameButton) {
throw new Error('Could not find #world_popup_name_button');
}
renameButton.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
const renameApplied = await waitFor(() => {
const editorValue = String($('#world_editor_select').find(':selected').text());
const optionTexts = $('#world_editor_select option').map((_, option) => String($(option).text())).get();
return editorValue === newName && optionTexts.includes(newName) && !optionTexts.includes(oldName);
});
if (!renameApplied) {
throw new Error('Rename operation did not complete in time');
}
return {
metadataAfter: chat_metadata[METADATA_KEY],
hasOldWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === oldName),
hasNewWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === newName),
};
} finally {
Popup.show.input = originalInput;
Popup.show.confirm = originalConfirm;
}
}, { oldName, newName });
expect(result.hasOldWorld).toBe(false);
expect(result.hasNewWorld).toBe(true);
expect(result.metadataAfter).toBe(newName);
});
});
@@ -1,85 +0,0 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
test.describe('World Info Rename Persona Lore', () => {
test.beforeEach(testSetup.awaitST);
test('should retarget persona lore metadata after lorebook rename', async ({ page }) => {
const oldName = 'STAGE_REPRO_PERSONA_ALPHA';
const newName = 'STAGE_REPRO_PERSONA_BETA';
const result = await page.evaluate(async ({ oldName, newName }) => {
const { createNewWorldInfo, deleteWorldInfo, openWorldInfoEditor, world_names } = await import('./scripts/world-info.js');
const { Popup, POPUP_RESULT } = await import('./scripts/popup.js');
const { power_user } = await import('./scripts/power-user.js');
const { getOrCreatePersonaDescriptor, user_avatar } = await import('./scripts/personas.js');
async function waitFor(condition, timeoutMs = 5000, intervalMs = 50) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (condition()) return true;
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
return false;
}
const originalInput = Popup.show.input;
const originalConfirm = Popup.show.confirm;
try {
if (world_names.includes(oldName)) {
await deleteWorldInfo(oldName);
}
if (world_names.includes(newName)) {
await deleteWorldInfo(newName);
}
const created = await createNewWorldInfo(oldName, { interactive: false });
if (!created) {
throw new Error(`Failed to create world info '${oldName}'`);
}
power_user.personas[user_avatar] = power_user.personas[user_avatar] || 'STAGE_REPRO_PERSONA';
power_user.persona_description_lorebook = oldName;
const descriptor = getOrCreatePersonaDescriptor();
descriptor.lorebook = oldName;
await openWorldInfoEditor(oldName);
Popup.show.input = async () => newName;
Popup.show.confirm = async () => POPUP_RESULT.NEGATIVE;
const renameButton = document.querySelector('#world_popup_name_button');
if (!renameButton) {
throw new Error('Could not find #world_popup_name_button');
}
renameButton.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
const renameApplied = await waitFor(() => {
const editorValue = String($('#world_editor_select').find(':selected').text());
const optionTexts = $('#world_editor_select option').map((_, option) => String($(option).text())).get();
return editorValue === newName && optionTexts.includes(newName) && !optionTexts.includes(oldName);
});
if (!renameApplied) {
throw new Error('Rename operation did not complete in time');
}
return {
personaLoreAfter: power_user.persona_description_lorebook,
descriptorLoreAfter: descriptor.lorebook,
hasOldWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === oldName),
hasNewWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === newName),
};
} finally {
Popup.show.input = originalInput;
Popup.show.confirm = originalConfirm;
}
}, { oldName, newName });
expect(result.hasOldWorld).toBe(false);
expect(result.hasNewWorld).toBe(true);
expect(result.personaLoreAfter).toBe(newName);
expect(result.descriptorLoreAfter).toBe(newName);
});
});
+2 -20
View File
@@ -1,5 +1,3 @@
const baseURL = process.env.ST_BASE_URL || process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:8000';
export const testSetup = {
/**
* Navigates to the home page without waiting for SillyTavern to load.
@@ -17,24 +15,8 @@ export const testSetup = {
*/
awaitST: async ({ page }) => {
await page.goto('/');
if (await testSetup.isLoginPage({ page })) {
// eslint-disable-next-line playwright/no-networkidle
await page.waitForLoadState('networkidle');
const userSelect = page.locator('#userList .userSelect').last();
if (await userSelect.count()) {
await userSelect.click();
}
await page.waitForURL(url => url.toString().startsWith(baseURL) && url.pathname !== '/login');
}
await page.click('#userList .userSelect:last-child');
await page.waitForURL('http://127.0.0.1:8000');
await page.waitForFunction('document.getElementById("preloader") === null', { timeout: 0 });
},
/**
* Checks if the current page is the login page by looking for a body element with the class 'login'.
* @param {Object} params
* @param {import('@playwright/test').Page} params.page
*/
isLoginPage: async ({ page }) => {
return await page.locator('body.login').count() > 0;
},
};
+1 -3
View File
@@ -1,11 +1,9 @@
import { defineConfig } from '@playwright/test';
const baseURL = process.env.ST_BASE_URL || process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:8000';
export default defineConfig({
testMatch: '*.e2e.js',
use: {
baseURL,
baseURL: 'http://127.0.0.1:8000',
video: 'only-on-failure',
screenshot: 'only-on-failure',
},