Compare commits

..
Author SHA1 Message Date
Wolfsblvt 207bb8239e Add number input min/max constraint enforcement on manual text entry
Browsers only enforce min/max constraints on number inputs when using spinner arrows or keyboard shortcuts, not when users manually type values. This adds a change event listener that clamps typed values to the defined min/max range, applies step alignment if specified, and triggers input events to notify existing handlers.
2026-05-15 20:54:58 +02:00
FeldherrenandCohee 77ba2c21a5 Add message indicating that the 'Request mode reasoning' checkbox controls whether reasoning is generated at the source, for Deepseek API (#5633)
* Add message indicating that the 'Request mode reasoning' checkbox
controls whether reasoning is generated at the source, for Deepseek API.

* Added zai and moonshot to conditions for showing message indicating reasoning is enabled/disabled by 'request model reasoning' toggle..

* Added new message indicating openrouter's behaviour when 'request model reasoning' setting is disabled.

* fix: grammar

* fix: duplication for openrouter

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2026-05-13 22:43:37 +03:00
Leandro Jofré 597517730b Feat/New features for character expressions (#5574)
* update: improve fetching of selected default expression
It includes the fallback values #emoji and #none.

* update: allow expression-list to filter custom expressions
It can allow, filter out, or only include custom expressions in the result.

* update: separate getLastExpression from the slash command to use on macros

* feat: register defaultExpression macro
It will fetch the label of the currently selected global fallback expression.

* feat: register lastExpression macro
It will return the last expression used by the selected character.

* feat: register availableExpressions macro
Returns a list of all expressions provided by the Classifier API.

* update: fix macros labels

* update: normalize return label for defaultExpression macro

* Fix - Typos

* Update - Add compatibility with old macro engine

* Fix - Remove redundant structuredClone

* Update - Consider sprite folders to fetch the last expression used

* Update - Improve last message handling when name is provided

* Fix - Update description of getLastCharacterMessage

* Update - Bring back using active character as fallback for groups
Just weighted that if no name is provided, doing fallback to the active character generating prompt is more useful for groups than grabbing the expression used by another character, after randomly removing that prev commit.
2026-05-13 22:35:45 +03:00
44af6bc169 Update persona lore on WI rename (#5637)
* Fix personal lore stale update on rename (#5628)

* Add test for rename persona lore

Co-authored-by: Copilot <copilot@github.com>

* Fix stale update on personal lore rename

Co-authored-by: Copilot <copilot@github.com>

Given the recent work to fix #5610, this is a continuation to fix a
similiar bug in the persona lore.

* Add newline for linter check

---------

Co-authored-by: Copilot <copilot@github.com>

* feat: update links for other personas

---------

Co-authored-by: Unnatural Developer <40277404+unnaturaldeveloper@users.noreply.github.com>
Co-authored-by: Copilot <copilot@github.com>
2026-05-13 22:04:03 +03:00
RojikkuandCohee 3913dfffb9 fix(content-manager) parseChubUrl should clean URL before relying on length (#5604)
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2026-05-13 22:03:26 +03:00
Tantoofaaz777 d08bbb1096 Skip inactive autocomplete repositioning (#5635) 2026-05-13 20:53:50 +03:00
Manthan AwganandCohee b1f5c29921 Refactor custom header and body handling in OpenAI scripts to use substituteParams function for improved parameter substitution. (#5627)
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2026-05-13 20:43:58 +03:00
Cohee bfff81bbf9 fix: event type in note-position command (#5624) 2026-05-12 00:54:26 +03:00
Unnatural DeveloperandCohee d5b6b7924b Fix stale chat bound lore name after rename (#5610)
* Add test to reproduce chat lore bug

Co-authored-by: Copilot <copilot@github.com>

Given that I wanted to reliably reproduce the bug, I created a playwright Docker container as part of this commit, along with the applicable unit test. The included docker-compose includes an environment variable that is passed for use by the frontend test harness, default to the host that the playwright and the ST instance containers are running on.

* Fix stale chat bound lore name after rename

Co-authored-by: Copilot <copilot@github.com>

Given the function renameWorldInfo and the resulting call to updateWorldInfoLinks, this fix ensures that if the world_info key in the chat_metadata is still set to the old name, it will be updated to the name

Resolves: #5608

* Start to separate test runner from branch

Given the bug fix for #5608 should be separate from the test runner
compose file, this commit removes the file from the branch associated
with the bug fix.

* Fix frontend test setup to check for login page

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>

* Make change to eslint configuration

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>

Given the updates to the setup of frontend-utils, configure eslint to
recognize browser and jquery specific globals

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2026-05-12 00:27:11 +03:00
CasualAutopsyandCohee e0c1dbad8f Add expand editor button to CC quick prompts (#5607)
* Add expand editor button to quick prompts

* fix: clean-up html

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2026-05-12 00:25:37 +03:00
ReithanandCohee 37b3e9e461 fix /tokens command returning inflated count for OpenAI API (#5601)
* fix /tokens command returning inflated count for OpenAI API

* Apply repo owner's patch to improve token counting fix

- Remove artificial 'role: system' wrapper that caused inflated counts
- Initialize token_count to 0 instead of -1
- Simplify web tokenizer to join message content directly
- Maintains caching functionality while fixing the overhead issue

* lint

* Revert to using cached implementation

* lint 2: revenge

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2026-05-12 00:19:48 +03:00
Wolfsblvt 29a18ce0c6 Refactor getUniqueName utility for allowBaseName option (#5602)
* feat: add allowBaseName option to getUniqueName utility function

* feat: simplify getUniqueName by removing allowBaseName option and changing default startIndex to 0
2026-05-05 22:33:04 +03:00
20 changed files with 512 additions and 75 deletions
+6
View File
@@ -809,18 +809,21 @@
<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>
@@ -2144,6 +2147,9 @@
<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');
$(`input[name="extension_floating_position"][value="${position}"]`).prop('checked', true).trigger('input').trigger('change');
toastr.info(t`Author's Note position updated`);
}
return Object.keys(validPositions).find(key => validPositions[key] == chat_metadata[metadata_keys.position]);
+10 -2
View File
@@ -126,9 +126,17 @@ export class AutoComplete {
});
textarea.addEventListener('blur', () => this.hide());
if (isFloating) {
textarea.addEventListener('scroll', () => this.updateFloatingPositionDebounced());
textarea.addEventListener('scroll', () => {
if (this.isActive) {
this.updateFloatingPositionDebounced();
}
});
}
window.addEventListener('resize', () => this.updatePositionDebounced());
window.addEventListener('resize', () => {
if (this.isActive) {
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 });
const suggestedName = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildCheckpointName, startIndex: 1 });
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 });
const name = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildBranchName, startIndex: 1 });
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,6 +2,7 @@ import { throttle } from './utils.js';
export function initDomHandlers() {
handleInputWheel();
handleNumberInputConstraints();
}
/**
@@ -64,3 +65,66 @@ 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 });
}
+176 -33
View File
@@ -18,6 +18,8 @@ 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 };
/**
@@ -103,6 +105,19 @@ 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
@@ -786,13 +801,48 @@ 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 extension_settings?.expressions?.fallback_expression || '';
if (!expressionName) return getCurrentFallbackExpression();
const select = /** @type {HTMLSelectElement} */(document.getElementById('expression_fallback'));
const fallbackExpressions = Array
@@ -1151,15 +1201,24 @@ export async function getExpressionLabel(text, expressionsApi = extension_settin
}
}
function getLastCharacterMessage() {
/**
* @param {Object} [options]
* @param {string} [options.characterName] Filters last message to the one of the target character
*/
function getLastCharacterMessage({ characterName = '' } = {}) {
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 };
}
@@ -1463,6 +1522,30 @@ 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.
*
@@ -2351,15 +2434,15 @@ export async function init() {
typeList: [ARGUMENT_TYPE.STRING],
isRequired: false,
enumProvider: () => [
new SlashCommandEnumValue('#none', 'Sets the fallback expression to no image'),
new SlashCommandEnumValue('#emoji', 'Sets the fallback expression to emojis'),
new SlashCommandEnumValue(OPTION_NO_FALLBACK, 'Sets the fallback expression to no image'),
new SlashCommandEnumValue(OPTION_EMOJI_FALLBACK, 'Sets the fallback expression to emojis'),
...localEnumProviders.expressions(),
],
}),
],
helpString: `
<div>
Gets the currently selected expression fallback for all characters.<br />
Gets the currently selected global fallback expression.<br />
If a valid expression label is sent, it will be set as the new fallback.
</div>
<div>
@@ -2410,23 +2493,8 @@ export async function init() {
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'expression-last',
aliases: ['lastsprite'],
/** @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;
},
/** @type {(args: object, name: string) => string} */
callback: (_, name) => getLastExpression({ characterName: (name || '') }),
returns: 'the last set expression for the named character.',
unnamedArgumentList: [
SlashCommandArgument.fromProps({
@@ -2440,23 +2508,14 @@ export async function init() {
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'expression-list',
aliases: ['expressions'],
/** @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(', ') });
},
callback: getExpressionListSlashCommand,
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 }),
enumList: slashCommandReturnHelper.enumList({ allowObject: true, allowPopup: true }),
forceEnum: true,
}),
SlashCommandNamedArgument.fromProps({
@@ -2466,6 +2525,21 @@ 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.',
@@ -2573,4 +2647,73 @@ 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 } from '../../script.js';
import { CONNECT_API_MAP, createModelIcon, getRequestHeaders, substituteParams } 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 = oai_settings.custom_include_headers;
requestBody.custom_include_body = oai_settings.custom_include_body;
requestBody.custom_exclude_body = oai_settings.custom_exclude_body;
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);
}
if (extension_settings.caption.multimodal_api === 'zai') {
+1
View File
@@ -52,6 +52,7 @@ 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 = settings.custom_include_body;
generate_data.custom_exclude_body = settings.custom_exclude_body;
generate_data.custom_include_headers = settings.custom_include_headers;
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);
}
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 = oai_settings.custom_include_headers;
data.custom_include_headers = substituteParams(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: (_, text) => {
callback: async (_, text) => {
if (text instanceof SlashCommandClosure || Array.isArray(text)) throw new Error(t`Unnamed argument cannot be a closure for command /tokens`);
return getTokenCountAsync(text).then(count => String(count));
return String(await getTokenCountAsync(text));
},
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 = { role: 'system', content: text };
const message = { content: text };
return countTokensOpenAI(message, true);
}
@@ -562,7 +562,7 @@ function counterWrapperOpenAI(text) {
* @returns {Promise<number>} Token count.
*/
function counterWrapperOpenAIAsync(text) {
const message = { role: 'system', content: text };
const message = { content: text };
return countTokensOpenAIAsync(message, true);
}
@@ -801,7 +801,7 @@ export function countTokensOpenAI(messages, full = false) {
messages = [messages];
}
let token_count = -1;
let token_count = 0;
for (const message of messages) {
const model = getTokenizerModel();
@@ -851,7 +851,7 @@ export async function countTokensOpenAIAsync(messages, full = false) {
messages = [messages];
}
let token_count = -1;
let token_count = 0;
for (const message of messages) {
const model = getTokenizerModel();
+3 -4
View File
@@ -692,13 +692,12 @@ 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 1). If not provided, uses "${baseName} (${i})".
* Starts with the index provided by `startIndex` (default is 0). If not provided, uses `baseName` for index 0 and "${baseName} (${i})" for higher indices.
* @param {number} [options.maxTries=1000] The maximum number of tries to find a unique name. Default is 1000.
* @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.
* @param {number} [options.startIndex=0] The index to start with when building the name. Default is 0.
* @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 = 1 } = {}) {
export function getUniqueName(baseName, exists, { nameBuilder = null, maxTries = 1000, startIndex = 0 } = {}) {
nameBuilder ??= (baseName, i) => i === 0 ? baseName : `${baseName} (${i})`;
let i = startIndex;
let name;
+34 -2
View File
@@ -4123,11 +4123,12 @@ 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);
await updateWorldInfoLinks(oldName, newName, { retargetPersonaLore });
if (entryPreviouslySelected !== -1) {
const wiElement = getWIElement(newName);
@@ -4145,9 +4146,10 @@ 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) {
async function updateWorldInfoLinks(oldName, newName, { retargetPersonaLore } = {}) {
const existingCharLores = world_info.charLore?.filter((e) => e.extraBooks.includes(oldName));
if (existingCharLores && existingCharLores.length > 0) {
existingCharLores.forEach((charLore) => {
@@ -4158,6 +4160,36 @@ async function updateWorldInfoLinks(oldName, newName) {
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,11 +556,6 @@ async function downloadPygmalionCharacter(id) {
*/
function parseChubUrl(str) {
const splitStr = str.split('/');
const length = splitStr.length;
if (length < 2) {
return null;
}
let domainIndex = -1;
@@ -570,20 +565,25 @@ function parseChubUrl(str) {
}
});
const lastTwo = domainIndex !== -1 ? splitStr.slice(domainIndex + 1) : splitStr;
const cleanUrl = domainIndex !== -1 ? splitStr.slice(domainIndex + 1) : splitStr;
const length = cleanUrl.length;
const firstPart = lastTwo[0].toLowerCase();
if (length < 2) {
return null;
}
const firstPart = cleanUrl[0].toLowerCase();
if (firstPart === 'characters' || firstPart === 'lorebooks') {
const type = firstPart === 'characters' ? 'character' : 'lorebook';
const id = type === 'character' ? lastTwo.slice(1).join('/') : lastTwo.join('/');
const id = type === 'character' ? cleanUrl.slice(1).join('/') : cleanUrl.join('/');
return {
id: id,
type: type,
};
} else if (length === 2) {
return {
id: lastTwo.join('/'),
id: cleanUrl.join('/'),
type: 'character',
};
}
+3 -5
View File
@@ -12,7 +12,6 @@ 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';
@@ -545,15 +544,14 @@ export function getTiktokenTokenizer(model) {
* @returns {number} Number of tokens
*/
export function countWebTokenizerTokens(tokenizer, messages) {
// 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);
const jsonBody = messages.flatMap(x => Object.values(x)).join('\n\n');
// Fallback to strlen estimation
if (!tokenizer) {
return guesstimate(convertedPrompt);
return guesstimate(jsonBody);
}
const count = tokenizer.encode(convertedPrompt).length;
const count = tokenizer.encode(jsonBody).length;
return count;
}
+2
View File
@@ -12,6 +12,8 @@ module.exports = {
env: {
es6: true,
node: true,
browser: true,
jquery: true,
'jest/globals': true,
},
parserOptions: {
@@ -0,0 +1,79 @@
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);
});
});
@@ -0,0 +1,85 @@
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);
});
});
+20 -2
View File
@@ -1,3 +1,5 @@
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.
@@ -15,8 +17,24 @@ export const testSetup = {
*/
awaitST: async ({ page }) => {
await page.goto('/');
await page.click('#userList .userSelect:last-child');
await page.waitForURL('http://127.0.0.1:8000');
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.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;
},
};
+3 -1
View File
@@ -1,9 +1,11 @@
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: 'http://127.0.0.1:8000',
baseURL,
video: 'only-on-failure',
screenshot: 'only-on-failure',
},