Merge branch 'staging' into neo-server
This commit is contained in:
commit
d8092ec3eb
103
public/script.js
103
public/script.js
|
@ -153,7 +153,7 @@ import {
|
|||
ensureImageFormatSupported,
|
||||
} from './scripts/utils.js';
|
||||
|
||||
import { ModuleWorkerWrapper, doDailyExtensionUpdatesCheck, extension_settings, getContext, loadExtensionSettings, renderExtensionTemplate, runGenerationInterceptors, saveMetadataDebounced, writeExtensionField } from './scripts/extensions.js';
|
||||
import { ModuleWorkerWrapper, doDailyExtensionUpdatesCheck, extension_settings, getContext, loadExtensionSettings, renderExtensionTemplate, renderExtensionTemplateAsync, runGenerationInterceptors, saveMetadataDebounced, writeExtensionField } from './scripts/extensions.js';
|
||||
import { COMMENT_NAME_DEFAULT, executeSlashCommands, getSlashCommandsHelp, processChatSlashCommands, registerSlashCommand } from './scripts/slash-commands.js';
|
||||
import {
|
||||
tag_map,
|
||||
|
@ -213,6 +213,7 @@ import { initPresetManager } from './scripts/preset-manager.js';
|
|||
import { evaluateMacros } from './scripts/macros.js';
|
||||
import { currentUser, setUserControls } from './scripts/user.js';
|
||||
import { callGenericPopup } from './scripts/popup.js';
|
||||
import { renderTemplate, renderTemplateAsync } from './scripts/templates.js';
|
||||
|
||||
//exporting functions and vars for mods
|
||||
export {
|
||||
|
@ -287,6 +288,7 @@ export {
|
|||
printCharactersDebounced,
|
||||
isOdd,
|
||||
countOccurrences,
|
||||
renderTemplate,
|
||||
};
|
||||
|
||||
showLoader();
|
||||
|
@ -576,14 +578,14 @@ export const MAX_INJECTION_DEPTH = 1000;
|
|||
|
||||
let system_messages = {};
|
||||
|
||||
function getSystemMessages() {
|
||||
async function getSystemMessages() {
|
||||
system_messages = {
|
||||
help: {
|
||||
name: systemUserName,
|
||||
force_avatar: system_avatar,
|
||||
is_user: false,
|
||||
is_system: true,
|
||||
mes: renderTemplate('help'),
|
||||
mes: await renderTemplateAsync('help'),
|
||||
},
|
||||
slash_commands: {
|
||||
name: systemUserName,
|
||||
|
@ -597,21 +599,21 @@ function getSystemMessages() {
|
|||
force_avatar: system_avatar,
|
||||
is_user: false,
|
||||
is_system: true,
|
||||
mes: renderTemplate('hotkeys'),
|
||||
mes: await renderTemplateAsync('hotkeys'),
|
||||
},
|
||||
formatting: {
|
||||
name: systemUserName,
|
||||
force_avatar: system_avatar,
|
||||
is_user: false,
|
||||
is_system: true,
|
||||
mes: renderTemplate('formatting'),
|
||||
mes: await renderTemplateAsync('formatting'),
|
||||
},
|
||||
macros: {
|
||||
name: systemUserName,
|
||||
force_avatar: system_avatar,
|
||||
is_user: false,
|
||||
is_system: true,
|
||||
mes: renderTemplate('macros'),
|
||||
mes: await renderTemplateAsync('macros'),
|
||||
},
|
||||
welcome:
|
||||
{
|
||||
|
@ -619,7 +621,7 @@ function getSystemMessages() {
|
|||
force_avatar: system_avatar,
|
||||
is_user: false,
|
||||
is_system: true,
|
||||
mes: renderTemplate('welcome'),
|
||||
mes: await renderTemplateAsync('welcome'),
|
||||
},
|
||||
group: {
|
||||
name: systemUserName,
|
||||
|
@ -673,52 +675,6 @@ $(document).ajaxError(function myErrorHandler(_, xhr) {
|
|||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Loads a URL content using XMLHttpRequest synchronously.
|
||||
* @param {string} url URL to load synchronously
|
||||
* @returns {string} Response text
|
||||
*/
|
||||
function getUrlSync(url) {
|
||||
console.debug('Loading URL synchronously', url);
|
||||
const request = new XMLHttpRequest();
|
||||
request.open('GET', url, false); // `false` makes the request synchronous
|
||||
request.send();
|
||||
|
||||
if (request.status >= 200 && request.status < 300) {
|
||||
return request.responseText;
|
||||
}
|
||||
|
||||
throw new Error(`Error loading ${url}: ${request.status} ${request.statusText}`);
|
||||
}
|
||||
|
||||
const templateCache = new Map();
|
||||
|
||||
export function renderTemplate(templateId, templateData = {}, sanitize = true, localize = true, fullPath = false) {
|
||||
try {
|
||||
const pathToTemplate = fullPath ? templateId : `/scripts/templates/${templateId}.html`;
|
||||
let template = templateCache.get(pathToTemplate);
|
||||
if (!template) {
|
||||
const templateContent = getUrlSync(pathToTemplate);
|
||||
template = Handlebars.compile(templateContent);
|
||||
templateCache.set(pathToTemplate, template);
|
||||
}
|
||||
let result = template(templateData);
|
||||
|
||||
if (sanitize) {
|
||||
result = DOMPurify.sanitize(result);
|
||||
}
|
||||
|
||||
if (localize) {
|
||||
result = applyLocale(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
console.error('Error rendering template', templateId, templateData, err);
|
||||
toastr.error('Check the DevTools console for more information.', 'Error rendering template');
|
||||
}
|
||||
}
|
||||
|
||||
async function getClientVersion() {
|
||||
try {
|
||||
const response = await fetch('/version');
|
||||
|
@ -782,7 +738,7 @@ function getCurrentChatId() {
|
|||
if (selected_group) {
|
||||
return groups.find(x => x.id == selected_group)?.chat_id;
|
||||
}
|
||||
else if (this_chid) {
|
||||
else if (this_chid !== undefined) {
|
||||
return characters[this_chid]?.chat;
|
||||
}
|
||||
}
|
||||
|
@ -902,7 +858,7 @@ async function firstLoadInit() {
|
|||
await getClientVersion();
|
||||
await readSecretState();
|
||||
await getSettings();
|
||||
getSystemMessages();
|
||||
await getSystemMessages();
|
||||
sendSystemMessage(system_message_types.WELCOME);
|
||||
initLocales();
|
||||
initTags();
|
||||
|
@ -1205,7 +1161,7 @@ export function resultCheckStatus() {
|
|||
}
|
||||
|
||||
export async function selectCharacterById(id) {
|
||||
if (characters[id] == undefined) {
|
||||
if (characters[id] === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -1566,7 +1522,7 @@ async function getCharacters() {
|
|||
|
||||
characters[i]['chat'] = String(characters[i]['chat']);
|
||||
}
|
||||
if (this_chid != undefined && this_chid != 'invalid-safety-id') {
|
||||
if (this_chid !== undefined) {
|
||||
$('#avatar_url_pole').val(characters[this_chid].avatar);
|
||||
}
|
||||
|
||||
|
@ -1719,11 +1675,12 @@ export async function reloadCurrentChat() {
|
|||
if (selected_group) {
|
||||
await getGroupChat(selected_group, true);
|
||||
}
|
||||
else if (this_chid) {
|
||||
else if (this_chid !== undefined) {
|
||||
await getChat();
|
||||
}
|
||||
else {
|
||||
resetChatState();
|
||||
await getCharacters();
|
||||
await printMessages();
|
||||
await eventSource.emit(event_types.CHAT_CHANGED, getCurrentChatId());
|
||||
}
|
||||
|
@ -1826,7 +1783,7 @@ function messageFormatting(mes, ch_name, isSystem, isUser, messageId) {
|
|||
mes = mes.replaceAll('<', '<').replaceAll('>', '>');
|
||||
}
|
||||
|
||||
if ((this_chid === undefined || this_chid === 'invalid-safety-id') && !selected_group) {
|
||||
if (this_chid === undefined && !selected_group) {
|
||||
mes = mes
|
||||
.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>')
|
||||
.replace(/\n/g, '<br/>');
|
||||
|
@ -2083,7 +2040,7 @@ function addOneMessage(mes, { type = 'normal', insertAfter = null, scroll = true
|
|||
if (!mes['is_user']) {
|
||||
if (mes.force_avatar) {
|
||||
avatarImg = mes.force_avatar;
|
||||
} else if (this_chid === undefined || this_chid === 'invalid-safety-id') {
|
||||
} else if (this_chid === undefined) {
|
||||
avatarImg = system_avatar;
|
||||
} else {
|
||||
if (characters[this_chid].avatar != 'none') {
|
||||
|
@ -3176,12 +3133,12 @@ async function Generate(type, { automatic_trigger, force_name2, quiet_prompt, qu
|
|||
quiet_prompt = main_api == 'novel' && !quietToLoud ? adjustNovelInstructionPrompt(quiet_prompt) : quiet_prompt;
|
||||
}
|
||||
|
||||
const isChatValid = online_status != 'no_connection' && this_chid != undefined && this_chid !== 'invalid-safety-id';
|
||||
const isChatValid = online_status !== 'no_connection' && this_chid !== undefined;
|
||||
|
||||
// We can't do anything because we're not in a chat right now. (Unless it's a dry run, in which case we need to
|
||||
// assemble the prompt so we can count its tokens regardless of whether a chat is active.)
|
||||
if (!dryRun && !isChatValid) {
|
||||
if (this_chid === undefined || this_chid === 'invalid-safety-id') {
|
||||
if (this_chid === undefined) {
|
||||
toastr.warning('Сharacter is not selected');
|
||||
}
|
||||
is_send_press = false;
|
||||
|
@ -4613,7 +4570,7 @@ async function DupeChar() {
|
|||
}
|
||||
}
|
||||
|
||||
function promptItemize(itemizedPrompts, requestedMesId) {
|
||||
async function promptItemize(itemizedPrompts, requestedMesId) {
|
||||
console.log('PROMPT ITEMIZE ENTERED');
|
||||
var incomingMesId = Number(requestedMesId);
|
||||
console.debug(`looking for MesId ${incomingMesId}`);
|
||||
|
@ -4654,7 +4611,7 @@ function promptItemize(itemizedPrompts, requestedMesId) {
|
|||
chatInjects: getTokenCount(itemizedPrompts[thisPromptSet].chatInjects),
|
||||
};
|
||||
|
||||
if (params.chatInjects){
|
||||
if (params.chatInjects) {
|
||||
params.ActualChatHistoryTokens = params.ActualChatHistoryTokens - params.chatInjects;
|
||||
}
|
||||
|
||||
|
@ -4736,10 +4693,12 @@ function promptItemize(itemizedPrompts, requestedMesId) {
|
|||
}
|
||||
|
||||
if (params.this_main_api == 'openai') {
|
||||
callPopup(renderTemplate('itemizationChat', params), 'text');
|
||||
const template = await renderTemplateAsync('itemizationChat', params);
|
||||
callPopup(template, 'text');
|
||||
|
||||
} else {
|
||||
callPopup(renderTemplate('itemizationText', params), 'text');
|
||||
const template = await renderTemplateAsync('itemizationText', params);
|
||||
callPopup(template, 'text');
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5308,7 +5267,7 @@ export function deactivateSendButtons() {
|
|||
|
||||
function resetChatState() {
|
||||
//unsets expected chid before reloading (related to getCharacters/printCharacters from using old arrays)
|
||||
this_chid = 'invalid-safety-id';
|
||||
this_chid = undefined;
|
||||
// replaces deleted charcter name with system user since it will be displayed next.
|
||||
name2 = systemUserName;
|
||||
// sets up system user to tell user about having deleted a character
|
||||
|
@ -7693,7 +7652,7 @@ async function createOrEditCharacter(e) {
|
|||
|
||||
$('#create_button').attr('value', '✅');
|
||||
let oldSelectedChar = null;
|
||||
if (this_chid != undefined && this_chid != 'invalid-safety-id') {
|
||||
if (this_chid !== undefined) {
|
||||
oldSelectedChar = characters[this_chid].avatar;
|
||||
}
|
||||
|
||||
|
@ -7815,7 +7774,11 @@ window['SillyTavern'].getContext = function () {
|
|||
*/
|
||||
registerHelper: () => { },
|
||||
registedDebugFunction: registerDebugFunction,
|
||||
/**
|
||||
* @deprecated Use renderExtensionTemplateAsync instead.
|
||||
*/
|
||||
renderExtensionTemplate: renderExtensionTemplate,
|
||||
renderExtensionTemplateAsync: renderExtensionTemplateAsync,
|
||||
callPopup: callPopup,
|
||||
callGenericPopup: callGenericPopup,
|
||||
mainApi: main_api,
|
||||
|
@ -8440,7 +8403,7 @@ async function importCharacter(file, preserveFileName = false) {
|
|||
$('#character_search_bar').val('').trigger('input');
|
||||
|
||||
let oldSelectedChar = null;
|
||||
if (this_chid != undefined && this_chid != 'invalid-safety-id') {
|
||||
if (this_chid !== undefined) {
|
||||
oldSelectedChar = characters[this_chid].avatar;
|
||||
}
|
||||
|
||||
|
@ -8571,7 +8534,7 @@ export async function handleDeleteCharacter(popup_type, this_chid, delete_chats)
|
|||
export async function deleteCharacter(name, avatar, reloadCharacters = true) {
|
||||
await clearChat();
|
||||
$('#character_cross').click();
|
||||
this_chid = 'invalid-safety-id';
|
||||
this_chid = undefined;
|
||||
characters.length = 0;
|
||||
name2 = systemUserName;
|
||||
chat = [...safetychat];
|
||||
|
|
|
@ -108,13 +108,22 @@ export function humanizeGenTime(total_gen_time) {
|
|||
return time_spent;
|
||||
}
|
||||
|
||||
let parsedUA = null;
|
||||
try {
|
||||
parsedUA = Bowser.parse(navigator.userAgent);
|
||||
} catch {
|
||||
// In case the user agent is an empty string or Bowser can't parse it for some other reason
|
||||
}
|
||||
/**
|
||||
* DON'T OPTIMIZE, don't change this to a const or let, it needs to be a var.
|
||||
*/
|
||||
var parsedUA = null;
|
||||
|
||||
function getParsedUA() {
|
||||
if (!parsedUA) {
|
||||
try {
|
||||
parsedUA = Bowser.parse(navigator.userAgent);
|
||||
} catch {
|
||||
// In case the user agent is an empty string or Bowser can't parse it for some other reason
|
||||
}
|
||||
}
|
||||
|
||||
return parsedUA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the device is a mobile device.
|
||||
|
@ -123,7 +132,7 @@ try {
|
|||
export function isMobile() {
|
||||
const mobileTypes = ['mobile', 'tablet'];
|
||||
|
||||
return mobileTypes.includes(parsedUA?.platform?.type);
|
||||
return mobileTypes.includes(getParsedUA()?.platform?.type);
|
||||
}
|
||||
|
||||
export function shouldSendOnEnter() {
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import { callPopup, eventSource, event_types, saveSettings, saveSettingsDebounced, getRequestHeaders, substituteParams, renderTemplate, animation_duration } from '../script.js';
|
||||
import { callPopup, eventSource, event_types, saveSettings, saveSettingsDebounced, getRequestHeaders, animation_duration } from '../script.js';
|
||||
import { hideLoader, showLoader } from './loader.js';
|
||||
import { renderTemplate, renderTemplateAsync } from './templates.js';
|
||||
import { isSubsetOf, setValueByPath } from './utils.js';
|
||||
export {
|
||||
getContext,
|
||||
|
@ -50,17 +51,31 @@ export function saveMetadataDebounced() {
|
|||
}
|
||||
|
||||
/**
|
||||
* Provides an ability for extensions to render HTML templates.
|
||||
* Provides an ability for extensions to render HTML templates synchronously.
|
||||
* Templates sanitation and localization is forced.
|
||||
* @param {string} extensionName Extension name
|
||||
* @param {string} templateId Template ID
|
||||
* @param {object} templateData Additional data to pass to the template
|
||||
* @returns {string} Rendered HTML
|
||||
*
|
||||
* @deprecated Use renderExtensionTemplateAsync instead.
|
||||
*/
|
||||
export function renderExtensionTemplate(extensionName, templateId, templateData = {}, sanitize = true, localize = true) {
|
||||
return renderTemplate(`scripts/extensions/${extensionName}/${templateId}.html`, templateData, sanitize, localize, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides an ability for extensions to render HTML templates asynchronously.
|
||||
* Templates sanitation and localization is forced.
|
||||
* @param {string} extensionName Extension name
|
||||
* @param {string} templateId Template ID
|
||||
* @param {object} templateData Additional data to pass to the template
|
||||
* @returns {Promise<string>} Rendered HTML
|
||||
*/
|
||||
export function renderExtensionTemplateAsync(extensionName, templateId, templateData = {}, sanitize = true, localize = true) {
|
||||
return renderTemplateAsync(`scripts/extensions/${extensionName}/${templateId}.html`, templateData, sanitize, localize, true);
|
||||
}
|
||||
|
||||
// Disables parallel updates
|
||||
class ModuleWorkerWrapper {
|
||||
constructor(callback) {
|
||||
|
|
|
@ -4,7 +4,7 @@ TODO:
|
|||
//const DEBUG_TONY_SAMA_FORK_MODE = true
|
||||
|
||||
import { getRequestHeaders, callPopup, processDroppedFiles } from '../../../script.js';
|
||||
import { deleteExtension, extensionNames, getContext, installExtension, renderExtensionTemplate } from '../../extensions.js';
|
||||
import { deleteExtension, extensionNames, getContext, installExtension, renderExtensionTemplateAsync } from '../../extensions.js';
|
||||
import { executeSlashCommands } from '../../slash-commands.js';
|
||||
import { getStringHash, isValidUrl } from '../../utils.js';
|
||||
export { MODULE_NAME };
|
||||
|
@ -355,7 +355,8 @@ async function updateCurrentAssets() {
|
|||
// This function is called when the extension is loaded
|
||||
jQuery(async () => {
|
||||
// This is an example of loading HTML from a file
|
||||
const windowHtml = $(renderExtensionTemplate(MODULE_NAME, 'window', {}));
|
||||
const windowTemplate = await renderExtensionTemplateAsync(MODULE_NAME, 'window', {});
|
||||
const windowHtml = $(windowTemplate);
|
||||
|
||||
const assetsJsonUrl = windowHtml.find('#assets-json-url-field');
|
||||
assetsJsonUrl.val(ASSETS_JSON_URL);
|
||||
|
@ -366,7 +367,7 @@ jQuery(async () => {
|
|||
const rememberKey = `Assets_SkipConfirm_${getStringHash(url)}`;
|
||||
const skipConfirm = localStorage.getItem(rememberKey) === 'true';
|
||||
|
||||
const template = renderExtensionTemplate(MODULE_NAME, 'confirm', { url });
|
||||
const template = await renderExtensionTemplateAsync(MODULE_NAME, 'confirm', { url });
|
||||
const confirmation = skipConfirm || await callPopup(template, 'confirm');
|
||||
|
||||
if (confirmation) {
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { callPopup, eventSource, event_types, getRequestHeaders, saveSettingsDebounced } from '../../../script.js';
|
||||
import { dragElement, isMobile } from '../../RossAscends-mods.js';
|
||||
import { getContext, getApiUrl, modules, extension_settings, ModuleWorkerWrapper, doExtrasFetch, renderExtensionTemplate } from '../../extensions.js';
|
||||
import { getContext, getApiUrl, modules, extension_settings, ModuleWorkerWrapper, doExtrasFetch, renderExtensionTemplateAsync } from '../../extensions.js';
|
||||
import { loadMovingUIState, power_user } from '../../power-user.js';
|
||||
import { registerSlashCommand } from '../../slash-commands.js';
|
||||
import { onlyUnique, debounce, getCharaFilename, trimToEndSentence, trimToStartSentence } from '../../utils.js';
|
||||
|
@ -594,7 +594,7 @@ async function moduleWorker() {
|
|||
}
|
||||
|
||||
// non-characters not supported
|
||||
if (!context.groupId && (context.characterId === undefined || context.characterId === 'invalid-safety-id')) {
|
||||
if (!context.groupId && context.characterId === undefined) {
|
||||
removeExpression();
|
||||
return;
|
||||
}
|
||||
|
@ -977,6 +977,10 @@ async function getExpressionLabel(text) {
|
|||
return getFallbackExpression();
|
||||
}
|
||||
|
||||
if (extension_settings.expressions.translate && typeof window['translate'] === 'function') {
|
||||
text = await window['translate'](text, 'en');
|
||||
}
|
||||
|
||||
text = sampleClassifyText(text);
|
||||
|
||||
try {
|
||||
|
@ -1051,18 +1055,18 @@ async function validateImages(character, forceRedrawCached) {
|
|||
if (spriteCache[character]) {
|
||||
if (forceRedrawCached && $('#image_list').data('name') !== character) {
|
||||
console.debug('force redrawing character sprites list');
|
||||
drawSpritesList(character, labels, spriteCache[character]);
|
||||
await drawSpritesList(character, labels, spriteCache[character]);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const sprites = await getSpritesList(character);
|
||||
let validExpressions = drawSpritesList(character, labels, sprites);
|
||||
let validExpressions = await drawSpritesList(character, labels, sprites);
|
||||
spriteCache[character] = validExpressions;
|
||||
}
|
||||
|
||||
function drawSpritesList(character, labels, sprites) {
|
||||
async function drawSpritesList(character, labels, sprites) {
|
||||
let validExpressions = [];
|
||||
$('#no_chat_expressions').hide();
|
||||
$('#open_chat_expressions').show();
|
||||
|
@ -1074,18 +1078,20 @@ function drawSpritesList(character, labels, sprites) {
|
|||
return [];
|
||||
}
|
||||
|
||||
labels.sort().forEach((item) => {
|
||||
for (const item of labels.sort()) {
|
||||
const sprite = sprites.find(x => x.label == item);
|
||||
const isCustom = extension_settings.expressions.custom.includes(item);
|
||||
|
||||
if (sprite) {
|
||||
validExpressions.push(sprite);
|
||||
$('#image_list').append(getListItem(item, sprite.path, 'success', isCustom));
|
||||
const listItem = await getListItem(item, sprite.path, 'success', isCustom);
|
||||
$('#image_list').append(listItem);
|
||||
}
|
||||
else {
|
||||
$('#image_list').append(getListItem(item, '/img/No-Image-Placeholder.svg', 'failure', isCustom));
|
||||
const listItem = await getListItem(item, '/img/No-Image-Placeholder.svg', 'failure', isCustom);
|
||||
$('#image_list').append(listItem);
|
||||
}
|
||||
});
|
||||
}
|
||||
return validExpressions;
|
||||
}
|
||||
|
||||
|
@ -1095,12 +1101,12 @@ function drawSpritesList(character, labels, sprites) {
|
|||
* @param {string} imageSrc Path to image
|
||||
* @param {'success' | 'failure'} textClass 'success' or 'failure'
|
||||
* @param {boolean} isCustom If expression is added by user
|
||||
* @returns {string} Rendered list item template
|
||||
* @returns {Promise<string>} Rendered list item template
|
||||
*/
|
||||
function getListItem(item, imageSrc, textClass, isCustom) {
|
||||
async function getListItem(item, imageSrc, textClass, isCustom) {
|
||||
const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
|
||||
imageSrc = isFirefox ? `${imageSrc}?t=${Date.now()}` : imageSrc;
|
||||
return renderExtensionTemplate(MODULE_NAME, 'list-item', { item, imageSrc, textClass, isCustom });
|
||||
return renderExtensionTemplateAsync(MODULE_NAME, 'list-item', { item, imageSrc, textClass, isCustom });
|
||||
}
|
||||
|
||||
async function getSpritesList(name) {
|
||||
|
@ -1162,7 +1168,7 @@ async function renderFallbackExpressionPicker() {
|
|||
async function getExpressionsList() {
|
||||
// Return cached list if available
|
||||
if (Array.isArray(expressionsList)) {
|
||||
return expressionsList;
|
||||
return [...expressionsList, ...extension_settings.expressions.custom].filter(onlyUnique);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -1211,7 +1217,7 @@ async function getExpressionsList() {
|
|||
}
|
||||
|
||||
const result = await resolveExpressionsList();
|
||||
return [...result, ...extension_settings.expressions.custom];
|
||||
return [...result, ...extension_settings.expressions.custom].filter(onlyUnique);
|
||||
}
|
||||
|
||||
async function setExpression(character, expression, force) {
|
||||
|
@ -1367,7 +1373,8 @@ function onClickExpressionImage() {
|
|||
}
|
||||
|
||||
async function onClickExpressionAddCustom() {
|
||||
let expressionName = await callPopup(renderExtensionTemplate(MODULE_NAME, 'add-custom-expression'), 'input');
|
||||
const template = await renderExtensionTemplateAsync(MODULE_NAME, 'add-custom-expression');
|
||||
let expressionName = await callPopup(template, 'input');
|
||||
|
||||
if (!expressionName) {
|
||||
console.debug('No custom expression name provided');
|
||||
|
@ -1406,14 +1413,15 @@ async function onClickExpressionAddCustom() {
|
|||
}
|
||||
|
||||
async function onClickExpressionRemoveCustom() {
|
||||
const selectedExpression = $('#expression_custom').val();
|
||||
const selectedExpression = String($('#expression_custom').val());
|
||||
|
||||
if (!selectedExpression) {
|
||||
console.debug('No custom expression selected');
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmation = await callPopup(renderExtensionTemplate(MODULE_NAME, 'remove-custom-expression', { expression: selectedExpression }), 'confirm');
|
||||
const template = await renderExtensionTemplateAsync(MODULE_NAME, 'remove-custom-expression', { expression: selectedExpression });
|
||||
const confirmation = await callPopup(template, 'confirm');
|
||||
|
||||
if (!confirmation) {
|
||||
console.debug('Custom expression removal cancelled');
|
||||
|
@ -1712,11 +1720,16 @@ async function fetchImagesNoCache() {
|
|||
$('body').append(element);
|
||||
}
|
||||
async function addSettings() {
|
||||
$('#extensions_settings').append(renderExtensionTemplate(MODULE_NAME, 'settings'));
|
||||
const template = await renderExtensionTemplateAsync(MODULE_NAME, 'settings');
|
||||
$('#extensions_settings').append(template);
|
||||
$('#expression_override_button').on('click', onClickExpressionOverrideButton);
|
||||
$('#expressions_show_default').on('input', onExpressionsShowDefaultInput);
|
||||
$('#expression_upload_pack_button').on('click', onClickExpressionUploadPackButton);
|
||||
$('#expressions_show_default').prop('checked', extension_settings.expressions.showDefault).trigger('input');
|
||||
$('#expression_translate').prop('checked', extension_settings.expressions.translate).on('input', function () {
|
||||
extension_settings.expressions.translate = !!$(this).prop('checked');
|
||||
saveSettingsDebounced();
|
||||
});
|
||||
$('#expression_local').prop('checked', extension_settings.expressions.local).on('input', function () {
|
||||
extension_settings.expressions.local = !!$(this).prop('checked');
|
||||
moduleWorker();
|
||||
|
@ -1743,7 +1756,7 @@ async function fetchImagesNoCache() {
|
|||
|
||||
$('#expression_custom_add').on('click', onClickExpressionAddCustom);
|
||||
$('#expression_custom_remove').on('click', onClickExpressionRemoveCustom);
|
||||
$('#expression_fallback').on('change', onExpressionFallbackChanged)
|
||||
$('#expression_fallback').on('change', onExpressionFallbackChanged);
|
||||
}
|
||||
|
||||
// Pause Talkinghead to save resources when the ST tab is not visible or the window is minimized.
|
||||
|
|
|
@ -10,6 +10,10 @@
|
|||
<input id="expression_local" type="checkbox" />
|
||||
<span data-i18n="Local server classification">Local server classification</span>
|
||||
</label>
|
||||
<label class="checkbox_label" for="expression_translate" title="Use the selected API from Chat Translation extension settings.">
|
||||
<input id="expression_translate" type="checkbox">
|
||||
<span>Translate text to English before classification</span>
|
||||
</label>
|
||||
<label class="checkbox_label" for="expressions_show_default">
|
||||
<input id="expressions_show_default" type="checkbox">
|
||||
<span>Show default images (emojis) if sprite missing</span>
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { getStringHash, debounce, waitUntilCondition, extractAllWords, delay } from '../../utils.js';
|
||||
import { getContext, getApiUrl, extension_settings, doExtrasFetch, modules, renderExtensionTemplate } from '../../extensions.js';
|
||||
import { getContext, getApiUrl, extension_settings, doExtrasFetch, modules, renderExtensionTemplateAsync } from '../../extensions.js';
|
||||
import {
|
||||
activateSendButtons,
|
||||
deactivateSendButtons,
|
||||
|
@ -847,9 +847,9 @@ function setupListeners() {
|
|||
});
|
||||
}
|
||||
|
||||
jQuery(function () {
|
||||
function addExtensionControls() {
|
||||
const settingsHtml = renderExtensionTemplate('memory', 'settings', { defaultSettings });
|
||||
jQuery(async function () {
|
||||
async function addExtensionControls() {
|
||||
const settingsHtml = await renderExtensionTemplateAsync('memory', 'settings', { defaultSettings });
|
||||
$('#extensions_settings2').append(settingsHtml);
|
||||
setupListeners();
|
||||
$('#summaryExtensionPopoutButton').off('click').on('click', function (e) {
|
||||
|
@ -858,7 +858,7 @@ jQuery(function () {
|
|||
});
|
||||
}
|
||||
|
||||
addExtensionControls();
|
||||
await addExtensionControls();
|
||||
loadSettings();
|
||||
eventSource.on(event_types.MESSAGE_RECEIVED, onChatEvent);
|
||||
eventSource.on(event_types.MESSAGE_DELETED, onChatEvent);
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { callPopup, getCurrentChatId, reloadCurrentChat, saveSettingsDebounced } from '../../../script.js';
|
||||
import { extension_settings } from '../../extensions.js';
|
||||
import { extension_settings, renderExtensionTemplateAsync } from '../../extensions.js';
|
||||
import { registerSlashCommand } from '../../slash-commands.js';
|
||||
import { download, getFileText, getSortableDelay, uuidv4 } from '../../utils.js';
|
||||
import { resolveVariable } from '../../variables.js';
|
||||
|
@ -71,7 +71,7 @@ async function deleteRegexScript({ existingId }) {
|
|||
async function loadRegexScripts() {
|
||||
$('#saved_regex_scripts').empty();
|
||||
|
||||
const scriptTemplate = $(await $.get('scripts/extensions/regex/scriptTemplate.html'));
|
||||
const scriptTemplate = $(await renderExtensionTemplateAsync('regex', 'scriptTemplate'));
|
||||
|
||||
extension_settings.regex.forEach((script) => {
|
||||
// Have to clone here
|
||||
|
@ -113,7 +113,7 @@ async function loadRegexScripts() {
|
|||
}
|
||||
|
||||
async function onRegexEditorOpenClick(existingId) {
|
||||
const editorHtml = $(await $.get('scripts/extensions/regex/editor.html'));
|
||||
const editorHtml = $(await renderExtensionTemplateAsync('regex', 'editor'));
|
||||
|
||||
// If an ID exists, fill in all the values
|
||||
let existingScriptIndex = -1;
|
||||
|
@ -316,7 +316,7 @@ jQuery(async () => {
|
|||
return;
|
||||
}
|
||||
|
||||
const settingsHtml = await $.get('scripts/extensions/regex/dropdown.html');
|
||||
const settingsHtml = $(await renderExtensionTemplateAsync('regex', 'dropdown'));
|
||||
$('#extensions_settings2').append(settingsHtml);
|
||||
$('#open_regex_editor').on('click', function () {
|
||||
onRegexEditorOpenClick(false);
|
||||
|
|
|
@ -18,7 +18,7 @@ import {
|
|||
formatCharacterAvatar,
|
||||
substituteParams,
|
||||
} from '../../../script.js';
|
||||
import { getApiUrl, getContext, extension_settings, doExtrasFetch, modules, renderExtensionTemplate } from '../../extensions.js';
|
||||
import { getApiUrl, getContext, extension_settings, doExtrasFetch, modules, renderExtensionTemplateAsync } from '../../extensions.js';
|
||||
import { selected_group } from '../../group-chats.js';
|
||||
import { stringFormat, initScrollHeight, resetScrollHeight, getCharaFilename, saveBase64AsFile, getBase64Async, delay, isTrueBoolean } from '../../utils.js';
|
||||
import { getMessageTimeStamp, humanizedDateTime } from '../../RossAscends-mods.js';
|
||||
|
@ -2990,7 +2990,8 @@ jQuery(async () => {
|
|||
registerSlashCommand('imagine', generatePicture, ['sd', 'img', 'image'], helpString, true, true);
|
||||
registerSlashCommand('imagine-comfy-workflow', changeComfyWorkflow, ['icw'], '(workflowName) - change the workflow to be used for image generation with ComfyUI, e.g. <tt>/imagine-comfy-workflow MyWorkflow</tt>');
|
||||
|
||||
$('#extensions_settings').append(renderExtensionTemplate('stable-diffusion', 'settings', defaultSettings));
|
||||
const template = await renderExtensionTemplateAsync('stable-diffusion', 'settings', defaultSettings);
|
||||
$('#extensions_settings').append(template);
|
||||
$('#sd_source').on('change', onSourceChange);
|
||||
$('#sd_scale').on('input', onScaleInput);
|
||||
$('#sd_steps').on('input', onStepsInput);
|
||||
|
|
|
@ -509,6 +509,8 @@ const handleOutgoingMessage = createEventHandler(translateOutgoingMessage, () =>
|
|||
const handleImpersonateReady = createEventHandler(translateImpersonate, () => shouldTranslate(incomingTypes));
|
||||
const handleMessageEdit = createEventHandler(translateMessageEdit, () => true);
|
||||
|
||||
window['translate'] = translate;
|
||||
|
||||
jQuery(() => {
|
||||
const html = `
|
||||
<div class="translation_settings">
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { eventSource, event_types, extension_prompt_types, getCurrentChatId, getRequestHeaders, is_send_press, saveSettingsDebounced, setExtensionPrompt, substituteParams } from '../../../script.js';
|
||||
import { ModuleWorkerWrapper, extension_settings, getContext, modules, renderExtensionTemplate } from '../../extensions.js';
|
||||
import { ModuleWorkerWrapper, extension_settings, getContext, modules, renderExtensionTemplateAsync } from '../../extensions.js';
|
||||
import { collapseNewlines } from '../../power-user.js';
|
||||
import { SECRET_KEYS, secret_state, writeSecret } from '../../secrets.js';
|
||||
import { debounce, getStringHash as calculateHash, waitUntilCondition, onlyUnique, splitRecursive } from '../../utils.js';
|
||||
|
@ -658,7 +658,8 @@ jQuery(async () => {
|
|||
|
||||
// Migrate from TensorFlow to Transformers
|
||||
settings.source = settings.source !== 'local' ? settings.source : 'transformers';
|
||||
$('#extensions_settings2').append(renderExtensionTemplate(MODULE_NAME, 'settings'));
|
||||
const template = await renderExtensionTemplateAsync(MODULE_NAME, 'settings');
|
||||
$('#extensions_settings2').append(template);
|
||||
$('#vectors_enabled_chats').prop('checked', settings.enabled_chats).on('input', () => {
|
||||
settings.enabled_chats = $('#vectors_enabled_chats').prop('checked');
|
||||
Object.assign(extension_settings.vectors, settings);
|
||||
|
|
|
@ -13,7 +13,6 @@ import {
|
|||
printCharactersDebounced,
|
||||
setCharacterId,
|
||||
setEditedMessageId,
|
||||
renderTemplate,
|
||||
chat,
|
||||
getFirstDisplayedMessageId,
|
||||
showMoreMessages,
|
||||
|
@ -39,6 +38,7 @@ import { registerSlashCommand } from './slash-commands.js';
|
|||
import { tags } from './tags.js';
|
||||
import { tokenizers } from './tokenizers.js';
|
||||
import { BIAS_CACHE } from './logit-bias.js';
|
||||
import { renderTemplateAsync } from './templates.js';
|
||||
|
||||
import { countOccurrences, debounce, delay, download, getFileText, isOdd, resetScrollHeight, shuffle, sortMoments, stringToRange, timestampToMoment } from './utils.js';
|
||||
|
||||
|
@ -1363,8 +1363,8 @@ export function registerDebugFunction(functionId, name, description, func) {
|
|||
debug_functions.push({ functionId, name, description, func });
|
||||
}
|
||||
|
||||
function showDebugMenu() {
|
||||
const template = renderTemplate('debug', { functions: debug_functions });
|
||||
async function showDebugMenu() {
|
||||
const template = await renderTemplateAsync('debug', { functions: debug_functions });
|
||||
callPopup(template, 'text', '', { wide: true, large: true });
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,130 @@
|
|||
import { applyLocale } from './i18n.js';
|
||||
|
||||
/**
|
||||
* @type {Map<string, function>}
|
||||
* @description Cache for Handlebars templates.
|
||||
*/
|
||||
const TEMPLATE_CACHE = new Map();
|
||||
|
||||
/**
|
||||
* Loads a URL content using XMLHttpRequest synchronously.
|
||||
* @param {string} url URL to load synchronously
|
||||
* @returns {string} Response text
|
||||
*/
|
||||
function getUrlSync(url) {
|
||||
console.debug('Loading URL synchronously', url);
|
||||
const request = new XMLHttpRequest();
|
||||
request.open('GET', url, false); // `false` makes the request synchronous
|
||||
request.send();
|
||||
|
||||
if (request.status >= 200 && request.status < 300) {
|
||||
return request.responseText;
|
||||
}
|
||||
|
||||
throw new Error(`Error loading ${url}: ${request.status} ${request.statusText}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a URL content using XMLHttpRequest asynchronously.
|
||||
* @param {string} url URL to load asynchronously
|
||||
* @returns {Promise<string>} Response text
|
||||
*/
|
||||
function getUrlAsync(url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = new XMLHttpRequest();
|
||||
request.open('GET', url, true);
|
||||
request.onload = () => {
|
||||
if (request.status >= 200 && request.status < 300) {
|
||||
resolve(request.responseText);
|
||||
} else {
|
||||
reject(new Error(`Error loading ${url}: ${request.status} ${request.statusText}`));
|
||||
}
|
||||
};
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Error loading ${url}: ${request.status} ${request.statusText}`));
|
||||
};
|
||||
request.send();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a Handlebars template asynchronously.
|
||||
* @param {string} templateId ID of the template to render
|
||||
* @param {Record<string, any>} templateData The data to pass to the template
|
||||
* @param {boolean} sanitize Should the template be sanitized with DOMPurify
|
||||
* @param {boolean} localize Should the template be localized
|
||||
* @param {boolean} fullPath Should the template ID be treated as a full path or a relative path
|
||||
* @returns {Promise<string>} Rendered template
|
||||
*/
|
||||
export async function renderTemplateAsync(templateId, templateData = {}, sanitize = true, localize = true, fullPath = false) {
|
||||
async function fetchTemplateAsync(pathToTemplate) {
|
||||
let template = TEMPLATE_CACHE.get(pathToTemplate);
|
||||
if (!template) {
|
||||
const templateContent = await getUrlAsync(pathToTemplate);
|
||||
template = Handlebars.compile(templateContent);
|
||||
TEMPLATE_CACHE.set(pathToTemplate, template);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
try {
|
||||
const pathToTemplate = fullPath ? templateId : `/scripts/templates/${templateId}.html`;
|
||||
const template = await fetchTemplateAsync(pathToTemplate);
|
||||
let result = template(templateData);
|
||||
|
||||
if (sanitize) {
|
||||
result = DOMPurify.sanitize(result);
|
||||
}
|
||||
|
||||
if (localize) {
|
||||
result = applyLocale(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
console.error('Error rendering template', templateId, templateData, err);
|
||||
toastr.error('Check the DevTools console for more information.', 'Error rendering template');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a Handlebars template synchronously.
|
||||
* @param {string} templateId ID of the template to render
|
||||
* @param {Record<string, any>} templateData The data to pass to the template
|
||||
* @param {boolean} sanitize Should the template be sanitized with DOMPurify
|
||||
* @param {boolean} localize Should the template be localized
|
||||
* @param {boolean} fullPath Should the template ID be treated as a full path or a relative path
|
||||
* @returns {string} Rendered template
|
||||
*
|
||||
* @deprecated Use renderTemplateAsync instead.
|
||||
*/
|
||||
export function renderTemplate(templateId, templateData = {}, sanitize = true, localize = true, fullPath = false) {
|
||||
function fetchTemplateSync(pathToTemplate) {
|
||||
let template = TEMPLATE_CACHE.get(pathToTemplate);
|
||||
if (!template) {
|
||||
const templateContent = getUrlSync(pathToTemplate);
|
||||
template = Handlebars.compile(templateContent);
|
||||
TEMPLATE_CACHE.set(pathToTemplate, template);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
try {
|
||||
const pathToTemplate = fullPath ? templateId : `/scripts/templates/${templateId}.html`;
|
||||
const template = fetchTemplateSync(pathToTemplate);
|
||||
let result = template(templateData);
|
||||
|
||||
if (sanitize) {
|
||||
result = DOMPurify.sanitize(result);
|
||||
}
|
||||
|
||||
if (localize) {
|
||||
result = applyLocale(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
console.error('Error rendering template', templateId, templateData, err);
|
||||
toastr.error('Check the DevTools console for more information.', 'Error rendering template');
|
||||
}
|
||||
}
|
|
@ -508,24 +508,36 @@ llamacpp.post('/slots', jsonParser, async function (request, response) {
|
|||
if (!request.body.server_url) {
|
||||
return response.sendStatus(400);
|
||||
}
|
||||
if (!/^\d+$/.test(request.body.id_slot)) {
|
||||
return response.sendStatus(400);
|
||||
}
|
||||
if (!/^(erase|restore|save)$/.test(request.body.action)) {
|
||||
if (!/^(erase|info|restore|save)$/.test(request.body.action)) {
|
||||
return response.sendStatus(400);
|
||||
}
|
||||
|
||||
console.log('LlamaCpp slots request:', request.body);
|
||||
const baseUrl = trimV1(request.body.server_url);
|
||||
|
||||
const fetchResponse = await fetch(`${baseUrl}/slots/${request.body.id_slot}?action=${request.body.action}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
timeout: 0,
|
||||
body: JSON.stringify({
|
||||
filename: `${request.body.filename}`,
|
||||
}),
|
||||
});
|
||||
let fetchResponse;
|
||||
if (request.body.action === "info") {
|
||||
fetchResponse = await fetch(`${baseUrl}/slots`, {
|
||||
method: 'GET',
|
||||
timeout: 0,
|
||||
});
|
||||
} else {
|
||||
if (!/^\d+$/.test(request.body.id_slot)) {
|
||||
return response.sendStatus(400);
|
||||
}
|
||||
if (request.body.action !== "erase" && !request.body.filename) {
|
||||
return response.sendStatus(400);
|
||||
}
|
||||
|
||||
fetchResponse = await fetch(`${baseUrl}/slots/${request.body.id_slot}?action=${request.body.action}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
timeout: 0,
|
||||
body: JSON.stringify({
|
||||
filename: request.body.action !== "erase" ? `${request.body.filename}` : undefined,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
if (!fetchResponse.ok) {
|
||||
console.log('LlamaCpp slots error:', fetchResponse.status, fetchResponse.statusText);
|
||||
|
|
Loading…
Reference in New Issue