Compare commits

..
Author SHA1 Message Date
Wolfsblvt 7ee041c11d fix: handle nested same-delimiter emphasis in markdown rendering
Showdown cannot natively process nested emphasis with the same delimiter
(e.g. *outer *inner* outer* or **outer **inner** outer**), rendering
them as broken text. Add a pre-processing step that detects nesting using
stack-based pairing with CommonMark-like flanking rules:

- Nested *...* inside *...*: promote inner to ** (bold-inside-italic)
- Nested **...** inside **...**:  strip inner ** (redundant bold)

Adds showdown-emphasis.js combining the underscore extension with the new
fixNestedEmphasis pre-processor, called in messageFormatting before
fixMarkdown. Includes 27 Playwright e2e tests.

Closes #5500
2026-05-16 05:20:07 +02:00
39 changed files with 622 additions and 1214 deletions
+1 -2
View File
@@ -26,7 +26,7 @@ SillyTavernは、多くのLLM API(KoboldAI/CPP、Horde、NovelAI、Ooba、Tabb
SillyTavern(略してST)は、テキスト生成LLM、画像生成エンジン、TTS音声モデルと対話するための、ローカルにインストールされるユーザーインターフェースです。
2023年2月にTavernAI 1.2.8のフォークとして始まり、SillyTavernは現在300人以上の貢献者と3年間の独立した開発を経て、知識豊富なAI愛好家のための主要なソフトウェアとして機能し続けています。
2023年2月にTavernAI 1.2.8のフォークとして始まり、SillyTavernは現在200人以上の貢献者と2年間の独立した開発を経て、知識豊富なAI愛好家のための主要なソフトウェアとして機能し続けています。
## 私たちのビジョン
@@ -79,7 +79,6 @@ SillyTavern(略してST)は、テキスト生成LLM、画像生成エンジ
* CncAnonのTavernAITurbo modの一部を許可を得て使用
* PepperTacoの作品に触発されたビジュアルノベルモード (<https://github.com/peppertaco/Tavern/>)
* GoogleによるNoto Sansフォント (OFLライセンス)
* Chevrotainによるレキサー/パーサー (Apache-2.0ライセンス) <https://github.com/chevrotain/chevrotain>
* Font Awesomeによるアイコンテーマ <https://fontawesome.com> (アイコン: CC BY 4.0, フォント: SIL OFL 1.1, コード: MITライセンス)
* @OtisAlejandroによるデフォルトコンテンツ(Seraphinaキャラクターと伝承本)と@kallmefloccによる10K Discordユーザー記念背景
* [@mrguymiah](https://github.com/mrguymiah)と[@Bronya-Rand](https://github.com/Bronya-Rand)によるDockerガイド
+1 -2
View File
@@ -26,7 +26,7 @@ SillyTavern 为众多 LLM API(KoboldAI/CPP、Horde、NovelAI、Ooba、Tabby、
SillyTavern(简称 ST)是一个本地安装的用户界面,允许您与文本生成 LLM、图像生成引擎和 TTS 语音模型进行交互。
SillyTavern 于 2023 年 2 月作为 TavernAI 1.2.8 的一个分支开始,如今已拥有超过 300 名贡献者和 3 年的独立开发经验,并继续作为资深 AI 爱好者领先的软件。
SillyTavern 于 2023 年 2 月作为 TavernAI 1.2.8 的一个分支开始,如今已拥有超过 200 名贡献者和 2 年的独立开发经验,并继续作为资深 AI 爱好者领先的软件。
## 我们的愿景
@@ -79,7 +79,6 @@ SillyTavern 于 2023 年 2 月作为 TavernAI 1.2.8 的一个分支开始,如
* CncAnon 的 TavernAITurbo mod 的部分内容经许可使用
* 视觉小说模式的灵感来自 PepperTaco 的工作 (<https://github.com/peppertaco/Tavern/>)
* Noto Sans 字体 by Google (OFL 许可证)
* Lexer/Parser 由 Chevrotain 提供 (Apache-2.0 许可证) <https://github.com/chevrotain/chevrotain>
* 图标主题 by Font Awesome <https://fontawesome.com> (图标: CC BY 4.0, 字体: SIL OFL 1.1, 代码: MIT 许可证)
* 默认内容由 @OtisAlejandro (Seraphina 角色和世界书) 和 @kallmeflocc (10K Discord 用户庆祝背景) 提供
* Docker 指南由 [@mrguymiah](https://github.com/mrguymiah) 和 [@Bronya-Rand](https://github.com/Bronya-Rand) 提供
+2 -3
View File
@@ -26,7 +26,7 @@ SillyTavern 提供一個統一的前端介面,整合多種大型語言模型
SillyTavern(簡稱 ST)是一款本地安裝的使用者介面,讓您能與大型語言模型(LLM)、影像生成引擎以及語音合成模型互動的前端。
SillyTavern 起源於 2023 年 2 月,作為 TavernAI 1.2.8 的分支版本發展至今。目前已有超過 300 位貢獻者,並擁有超過三年的獨立開發歷史。如今,它已成為 AI 愛好者中備受推崇的軟體之一。
SillyTavern 起源於 2023 年 2 月,作為 TavernAI 1.2.8 的分支版本發展至今。目前已有超過 200 位貢獻者,並擁有超過兩年的獨立開發歷史。如今,它已成為 AI 愛好者中備受推崇的軟體之一。
## 我們的願景
@@ -42,7 +42,7 @@ SillyTavern 的硬體需求相當低。任何能夠運行 NodeJS 20 或更高版
### 歡迎加入我們的 Discord 伺服器
| [![][discord-shield-badge]][discord-link] | [加入我們的 Discord 伺服器](https://discord.gg/sillytavern) 以獲得技術支援、分享您喜愛的角色與提示詞。 |
| [![][discord-shield-badge]][discord-link] | [加入我們的 Disocrd 伺服器](https://discord.gg/sillytavern) 以獲得技術支援、分享您喜愛的角色與提示詞。 |
| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
或直接聯繫開發者:
@@ -79,7 +79,6 @@ SillyTavern 的硬體需求相當低。任何能夠運行 NodeJS 20 或更高版
* 經授權使用部分來自 CncAnon 的 TavernAITurbo 模組
* 視覺小說模式(Visual Novel Mode)的靈感,來源於 PepperTaco 的貢獻(<https://github.com/peppertaco/Tavern/>)
* Noto Sans 字體由 Google 提供(OFL 許可)
* Lexer/Parser 由 Chevrotain 提供 (Apache-2.0 許可) <https://github.com/chevrotain/chevrotain>
* 主題圖示由 Font Awesome <https://fontawesome.com> 提供(圖示:CC BY 4.0,字體:SIL OFL 1.1,程式碼:MIT 許可)
* 預設資源來源於 @OtisAlejandro(包含角色 Seraphina 與知識書)與 @kallmeflocc(SillyTavern 官方 Discord 伺服器成員突破 10K 的慶祝背景)
* Docker 安裝指南由 [@mrguymiah](https://github.com/mrguymiah) 和 [@Bronya-Rand](https://github.com/Bronya-Rand) 編寫
-6
View File
@@ -1,8 +1,2 @@
ignore-scripts=true
min-release-age=7
allow-directory=none
allow-file=none
allow-git=none
# Temporarily disabled due to an npm bug:
# https://github.com/npm/cli/issues/9347
# allow-remote=none
-2
View File
@@ -198,8 +198,6 @@ rateLimiting:
accountsLoginMaxAttempts: 5
# Set the maximum number of allowed failed account recovery attempts before rate limiting is applied. Set to 0 to disable rate limiting for account recovery.
accountsRecoverMaxAttempts: 5
# Set the maximum number of allowed failed account reset attempts before rate limiting is applied. Set to 0 to disable rate limiting for account resets.
accountsResetMaxAttempts: 5
# Set to true to enable support for real IPs in certain request headers for features like IP whitelisting, rate limiting and access logging.
# Only change if you are sure that you use a correctly configured reverse proxy, otherwise this may lead to IP spoofing.
forwardedHeaders:
+11 -25
View File
@@ -3307,9 +3307,6 @@
<div>
<h4 data-i18n="Google Model">Google Model</h4>
<select id="model_google_select">
<optgroup label="Gemini 3.5">
<option value="gemini-3.5-flash">gemini-3.5-flash</option>
</optgroup>
<optgroup label="Gemini 3.1">
<option value="gemini-3.1-pro-preview">gemini-3.1-pro-preview</option>
<option value="gemini-3.1-flash-lite-preview">gemini-3.1-flash-lite-preview</option>
@@ -3490,9 +3487,6 @@
<h4 data-i18n="Google Model">Google Model</h4>
<select id="model_vertexai_select">
<!-- data-mode="full" is for models that require a service account -->
<optgroup label="Gemini 3.5">
<option value="gemini-3.5-flash">gemini-3.5-flash</option>
</optgroup>
<optgroup label="Gemini 3.1">
<option value="gemini-3.1-pro-preview">gemini-3.1-pro-preview</option>
<option value="gemini-3.1-flash-lite-preview">gemini-3.1-flash-lite-preview</option>
@@ -3880,24 +3874,17 @@
</select>
</div>
<div id="pollinations_form" data-source="pollinations">
<h4 data-i18n="Pollinations Endpoint">Pollinations Endpoint</h4>
<select id="pollinations_endpoint">
<option value="anonymous" data-i18n="Anonymous (No Key)">Anonymous (No Key)</option>
<option value="authenticated" data-i18n="Authenticated (API Key)">Authenticated (API Key)</option>
</select>
<div id="pollinations_key_section">
<h4>
<a href="https://enter.pollinations.ai/" target="_blank" rel="noopener noreferrer" data-i18n="Pollinations API Key">
Pollinations API Key
</a>
</h4>
<div class="flex-container">
<input id="api_key_pollinations" name="api_key_pollinations" class="text_pole flex1" value="" type="text" placeholder="sk_..." autocomplete="off">
<div title="Manage API keys" data-i18n="[title]Manage API keys" class="menu_button fa-solid fa-key fa-fw manage-api-keys" data-key="api_key_pollinations"></div>
</div>
<div data-for="api_key_pollinations" class="neutral_warning" data-i18n="For privacy reasons, your API key will be hidden after you click 'Connect'.">
For privacy reasons, your API key will be hidden after you click 'Connect'.
</div>
<h4>
<a href="https://enter.pollinations.ai/" target="_blank" rel="noopener noreferrer" data-i18n="Pollinations API Key">
Pollinations API Key
</a>
</h4>
<div class="flex-container">
<input id="api_key_pollinations" name="api_key_pollinations" class="text_pole flex1" value="" type="text" autocomplete="off">
<div title="Manage API keys" data-i18n="[title]Manage API keys" class="menu_button fa-solid fa-key fa-fw manage-api-keys" data-key="api_key_pollinations"></div>
</div>
<div data-for="api_key_pollinations" class="neutral_warning" data-i18n="For privacy reasons, your API key will be hidden after you click 'Connect'.">
For privacy reasons, your API key will be hidden after you click 'Connect'.
</div>
<h4 data-i18n="Pollinations Model">Pollinations Model</h4>
<select id="model_pollinations_select">
@@ -3951,7 +3938,6 @@
</select>
<h4 data-i18n="Z.AI Model">Z.AI Model</h4>
<select id="model_zai_select">
<option value="glm-5.2">glm-5.2</option>
<option value="glm-5-turbo">glm-5-turbo</option>
<option value="glm-5v-turbo">glm-5v-turbo</option>
<option value="glm-5.1">glm-5.1</option>
+15 -42
View File
@@ -215,7 +215,7 @@ import {
} from './scripts/tags.js';
import { checkOpenRouterAuth, initSecrets, readSecretState } from './scripts/secrets.js';
import { markdownExclusionExt } from './scripts/showdown-exclusion.js';
import { markdownUnderscoreExt } from './scripts/showdown-underscore.js';
import { markdownUnderscoreExt, fixNestedEmphasis } from './scripts/showdown-emphasis.js';
import { NOTE_MODULE_NAME, initAuthorsNote, metadata_keys, setFloatingPrompt, shouldWIAddPrompt } from './scripts/authors-note.js';
import { registerPromptManagerMigration } from './scripts/PromptManager.js';
import { getRegexedString, regex_placement } from './scripts/extensions/regex/engine.js';
@@ -282,7 +282,6 @@ import { initDomHandlers } from './scripts/dom-handlers.js';
import { SimpleMutex } from './scripts/util/SimpleMutex.js';
import { AudioPlayer } from './scripts/audio-player.js';
import { MacroEnvBuilder } from './scripts/macros/engine/MacroEnvBuilder.js';
import { MessageFormatter } from './scripts/message-formatter.js';
import { MacroEngine } from './scripts/macros/engine/MacroEngine.js';
import { addChatBackupsBrowser } from './scripts/chat-backups.js';
import { onboardingExperimentalMacroEngine } from './scripts/macros/engine/MacroDiagnostics.js';
@@ -1741,35 +1740,15 @@ export async function sendTextareaMessage() {
}
/**
* Formats raw message text into an HTML string ready for DOM insertion.
*
* The pipeline is, in order:
* 1. Prompt-bias stripping (message 0 only)
* 2. Comment / hidden-message normalisation
* 3. `beforeRegex` extension hooks (see {@link MessageFormatter})
* 4. Custom regex rules (`getRegexedString`)
* 5. `afterRegex` extension hooks
* 6. Markdown auto-fix (`fixMarkdown`)
* 7. HTML tag encoding (`encode_tags`)
* 8. Showdown Markdown → HTML conversion
* 9. `afterMarkdown` extension hooks
* 10. Name-prefix stripping (`allow_name2_display`)
* 11. DOMPurify sanitization
*
* All extension hooks run **before** DOMPurify (steps 3, 5, 9) so their
* output is always sanitised.
*
* @param {string} mes - Raw message text.
* @param {string} ch_name - Character name associated with the message.
* @param {boolean} isSystem - Whether the message is a system message.
* @param {boolean} isUser - Whether the message was sent by the user.
* @param {number} messageId - Index of the message in the chat array, or -1
* for transient messages (e.g. streaming previews).
* @param {Partial<DOMPurify.Config>} [sanitizerOverrides] - DOMPurify option
* overrides. Merged on top of the default config.
* @param {boolean} [isReasoning=false] - Whether the message is reasoning/thinking
* output (affects regex placement and some display rules).
* @returns {string} Sanitized HTML string ready to assign to `innerHTML`.
* Formats the message text into an HTML string using Markdown and other formatting.
* @param {string} mes Message text
* @param {string} ch_name Character name
* @param {boolean} isSystem If the message was sent by the system
* @param {boolean} isUser If the message was sent by the user
* @param {number} messageId Message index in chat array
* @param {Partial<DOMPurify.Config>} [sanitizerOverrides] DOMPurify sanitizer option overrides
* @param {boolean} [isReasoning] If the message is reasoning output
* @returns {string} HTML string
*/
export function messageFormatting(mes, ch_name, isSystem, isUser, messageId, sanitizerOverrides = {}, isReasoning = false) {
if (!mes) {
@@ -1826,20 +1805,18 @@ export function messageFormatting(mes, ch_name, isSystem, isUser, messageId, san
const indexOf = usableMessages.findIndex(x => x.index === Number(messageId));
const depth = messageId >= 0 && indexOf !== -1 ? (usableMessages.length - indexOf - 1) : undefined;
mes = MessageFormatter.runStage(MessageFormatter.stage.BEFORE_REGEX, mes,
{ ch_name, isSystem, isUser, messageId, isReasoning },
);
// Always override the character name
mes = getRegexedString(mes, regexPlacement, {
characterOverride: ch_name,
isMarkdown: true,
depth: depth,
});
}
mes = MessageFormatter.runStage(MessageFormatter.stage.AFTER_REGEX, mes,
{ ch_name, isSystem, isUser, messageId, isReasoning },
);
// Convert nested same-delimiter emphasis to bold before any markdown fixing.
// Must run before fixMarkdown which would strip the spaces that indicate nesting.
if (!isSystem) {
mes = fixNestedEmphasis(mes);
}
if (power_user.auto_fix_generated_markdown) {
@@ -1918,10 +1895,6 @@ export function messageFormatting(mes, ch_name, isSystem, isUser, messageId, san
mes = mes.replace(/<code(.*)>[\s\S]*?<\/code>/g, function (match) {
return match.replace(/&amp;/g, '&');
});
mes = MessageFormatter.runStage(MessageFormatter.stage.AFTER_MARKDOWN, mes,
{ ch_name, isSystem, isUser, messageId, isReasoning },
);
}
if (!power_user.allow_name2_display && ch_name && !isUser && !isSystem) {
+2 -2
View File
@@ -34,7 +34,7 @@ import {
secret_state,
} from './secrets.js';
import { debounce, getStringHash, isValidUrl } from './utils.js';
import { chat_completion_sources, oai_settings, POLLINATIONS_ENDPOINT } from './openai.js';
import { chat_completion_sources, oai_settings } from './openai.js';
import { getTokenCountAsync } from './tokenizers.js';
import { textgen_types, textgenerationwebui_settings as textgen_settings, getTextGenServer } from './textgen-settings.js';
import { debounce_timeout, SWIPE_SOURCE } from './constants.js';
@@ -406,7 +406,7 @@ function RA_autoconnect(PrevApi) {
|| (secret_state[SECRET_KEYS.FIREWORKS] && oai_settings.chat_completion_source == chat_completion_sources.FIREWORKS)
|| (secret_state[SECRET_KEYS.COMETAPI] && oai_settings.chat_completion_source == chat_completion_sources.COMETAPI)
|| (secret_state[SECRET_KEYS.ZAI] && oai_settings.chat_completion_source == chat_completion_sources.ZAI)
|| ((secret_state[SECRET_KEYS.POLLINATIONS] || oai_settings.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS) && oai_settings.chat_completion_source === chat_completion_sources.POLLINATIONS)
|| (secret_state[SECRET_KEYS.POLLINATIONS] && oai_settings.chat_completion_source === chat_completion_sources.POLLINATIONS)
|| (secret_state[SECRET_KEYS.WORKERS_AI] && oai_settings.chat_completion_source == chat_completion_sources.WORKERS_AI)
|| (secret_state[SECRET_KEYS.MINIMAX] && oai_settings.chat_completion_source == chat_completion_sources.MINIMAX)
|| (isValidUrl(oai_settings.custom_url) && oai_settings.chat_completion_source == chat_completion_sources.CUSTOM)
+1 -3
View File
@@ -674,9 +674,7 @@ export class AutoComplete {
this.clone.remove();
}
});
if (this.textarea.parentElement) {
mo.observe(this.textarea.parentElement, { childList: true });
}
mo.observe(this.textarea.parentElement, { childList: true });
}
this.clone.style.height = `${inputRect.height}px`;
this.clone.style.left = `${inputRect.left}px`;
+1 -1
View File
@@ -592,7 +592,7 @@ export class ChatCompletionService {
}
// Ensure api-url is properly applied for all sources that accept it
['custom_url', 'vertexai_region', 'zai_endpoint', 'siliconflow_endpoint', 'minimax_endpoint', 'pollinations_endpoint'].forEach(field => {
['custom_url', 'vertexai_region', 'zai_endpoint', 'siliconflow_endpoint', 'minimax_endpoint'].forEach(field => {
// The order is: connection profile => CC preset => CC settings
overridePayload[field] = overridePayload[field] || settings[field] || oai_settings[field];
});
+3 -3
View File
@@ -3,7 +3,7 @@ import { getContext, getApiUrl, doExtrasFetch, extension_settings, modules, rend
import { appendMediaToMessage, chat_metadata, eventSource, event_types, getRequestHeaders, saveChatConditional, saveSettingsDebounced, substituteParams } from '../../../script.js';
import { getMessageTimeStamp } from '../../RossAscends-mods.js';
import { SECRET_KEYS, secret_state } from '../../secrets.js';
import { oai_settings, POLLINATIONS_ENDPOINT } from '../../openai.js';
import { oai_settings } from '../../openai.js';
import { getMultimodalCaption } from '../shared.js';
import { textgen_types, textgenerationwebui_settings } from '../../textgen-settings.js';
import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
@@ -530,8 +530,8 @@ export async function init() {
return true;
}
// Custom API and anonymous Pollinations don't need additional checks
if (api === 'custom' || (api === 'pollinations' && oai_settings.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS)) {
// Custom API doesn't need additional checks
if (api === 'custom') {
return true;
}
}
@@ -120,7 +120,6 @@
<option data-type="anthropic" value="claude-3-5-haiku-20241022">claude-3-5-haiku-20241022</option>
<option data-type="anthropic" value="claude-3-opus-20240229">claude-3-opus-20240229</option>
<option data-type="anthropic" value="claude-3-haiku-20240307">claude-3-haiku-20240307</option>
<option data-type="google" value="gemini-3.5-flash">gemini-3.5-flash</option>
<option data-type="google" value="gemini-3.1-pro-preview">gemini-3.1-pro-preview</option>
<option data-type="google" value="gemini-3.1-flash-lite-preview">gemini-3.1-flash-lite-preview</option>
<option data-type="google" value="gemini-3.1-flash-image-preview">gemini-3.1-flash-image-preview</option>
@@ -159,7 +158,6 @@
<option data-type="google" value="gemma-3-27b-it">gemma-3-27b-it</option>
<option data-type="google" value="gemma-3-12b-it">gemma-3-12b-it</option>
<option data-type="google" value="gemma-3-4b-it">gemma-3-4b-it</option>
<option data-type="vertexai" value="gemini-3.5-flash">gemini-3.5-flash</option>
<option data-type="vertexai" value="gemini-3.1-pro-preview">gemini-3.1-pro-preview</option>
<option data-type="vertexai" value="gemini-3.1-flash-lite-preview">gemini-3.1-flash-lite-preview</option>
<option data-type="vertexai" value="gemini-3.1-flash-image-preview">gemini-3.1-flash-image-preview</option>
@@ -381,7 +381,7 @@ export class SettingsUi {
if (name && name.length > 0) {
const oldQrs = QuickReplySet.get(name);
if (oldQrs) {
const replace = Popup.show.confirm('Replace existing Quick Reply set', `A Quick Reply Set named "${name}" already exists.<br>Do you want to overwrite the existing Quick Reply Set?<br>The existing set will be deleted. This cannot be undone.`);
const replace = Popup.show.confirm('Replace existing World Info', `A Quick Reply Set named "${name}" already exists.<br>Do you want to overwrite the existing Quick Reply Set?<br>The existing set will be deleted. This cannot be undone.`);
if (replace) {
const idx = QuickReplySet.list.indexOf(oldQrs);
await this.doDeleteQrSet(oldQrs);
@@ -444,7 +444,7 @@ export class SettingsUi {
qrs.init();
const oldQrs = QuickReplySet.get(props.name);
if (oldQrs) {
const replace = Popup.show.confirm('Replace existing Quick Reply set', `A Quick Reply Set named "${name}" already exists.<br>Do you want to overwrite the existing Quick Reply Set?<br>The existing set will be deleted. This cannot be undone.`);
const replace = Popup.show.confirm('Replace existing World Info', `A Quick Reply Set named "${name}" already exists.<br>Do you want to overwrite the existing Quick Reply Set?<br>The existing set will be deleted. This cannot be undone.`);
if (replace) {
const idx = QuickReplySet.list.indexOf(oldQrs);
await this.doDeleteQrSet(oldQrs);
+2 -7
View File
@@ -1,7 +1,7 @@
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, POLLINATIONS_ENDPOINT } from '../openai.js';
import { oai_settings, proxies, ZAI_ENDPOINT } from '../openai.js';
import { SECRET_KEYS, secret_state } from '../secrets.js';
import { textgen_types, textgenerationwebui_settings } from '../textgen-settings.js';
import { getTokenCountAsync } from '../tokenizers.js';
@@ -126,10 +126,6 @@ export async function getMultimodalCaption(base64Img, prompt) {
requestBody.zai_endpoint = oai_settings.zai_endpoint || ZAI_ENDPOINT.COMMON;
}
if (extension_settings.caption.multimodal_api === 'pollinations') {
requestBody.pollinations_endpoint = oai_settings.pollinations_endpoint || POLLINATIONS_ENDPOINT.AUTHENTICATED;
}
if (extension_settings.caption.multimodal_api === 'workers_ai') {
requestBody.workers_ai_account_id = oai_settings.workers_ai_account_id;
}
@@ -288,7 +284,7 @@ function throwIfInvalidModel(useReverseProxy) {
throw new Error('Z.AI API key is not set.');
}
if (multimodalApi === 'pollinations' && oai_settings.pollinations_endpoint !== POLLINATIONS_ENDPOINT.ANONYMOUS && !secret_state[SECRET_KEYS.POLLINATIONS]) {
if (multimodalApi === 'pollinations' && !secret_state[SECRET_KEYS.POLLINATIONS]) {
throw new Error('Pollinations API key is not set.');
}
@@ -453,7 +449,6 @@ export class ConnectionManagerRequestService {
zai_endpoint: profile['api-url'],
siliconflow_endpoint: profile['api-url'],
minimax_endpoint: profile['api-url'],
pollinations_endpoint: profile['api-url'],
reverse_proxy: proxyPreset?.url,
proxy_password: proxyPreset?.password,
custom_prompt_post_processing: profile['prompt-post-processing'],
@@ -12,7 +12,7 @@ export class GoogleNativeTtsProvider {
defaultSettings = {
voiceMap: {},
model: 'gemini-3.1-flash-tts-preview',
model: 'gemini-2.5-flash-preview-tts',
apiType: 'makersuite',
};
@@ -32,7 +32,6 @@ export class GoogleNativeTtsProvider {
<select id="google-tts-model">
<option value="gemini-2.5-flash-preview-tts">Gemini 2.5 Flash Preview TTS</option>
<option value="gemini-2.5-pro-preview-tts">Gemini 2.5 Pro Preview TTS</option>
<option value="gemini-3.1-flash-tts-preview">Gemini 3.1 Flash TTS Preview</option>
</select>
</div>
</div>`;
@@ -289,8 +289,8 @@ export function registerCoreMacros() {
description: 'Any kind of text as comment. If you want multiline comments, consider using a scoped macro like {{//}}First\nSecond{{///}}.',
},
],
// list: true, // We consume any arguments as if this is a list, but we'll ignore them in the handler anyway
// strictArgs: false, // and we also always remove it, even if the parsing might say it's invalid
list: true, // We consume any arguments as if this is a list, but we'll ignore them in the handler anyway
strictArgs: false, // and we also always remove it, even if the parsing might say it's invalid
description: 'Comment macro that produces an empty string. Can be used for writing into prompt definitions, without being passed to the context.',
returns: '',
displayOverride: '{{// ...}}',
@@ -155,62 +155,6 @@ export function registerVariableMacros() {
},
});
// {{setvarkey::name::key::value}} -> ''
MacroRegistry.registerMacro('setvarkey', {
aliases: [{ alias: 'setvarindex' }],
category: MacroCategory.VARIABLE,
unnamedArgs: [
{
name: 'name',
type: MacroValueType.STRING,
description: 'The name of the local object or array.',
},
{
name: 'key',
type: [MacroValueType.STRING, MacroValueType.NUMBER],
description: 'The key of an object or the index of an array.',
},
{
name: 'value',
type: [MacroValueType.STRING, MacroValueType.NUMBER],
description: 'The value to set at the specified key or index.',
},
],
description: 'Sets a value at a specific key or index in a local object or array. If the variable does not exist, it will be created based on the type of the key.',
returns: '',
exampleUsage: ['{{setvarkey::myarray::0::foo}}', '{{setvarkey::myobj::uniquekey::somevalue}}'],
handler: ({ unnamedArgs: [name, key, value] }) => {
ctx.variables.local.set(name, value, { index: key });
return '';
},
});
// {{getvarkey::name::key}} -> returns value at key
MacroRegistry.registerMacro('getvarkey', {
aliases: [{ alias: 'getvarindex' }],
category: MacroCategory.VARIABLE,
unnamedArgs: [
{
name: 'name',
type: MacroValueType.STRING,
description: 'The name of the local object or array variable to get from.',
},
{
name: 'key',
type: [MacroValueType.STRING, MacroValueType.NUMBER],
description: 'The key of an object or the index of an array.',
},
],
description: 'Gets a value at a specific key or index in a local object or array variable.',
returns: 'The value at the specified key or index in the local object or array variable.',
returnType: [MacroValueType.STRING, MacroValueType.NUMBER],
exampleUsage: ['{{getvarkey::myarray::0}}', '{{getvarkey::myobj::uniquekey}}'],
handler: ({ unnamedArgs: [name, key], normalize }) => {
const result = ctx.variables.local.get(name, { index: key });
return normalize(result);
},
});
// {{setglobalvar::name::value}} -> ''
MacroRegistry.registerMacro('setglobalvar', {
category: MacroCategory.VARIABLE,
@@ -358,60 +302,4 @@ export function registerVariableMacros() {
return '';
},
});
// {{setglobalvarkey::name::key::value}} -> ''
MacroRegistry.registerMacro('setglobalvarkey', {
aliases: [{ alias: 'setglobalvarindex' }],
category: MacroCategory.VARIABLE,
unnamedArgs: [
{
name: 'name',
type: MacroValueType.STRING,
description: 'The name of the global object or array variable.',
},
{
name: 'key',
type: [MacroValueType.STRING, MacroValueType.NUMBER],
description: 'The key of an object or the index of an array element to set.',
},
{
name: 'value',
type: [MacroValueType.STRING, MacroValueType.NUMBER],
description: 'The value to set at the specified key or index.',
},
],
description: 'Sets a value at a specific key or index in a global object or array variable. If the variable does not exist, it will be created based on the type of the key.',
returns: '',
exampleUsage: ['{{setglobalvarkey::myarray::0::foo}}', '{{setglobalvarkey::myobj::uniquekey::bar}}'],
handler: ({ unnamedArgs: [name, key, value] }) => {
ctx.variables.global.set(name, value, { index: key });
return '';
},
});
// {{getglobalvarkey::name::key}} -> returns value at key
MacroRegistry.registerMacro('getglobalvarkey', {
aliases: [{ alias: 'getglobalvarindex' }],
category: MacroCategory.VARIABLE,
unnamedArgs: [
{
name: 'name',
type: MacroValueType.STRING,
description: 'The name of the global object or array variable to get from.',
},
{
name: 'key',
type: [MacroValueType.STRING, MacroValueType.NUMBER],
description: 'The key of an object or the index of an array element to get.',
},
],
description: 'Gets a value at a specific key or index in a global object or array variable.',
returns: 'The value at the specified key or index in the global object or array variable.',
returnType: [MacroValueType.STRING, MacroValueType.NUMBER],
exampleUsage: ['{{getglobalvarkey::myarray::0}}', '{{getglobalvarkey::myobj::uniquekey}}'],
handler: ({ unnamedArgs: [name, key], normalize }) => {
const result = ctx.variables.global.get(name, { index: key });
return normalize(result);
},
});
}
+33 -45
View File
@@ -189,21 +189,7 @@ class MacroCstWalker {
// Check for closing block flag
const flagTokens = /** @type {IToken[]} */ (children.flags || []);
let isClosing = flagTokens.some(token => token.image === MacroFlagType.CLOSING_BLOCK);
// Special case for the comment macro (//):
// The lexer always greedily tokenizes '//' before a single '/', so {{///}} is parsed as
// {{// /}} (comment with arg '/') rather than {{/ //}} (closing block for //).
// We detect this by checking if the '//' macro's positionally-first argument token starts with '/'.
if (!isClosing && name === '//') {
const firstArgNode = /** @type {CstNode?} */ ((argumentNodes || [])[0]);
if (firstArgNode) {
const firstToken = this.#getFirstTokenInNode(firstArgNode);
if (firstToken?.image?.startsWith('/')) {
isClosing = true;
}
}
}
const isClosing = flagTokens.some(token => token.image === MacroFlagType.CLOSING_BLOCK);
return {
name,
@@ -241,7 +227,7 @@ class MacroCstWalker {
for (const item of items) {
if (item.type !== 'macro') continue;
const info = this.extractMacroInfo(item.node);
const info = this.#extractMacroInfo(item.node);
if (!info) continue;
if (info.isClosing) {
@@ -1112,34 +1098,6 @@ class MacroCstWalker {
return !!value && typeof value === 'object' && 'name' in value && 'children' in value;
}
/**
* Returns the positionally-first leaf token (by startOffset) across all children of a CST node.
* Chevrotain groups tokens by type in the children object, so we must scan all type arrays
* and pick the token with the smallest startOffset rather than assuming any one array is ordered first.
*
* @param {CstNode} node
* @returns {IToken|null}
*/
#getFirstTokenInNode(node) {
const children = node?.children || {};
/** @type {IToken|null} */
let first = null;
for (const key of Object.keys(children)) {
for (const element of children[key] || []) {
// Skip CST nodes (nested rules) — we only want leaf tokens
if (this.#isCstNode(element)) continue;
const token = /** @type {IToken} */ (element);
if (typeof token.startOffset !== 'number' || isNaN(token.startOffset)) continue;
if (first === null || token.startOffset < first.startOffset) {
first = token;
}
}
}
return first;
}
/**
* Evaluates scoped content between an opening and closing macro tag.
* This resolves any nested macros within the scoped content.
@@ -1188,7 +1146,7 @@ class MacroCstWalker {
const item = items[i];
if (item.type !== 'macro') continue;
const info = this.extractMacroInfo(item.node);
const info = this.#extractMacroInfo(item.node);
if (!info) continue;
macroInfos.push({
@@ -1296,6 +1254,36 @@ class MacroCstWalker {
return items.filter((_, index) => !itemsToRemove.has(index));
}
/**
* Extracts macro name and closing flag status from a macro node.
*
* @param {CstNode} macroNode
* @returns {{ name: string, isClosing: boolean } | null}
*/
#extractMacroInfo(macroNode) {
const children = macroNode.children || {};
// Check if this is a variable expression - they can't be scoped
const variableExprNode = (children.variableExpr || [])[0];
if (variableExprNode) {
return null; // Variable expressions don't support scoped content
}
// Regular macro - get info from macroBody
const macroBodyNode = /** @type {CstNode?} */ ((children.macroBody || [])[0]);
const bodyChildren = macroBodyNode?.children || {};
const identifierTokens = /** @type {IToken[]} */ (bodyChildren['Macro.identifier'] || []);
const name = identifierTokens[0]?.image || '';
if (!name) return null;
// Check for closing block flag (inside macroBody)
const flagTokens = /** @type {IToken[]} */ (children.flags || []);
const isClosing = flagTokens.some(token => token.image === MacroFlagType.CLOSING_BLOCK);
return { name, isClosing };
}
/**
* Checks if a macro can accept scoped content as an additional argument.
+2 -7
View File
@@ -214,16 +214,11 @@ const Def = {
// Macro args allow nested macros
enter(Tokens.Macro.Start, modes.macro_def),
// PIPE/FILTER FEATURE DISABLED: Lines below commented out until pipe/filter feature is fully implemented.
// Currently, having these active breaks macros that use | as a regular character in argument values (e.g., {{setvar::foo::|bar}})
// See: https://github.com/SillyTavern/SillyTavern/issues/5618
// TODO: Re-enable when filter flag (>) logic is properly implemented to conditionally enable pipe parsing
// We allow escaped pipes to not start output modifiers. We need to capture this first, before the pipe
// using(Tokens.Filter.EscapedPipe),
using(Tokens.Filter.EscapedPipe),
// If at any place during args writing there is a pipe, we lex it as an output identifier, and then continue with lex its args
// enter(Tokens.Filter.Pipe, modes.macro_filter_modifer),
enter(Tokens.Filter.Pipe, modes.macro_filter_modifer),
using(Tokens.Args.DoubleColon),
using(Tokens.Args.Colon),
-259
View File
@@ -1,259 +0,0 @@
import { messageFormatting } from '../script.js';
/**
* Pipeline stages at which extension hooks may run.
* All stages occur **before** DOMPurify sanitization so output is always safe.
*
* - `BEFORE_REGEX` – Raw message text, after prompt-bias stripping but before
* custom regex rules are applied. Suitable for transforms
* that should be invisible to regex rules.
* - `AFTER_REGEX` – After custom regex rules, before Markdown conversion.
* The text is still plain Markdown at this point.
* - `AFTER_MARKDOWN` – After Markdown-to-HTML conversion (showdown), before
* DOMPurify. The value is an HTML string. This is the
* **default** stage and the most common insertion point
* for extensions that want to annotate rendered HTML (e.g.
* adding ruby tags, tooltips, highlights).
*
* > There is intentionally no post-sanitize stage.
* > All hooks run before DOMPurify so their output is always sanitized along
* > with the rest of the message. If your hook inserts HTML, make sure it is
* > safe to pass through DOMPurify (i.e. avoid `<script>` tags and inline
* > event handlers — they will be stripped anyway, but it is still bad
* > practice to produce them).
*
* @enum {string}
*/
export const formatting_stage = {
BEFORE_REGEX: 'beforeRegex',
AFTER_REGEX: 'afterRegex',
AFTER_MARKDOWN: 'afterMarkdown',
};
/**
* @typedef {formatting_stage[keyof formatting_stage]} MessageFormattingStage
*/
/**
* Message metadata supplied by {@link messageFormatting} to {@link MessageFormatter#runStage}.
* Does not include `stage` — that is injected by `runStage` itself.
*
* @typedef {Object} MessageFormattingBase
* @property {string} characterName - Character name associated with the message.
* @property {boolean} isSystem - Whether the message is a system message.
* @property {boolean} isUser - Whether the message was sent by the user.
* @property {number} messageId - Index of the message in the chat array, or -1 for transient messages (e.g. streaming previews).
* @property {boolean} isReasoning - Whether the message is reasoning/thinking output.
*/
/**
* Immutable context object passed to every formatting hook.
* Built from {@link MessageFormattingBase} with `stage` added and the whole
* object frozen by {@link MessageFormatter#runStage}.
*
* @typedef {Readonly<MessageFormattingBase & { stage: MessageFormattingStage }>} MessageFormattingContext
*/
/**
* A formatting hook function.
* Receives the current message text (plain Markdown or HTML, depending on
* the stage) and an immutable context object. Must return the (possibly
* modified) message text **synchronously** as a `string`. Passing an async
* function to {@link MessageFormatter#addHook} will throw a `TypeError` at
* registration time. If a hook returns a non-string at runtime, a console
* warning is emitted and the return value is ignored (the pipeline continues
* with the previous text unchanged).
*
* @callback MessageFormattingHook
* @param {string} mes - Current message text at this pipeline stage.
* @param {MessageFormattingContext} ctx - Immutable metadata about the message.
* @returns {string} The (possibly transformed) message text.
*/
/**
* Options accepted by {@link MessageFormatter#addHook}.
*
* @typedef {Object} AddHookOptions
* @property {hook_order|number} [order=hook_order.NORMAL] - Numeric priority within the stage.
* Lower numbers run first. Use the exported {@link hook_order} constants for readable values.
*/
/**
* Ordering buckets for formatting hooks.
* Use these when calling {@link MessageFormatter#addHook} to express
* intent rather than bare numbers.
*
* @enum {number}
*/
export const hook_order = {
EARLIEST: 0,
EARLY: 10,
NORMAL: 50,
LATE: 90,
LATEST: 100,
};
/** @type {MessageFormatter} */
let instance;
/**
* Singleton instance of {@link MessageFormatter}.
* Exported under the class name so callers can write
* `import { MessageFormatter } from './message-formatter.js'`
* and use it directly.
*
* @type {MessageFormatter}
*/
export { instance as MessageFormatter };
/**
* Manages the message-formatting pipeline and exposes registration points
* for extensions that need to transform message text before it reaches the
* DOM.
*
* Extensions should obtain the singleton via `getContext().messageFormatter`
* and call {@link MessageFormatter#addHook} once during their init phase.
*
* @example
* // In your extension's init function:
* const { messageFormatter } = getContext();
* messageFormatter.addHook((mes, ctx) => {
* if (ctx.isUser) return mes;
* return addFurigana(mes);
* });
*
* // With an explicit stage and order (using the enum accessors on the singleton):
* const { messageFormatter } = getContext();
* messageFormatter.addHook((mes, ctx) => transform(mes), {
* stage: messageFormatter.stage.AFTER_REGEX,
* order: messageFormatter.order.EARLY,
* });
*/
class MessageFormatter {
/** @type {MessageFormatter} */
static #instance;
/** @returns {MessageFormatter} */
static get instance() {
return MessageFormatter.#instance ?? (MessageFormatter.#instance = new MessageFormatter());
}
/**
* Internal storage: one sorted bucket per stage.
*
* @type {Map<MessageFormattingStage, { fn: MessageFormattingHook, order: number }[]>}
*/
#hooks = new Map();
/**
* Exposes {@link formatting_stage} on the instance so extensions can
* access stage constants without a separate import.
* @type {typeof formatting_stage}
* @readonly
*/
stage = formatting_stage;
/**
* Exposes {@link hook_order} on the instance so extensions can
* access order constants without a separate import.
* @type {typeof hook_order}
* @readonly
*/
order = hook_order;
constructor() {
this.#hooks.set(formatting_stage.BEFORE_REGEX, []);
this.#hooks.set(formatting_stage.AFTER_REGEX, []);
this.#hooks.set(formatting_stage.AFTER_MARKDOWN, []);
}
/**
* Registers a hook function to run at a specific pipeline stage.
*
* Should be called once during the extension's init/setup phase.
* Hooks are applied in ascending `order` within each stage.
*
* @param {MessageFormattingHook} fn - The hook function.
* @param {AddHookOptions & { stage?: MessageFormattingStage }} [options={}]
* Options object. `stage` defaults to `'afterMarkdown'`; `order` defaults to `50`.
* @returns {void}
*
* @throws {TypeError} If `fn` is not a function or is an async function.
* @throws {RangeError} If `stage` is not a known {@link formatting_stage} value.
*/
addHook(fn, { stage = formatting_stage.AFTER_MARKDOWN, order = hook_order.NORMAL } = {}) {
if (typeof fn !== 'function') throw new TypeError('MessageFormatter: hook must be a function');
if (fn.constructor?.name === 'AsyncFunction') throw new TypeError(`MessageFormatter: hook registered for stage '${stage}' must be synchronous — async functions are not supported`);
if (!this.#hooks.has(stage)) throw new RangeError(`MessageFormatter: unknown stage '${stage}'`);
this.#hooks.get(stage).push({ fn, order });
}
/**
* Runs all hooks registered for the given stage in order.
* Called internally by {@link messageFormatting} at each pipeline point.
* Extensions do not need to call this directly.
*
* @param {MessageFormattingStage} stage - The pipeline stage to execute.
* @param {string} mes - Current message text.
* @param {MessageFormattingBase} base - Message metadata. `stage` is injected automatically.
* @returns {string} The message text after all hooks have been applied.
*/
runStage(stage, mes, base) {
const bucket = this.#hooks.get(stage);
if (!bucket?.length) return mes;
const ctx = Object.freeze({ ...base, stage });
const sorted = bucket.slice().sort((a, b) => a.order - b.order);
for (const { fn } of sorted) {
try {
const result = fn(mes, ctx);
if (typeof result !== 'string') {
console.warn(`[MessageFormatter] Hook at stage '${stage}' returned ${/** @type {unknown} */ (result) instanceof Promise ? 'a Promise (hook may be async)' : typeof result} instead of a string. The hook's return value has been ignored.`);
} else {
mes = result;
}
} catch (e) {
console.error(`[MessageFormatter] Hook error at stage '${stage}':`, e);
}
}
return mes;
}
/**
* Formats a message using the full pipeline (including all registered
* hooks). This is a convenience shim over the top-level
* {@link messageFormatting} function and accepts the same arguments.
*
* Extensions that already import `getContext()` can use this instead of
* importing `messageFormatting` directly from `script.js`.
*
* The pipeline is, in order:
* 1. Prompt-bias stripping (message 0 only)
* 2. Comment / hidden-message normalisation
* 3. `beforeRegex` extension hooks (see {@link MessageFormatter})
* 4. Custom regex rules (`getRegexedString`)
* 5. `afterRegex` extension hooks
* 6. Markdown auto-fix (`fixMarkdown`)
* 7. HTML tag encoding (`encode_tags`)
* 8. Showdown Markdown → HTML conversion
* 9. `afterMarkdown` extension hooks
* 10. Name-prefix stripping (`allow_name2_display`)
* 11. DOMPurify sanitization
*
* All extension hooks run **before** DOMPurify (steps 3, 5, 9) so their
* output is always sanitised.
*
* @param {string} mes - Raw message text.
* @param {string} characterName - Character name.
* @param {boolean} isSystem - Whether this is a system message.
* @param {boolean} isUser - Whether this was sent by the user.
* @param {number} messageId - Message index in the chat array.
* @param {Partial<import('dompurify').Config>} [sanitizerOverrides={}] - DOMPurify option overrides.
* @param {boolean} [isReasoning=false] - Whether this is reasoning output.
* @returns {string} Formatted HTML string ready for DOM insertion.
*/
format(mes, characterName, isSystem, isUser, messageId, sanitizerOverrides = {}, isReasoning = false) {
return messageFormatting(mes, characterName, isSystem, isUser, messageId, sanitizerOverrides, isReasoning);
}
}
instance = MessageFormatter.instance;
+1 -24
View File
@@ -267,11 +267,6 @@ export const ZAI_ENDPOINT = {
CODING: 'coding',
};
export const POLLINATIONS_ENDPOINT = {
AUTHENTICATED: 'authenticated',
ANONYMOUS: 'anonymous',
};
export const SILICONFLOW_ENDPOINT = {
GLOBAL: 'global',
CN: 'cn',
@@ -340,7 +335,6 @@ export const settingsToUpdate = {
aimlapi_model: ['#model_aimlapi_select', 'aimlapi_model', false, true],
xai_model: ['#model_xai_select', 'xai_model', false, true],
pollinations_model: ['#model_pollinations_select', 'pollinations_model', false, true],
pollinations_endpoint: ['#pollinations_endpoint', 'pollinations_endpoint', false, true],
moonshot_model: ['#model_moonshot_select', 'moonshot_model', false, true],
fireworks_model: ['#model_fireworks_select', 'fireworks_model', false, true],
cometapi_model: ['#model_cometapi_select', 'cometapi_model', false, true],
@@ -457,7 +451,6 @@ const default_settings = {
aimlapi_model: 'chatgpt-4o-latest',
xai_model: 'grok-3-beta',
pollinations_model: 'openai',
pollinations_endpoint: POLLINATIONS_ENDPOINT.AUTHENTICATED,
cometapi_model: 'gpt-4o',
moonshot_model: 'kimi-latest',
fireworks_model: 'accounts/fireworks/models/kimi-k2-instruct',
@@ -2940,10 +2933,6 @@ export async function createGenerationParameters(settings, model, type, messages
delete generate_data.frequency_penalty;
}
if (settings.chat_completion_source === chat_completion_sources.POLLINATIONS) {
generate_data.pollinations_endpoint = settings.pollinations_endpoint || POLLINATIONS_ENDPOINT.AUTHENTICATED;
}
if (settings.chat_completion_source === chat_completion_sources.SILICONFLOW) {
generate_data.siliconflow_endpoint = settings.siliconflow_endpoint || SILICONFLOW_ENDPOINT.GLOBAL;
}
@@ -4439,10 +4428,6 @@ async function getStatusOpen() {
data.workers_ai_account_id = oai_settings.workers_ai_account_id;
}
if (oai_settings.chat_completion_source === chat_completion_sources.POLLINATIONS) {
data.pollinations_endpoint = oai_settings.pollinations_endpoint || POLLINATIONS_ENDPOINT.AUTHENTICATED;
}
const canBypass = (oai_settings.chat_completion_source === chat_completion_sources.OPENAI && oai_settings.bypass_status_check) || oai_settings.chat_completion_source === chat_completion_sources.CUSTOM;
if (canBypass) {
setOnlineStatus(t`Status check bypassed`);
@@ -5152,7 +5137,6 @@ function getZaiMaxContext(model, isUnlocked) {
}
const contextMap = {
'glm-5.2': max_1mil,
'glm-5.1': max_200k,
'glm-5-turbo': max_200k,
'glm-5v-turbo': max_200k,
@@ -5950,7 +5934,7 @@ async function onConnectButtonClick(e) {
[chat_completion_sources.AZURE_OPENAI]: { key: SECRET_KEYS.AZURE_OPENAI, selector: '#api_key_azure_openai', proxy: false },
[chat_completion_sources.ZAI]: { key: SECRET_KEYS.ZAI, selector: '#api_key_zai', proxy: true },
[chat_completion_sources.CHUTES]: { key: SECRET_KEYS.CHUTES, selector: '#api_key_chutes', proxy: false },
[chat_completion_sources.POLLINATIONS]: { key: SECRET_KEYS.POLLINATIONS, selector: '#api_key_pollinations', proxy: false, keyless: oai_settings.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS },
[chat_completion_sources.POLLINATIONS]: { key: SECRET_KEYS.POLLINATIONS, selector: '#api_key_pollinations', proxy: false },
[chat_completion_sources.WORKERS_AI]: { key: SECRET_KEYS.WORKERS_AI, selector: '#api_key_workers_ai', proxy: false },
[chat_completion_sources.MINIMAX]: { key: SECRET_KEYS.MINIMAX, selector: '#api_key_minimax', proxy: false },
};
@@ -6033,7 +6017,6 @@ function toggleChatCompletionForms() {
} else if (oai_settings.chat_completion_source == chat_completion_sources.XAI) {
$('#model_xai_select').trigger('change');
} else if (oai_settings.chat_completion_source == chat_completion_sources.POLLINATIONS) {
$('#pollinations_key_section').toggle(oai_settings.pollinations_endpoint === POLLINATIONS_ENDPOINT.AUTHENTICATED);
$('#model_pollinations_select').trigger('change');
} else if (oai_settings.chat_completion_source == chat_completion_sources.MOONSHOT) {
$('#model_moonshot_select').trigger('change');
@@ -7210,12 +7193,6 @@ export function initOpenAI() {
oai_settings.zai_endpoint = String($(this).val());
saveSettingsDebounced();
});
$('#pollinations_endpoint').on('input', function () {
oai_settings.pollinations_endpoint = String($(this).val());
$('#pollinations_key_section').toggle(oai_settings.pollinations_endpoint === POLLINATIONS_ENDPOINT.AUTHENTICATED);
reconnectOpenAi();
saveSettingsDebounced();
});
$('#siliconflow_endpoint').on('input', function () {
oai_settings.siliconflow_endpoint = String($(this).val());
saveSettingsDebounced();
-5
View File
@@ -85,7 +85,6 @@ export const POPUP_RESULT = {
* @property {number?} [max] - The maximum value for number inputs
* @property {number?} [step] - The step value for number inputs
* @property {boolean?} [disabled=false] - Whether the input should be disabled
* @property {boolean?} [autoFocus=false] - Whether this input should be auto-focused when the popup opens
*/
/**
@@ -337,7 +336,6 @@ export class Popup {
inputElement.id = input.id;
inputElement.checked = Boolean(input.defaultState ?? false);
inputElement.disabled = Boolean(input.disabled ?? false);
if (input.autoFocus) { inputElement.setAttribute('autofocus', ''); inputElement.tabIndex = 0; }
label.appendChild(inputElement);
const labelText = document.createElement('span');
labelText.innerText = input.label;
@@ -364,7 +362,6 @@ export class Popup {
inputElement.value = String(input.defaultState ?? '');
inputElement.placeholder = input.tooltip ?? '';
inputElement.disabled = Boolean(input.disabled ?? false);
if (input.autoFocus) { inputElement.setAttribute('autofocus', ''); inputElement.tabIndex = 0; }
setTitleFromTooltip(inputElement, input.tooltip);
const labelText = document.createElement('span');
@@ -387,7 +384,6 @@ export class Popup {
inputElement.rows = input.rows ?? 1;
inputElement.placeholder = input.tooltip ?? '';
inputElement.disabled = Boolean(input.disabled ?? false);
if (input.autoFocus) { inputElement.setAttribute('autofocus', ''); inputElement.tabIndex = 0; }
setTitleFromTooltip(inputElement, input.tooltip);
const labelText = document.createElement('span');
@@ -413,7 +409,6 @@ export class Popup {
inputElement.max = String(input.max ?? '');
inputElement.step = String(input.step ?? '');
inputElement.disabled = Boolean(input.disabled ?? false);
if (input.autoFocus) { inputElement.setAttribute('autofocus', ''); inputElement.tabIndex = 0; }
setTitleFromTooltip(inputElement, input.tooltip);
inputElement.addEventListener('change', () => {
+237
View File
@@ -0,0 +1,237 @@
/**
* Showdown emphasis extensions and pre-processing utilities.
*
* Contains:
* - markdownUnderscoreExt: Showdown output extension for _word_ emphasis
* - fixNestedEmphasis: Pre-processor to convert nested same-delimiter emphasis to bold
*/
// ===== Underscore Emphasis Extension =====
/**
* Showdown extension that replaces words surrounded by singular underscores with <em> tags.
* @returns {import('showdown').ShowdownExtension[]} An array of Showdown extensions
*/
export const markdownUnderscoreExt = () => {
try {
if (!canUseNegativeLookbehind()) {
console.log('Showdown-underscore extension: Negative lookbehind not supported. Skipping.');
return [];
}
return [{
type: 'output',
regex: new RegExp('(<code(?:\\s+[^>]*)?>[\\s\\S]*?<\\/code>|<style(?:\\s+[^>]*)?>[\\s\\S]*?<\\/style>)|\\b(?<!_)_(?!_)(.*?)(?<!_)_(?!_)\\b', 'gi'),
replace: function (match, tagContent, italicContent) {
if (tagContent) {
// If it's inside <code> or <style> tags, return unchanged
return match;
} else if (italicContent) {
// If it's an italic group, apply the replacement
return '<em>' + italicContent + '</em>';
}
// If none of the conditions are met, return the original match
return match;
},
}];
} catch (e) {
console.error('Error in Showdown-underscore extension:', e);
return [];
}
};
function canUseNegativeLookbehind() {
try {
new RegExp('(?<!_)');
return true;
} catch (e) {
return false;
}
}
// ===== Nested Emphasis Pre-Processor =====
/**
* Fixes nested emphasis that showdown cannot handle.
*
* Showdown cannot handle nested emphasis with the same delimiter character.
* This function handles two cases:
* 1. `*outer *inner* outer*` — inner `*` promoted to `**` (renders as bold-inside-italic)
* 2. `**outer **inner** outer**` — inner `**` stripped (bold-inside-bold is redundant)
*
* Uses CommonMark-like flanking rules and stack-based pairing to detect nesting.
*
* @param {string} text The message text to process
* @returns {string} The processed text with nested emphasis fixed
* @example
* fixNestedEmphasis("*She sighs. *I can't do this,* she says.*")
* // → "*She sighs. **I can't do this,** she says.*"
* fixNestedEmphasis("**This is **bold**, isn't it?**")
* // → "**This is bold, isn't it?**"
*/
export function fixNestedEmphasis(text) {
// Temporarily replace code blocks and inline code to protect them from modification
const codeBlocks = [];
let processed = text.replace(/```[\s\S]*?```|~~~[\s\S]*?~~~|``[\s\S]*?``|`[^`\n]*`/g, (match) => {
codeBlocks.push(match);
return `\x00CODE_BLOCK_${codeBlocks.length - 1}\x00`;
});
processed = processed.split('\n').map(line => {
// Fix nested ** inside ** first (strip inner), then nested * inside * (promote inner)
line = fixNestedBoldLine(line);
line = fixNestedItalicLine(line);
return line;
}).join('\n');
// Restore code blocks
processed = processed.replace(/\x00CODE_BLOCK_(\d+)\x00/g, (_, idx) => codeBlocks[parseInt(idx)]);
return processed;
}
/**
* Finds nested `**...**` pairs inside other `**...**` pairs and strips the inner delimiters.
* Bold inside bold is redundant — like GitHub, the whole block renders as bold.
* @param {string} line A single line of text
* @returns {string} The processed line
*/
function fixNestedBoldLine(line) {
// Find all ** positions (exactly two consecutive asterisks, not part of ***)
const positions = [];
for (let i = 0; i < line.length - 1; i++) {
if (line[i] === '*' && line[i + 1] === '*') {
const before = i > 0 ? line[i - 1] : '';
const after = i + 2 < line.length ? line[i + 2] : '';
// Must be exactly ** (not *** or more)
if (before !== '*' && after !== '*') {
positions.push(i);
i++; // skip the second *
}
}
}
// Need at least 4 ** delimiters for nesting to be possible
if (positions.length < 4) return line;
// Stack-based pairing with flanking rules
const stack = [];
const pairs = [];
for (let i = 0; i < positions.length; i++) {
const pos = positions[i];
// For **, check the char before the first * and after the second *
const charBefore = pos > 0 ? line[pos - 1] : '';
const charAfter = pos + 2 < line.length ? line[pos + 2] : '';
const canClose = charBefore !== '' && !/\s/.test(charBefore);
const canOpen = charAfter !== '' && !/\s/.test(charAfter);
if (canClose && stack.length > 0) {
const openIdx = stack.pop();
pairs.push([openIdx, i]);
} else if (canOpen) {
stack.push(i);
}
}
// Determine which pairs are nested inside others
const nestedPositions = new Set();
for (let i = 0; i < pairs.length; i++) {
const [outerOpen, outerClose] = [positions[pairs[i][0]], positions[pairs[i][1]]];
for (let j = 0; j < pairs.length; j++) {
if (i === j) continue;
const [innerOpen, innerClose] = [positions[pairs[j][0]], positions[pairs[j][1]]];
if (innerOpen > outerOpen && innerClose < outerClose) {
// Inner pair is nested — mark both its ** delimiters for removal
nestedPositions.add(innerOpen);
nestedPositions.add(innerClose);
}
}
}
if (nestedPositions.size === 0) return line;
// Build result, skipping the nested ** delimiters
let result = '';
for (let i = 0; i < line.length; i++) {
if (nestedPositions.has(i)) {
i++; // skip both characters of **
continue;
}
result += line[i];
}
return result;
}
/**
* Finds nested `*...*` pairs inside other `*...*` pairs and promotes them to `**...**`.
* This converts inner emphasis to bold so showdown renders bold-inside-italic.
* @param {string} line A single line of text
* @returns {string} The processed line
*/
function fixNestedItalicLine(line) {
// Find all single-* positions (not part of ** or ***)
const positions = [];
for (let i = 0; i < line.length; i++) {
if (line[i] === '*') {
const before = i > 0 ? line[i - 1] : '';
const after = i < line.length - 1 ? line[i + 1] : '';
if (before !== '*' && after !== '*') {
positions.push(i);
}
}
}
// Need at least 4 single asterisks for nesting to be possible
if (positions.length < 4) return line;
// Use stack-based pairing with CommonMark-like flanking rules:
// - An asterisk can OPEN emphasis if followed by a non-whitespace character
// - An asterisk can CLOSE emphasis if preceded by a non-whitespace character
const stack = [];
const pairs = [];
for (let i = 0; i < positions.length; i++) {
const pos = positions[i];
const charBefore = pos > 0 ? line[pos - 1] : '';
const charAfter = pos < line.length - 1 ? line[pos + 1] : '';
const canClose = charBefore !== '' && !/\s/.test(charBefore);
const canOpen = charAfter !== '' && !/\s/.test(charAfter);
// Prefer closing over opening (matches CommonMark behavior)
if (canClose && stack.length > 0) {
const openIdx = stack.pop();
pairs.push([openIdx, i]);
} else if (canOpen) {
stack.push(i);
}
}
// Determine nesting: a pair is nested if fully contained within another pair
const nestedIndices = new Set();
for (let i = 0; i < pairs.length; i++) {
const [outerOpen, outerClose] = [positions[pairs[i][0]], positions[pairs[i][1]]];
for (let j = 0; j < pairs.length; j++) {
if (i === j) continue;
const [innerOpen, innerClose] = [positions[pairs[j][0]], positions[pairs[j][1]]];
if (innerOpen > outerOpen && innerClose < outerClose) {
nestedIndices.add(innerOpen);
nestedIndices.add(innerClose);
}
}
}
if (nestedIndices.size === 0) return line;
// Build result with doubled asterisks at nested positions
let result = '';
for (let i = 0; i < line.length; i++) {
result += line[i];
if (nestedIndices.has(i)) {
result += '*';
}
}
return result;
}
+2 -29
View File
@@ -70,7 +70,7 @@ import { hideChatMessageRange } from './chats.js';
import { getContext, saveMetadataDebounced } from './extensions.js';
import { getRegexedString, regex_placement } from './extensions/regex/engine.js';
import { findGroupMemberId, groups, is_group_generating, openGroupById, regenerateGroup, resetSelectedGroup, saveGroupChat, selected_group, getGroupMembers } from './group-chats.js';
import { chat_completion_sources, MINIMAX_ENDPOINT, oai_settings, POLLINATIONS_ENDPOINT, promptManager, SILICONFLOW_ENDPOINT, ZAI_ENDPOINT } from './openai.js';
import { chat_completion_sources, MINIMAX_ENDPOINT, oai_settings, promptManager, SILICONFLOW_ENDPOINT, ZAI_ENDPOINT } from './openai.js';
import { user_avatar } from './personas.js';
import { addEphemeralStoppingString, chat_styles, context_presets, flushEphemeralStoppingStrings, playMessageSound, power_user } from './power-user.js';
import { SERVER_INPUTS, textgen_types, textgenerationwebui_settings } from './textgen-settings.js';
@@ -3135,7 +3135,6 @@ export function initDefaultSlashCommands() {
new SlashCommandEnumValue('vertexai', 'Google Vertex AI', enumTypes.getBasedOnIndex(UNIQUE_APIS.findIndex(x => x === 'vertexai')), 'V'),
new SlashCommandEnumValue('siliconflow', 'SiliconFlow', enumTypes.getBasedOnIndex(UNIQUE_APIS.findIndex(x => x === 'siliconflow')), 'S'),
new SlashCommandEnumValue('minimax', 'MiniMax', enumTypes.getBasedOnIndex(UNIQUE_APIS.findIndex(x => x === 'minimax')), 'M'),
new SlashCommandEnumValue('pollinations', 'Pollinations', enumTypes.getBasedOnIndex(UNIQUE_APIS.findIndex(x => x === 'pollinations')), 'P'),
new SlashCommandEnumValue('kobold', 'KoboldAI Classic', enumTypes.getBasedOnIndex(UNIQUE_APIS.findIndex(x => x === 'kobold')), 'K'),
...Object.values(textgen_types).filter(api => Object.keys(SERVER_INPUTS).includes(api)).map(api => new SlashCommandEnumValue(api, null, enumTypes.getBasedOnIndex(UNIQUE_APIS.findIndex(x => x === 'textgenerationwebui')), 'T')),
],
@@ -3169,7 +3168,7 @@ export function initDefaultSlashCommands() {
${t`If a manual API is provided to <b>set</b> the URL, make sure to set <code>connect=false</code>, as auto-connect only works for the currently selected API, or consider switching to it with <code>/api</code> first.`}
</div>
<div>
${t`This slash command works for most of the Text Completion sources, KoboldAI Classic, and also Custom OpenAI compatible, Z.AI, SiliconFlow, MiniMax, Pollinations, and Google Vertex AI for the Chat Completion sources. If unsure which APIs are supported, check the auto-completion of the optional <code>api</code> argument of this command.`}
${t`This slash command works for most of the Text Completion sources, KoboldAI Classic, and also Custom OpenAI compatible, Z.AI, SiliconFlow, MiniMax, and Google Vertex AI for the Chat Completion sources. If unsure which APIs are supported, check the auto-completion of the optional <code>api</code> argument of this command.`}
</div>
`,
}));
@@ -6687,32 +6686,6 @@ async function setApiUrlCallback({ api = null, connect = 'true', quiet = 'false'
return oai_settings.vertexai_region || defaultRegion;
}
const isCurrentlyPollinations = main_api === 'openai' && oai_settings.chat_completion_source === chat_completion_sources.POLLINATIONS;
if (api === chat_completion_sources.POLLINATIONS || (!api && isCurrentlyPollinations)) {
if (!url) {
return oai_settings.pollinations_endpoint || POLLINATIONS_ENDPOINT.AUTHENTICATED;
}
const permittedValues = Object.values(POLLINATIONS_ENDPOINT);
if (!permittedValues.includes(url)) {
!isQuiet && toastr.warning(t`Valid options are: ${permittedValues.join(', ')}`, t`Pollinations endpoint '${url}' is not a valid option.`);
return '';
}
if (!isCurrentlyPollinations && autoConnect) {
toastr.warning(t`Pollinations API is not the currently selected API, so we cannot do an auto-connect. Consider switching to it via /api beforehand.`);
return '';
}
$('#pollinations_endpoint').val(url).trigger('input');
if (autoConnect) {
$('#api_button_openai').trigger('click');
}
return oai_settings.pollinations_endpoint || POLLINATIONS_ENDPOINT.AUTHENTICATED;
}
// Special handling for Kobold Classic API
const isCurrentlyKoboldClassic = main_api === 'kobold';
if (api === 'kobold' || (!api && isCurrentlyKoboldClassic)) {
-2
View File
@@ -110,7 +110,6 @@ import { ConnectionManagerRequestService } from './extensions/shared.js';
import { updateReasoningUI, parseReasoningFromString, getReasoningTemplateByName } from './reasoning.js';
import { IGNORE_SYMBOL } from './constants.js';
import { macros } from './macros/macro-system.js';
import { MessageFormatter } from './message-formatter.js';
export function getContext() {
return {
@@ -243,7 +242,6 @@ export function getContext() {
scrollChatToBottom,
scrollOnMediaLoad,
macros,
messageFormatter: MessageFormatter,
loader,
swipe: {
left: swipe_left,
+1 -1
View File
@@ -14,6 +14,6 @@
</div>
<div class="resetCodeBlock">
<label data-i18n="Reset Code:" for="password">Reset Code:</label>
<input type="text" name="code" class="text_pole" placeholder="XXXXXX">
<input type="text" name="code" class="text_pole" placeholder="XXXX">
</div>
</form>
-8
View File
@@ -258,10 +258,6 @@ const NANOGPT_PROVIDERS = [
'id': 'neuralwatt',
'label': 'Neuralwatt',
},
{
'id': 'tensorix',
'label': 'Tensorix',
},
{
'id': 'nextbit',
'label': 'NextBit',
@@ -314,10 +310,6 @@ const NANOGPT_PROVIDERS = [
'id': 'wandb',
'label': 'Weights & Biases',
},
{
'id': 'xiaomi',
'label': 'Xiaomi',
},
{
'id': 'zai',
'label': 'Z.AI',
+12 -34
View File
@@ -7,7 +7,7 @@ import {
} from '../lib.js';
import { getContext } from './extensions.js';
import { animation_duration, characters, getRequestHeaders, processDroppedFiles, this_chid, user_avatar } from '../script.js';
import { characters, getRequestHeaders, processDroppedFiles, this_chid, user_avatar } from '../script.js';
import { isMobile } from './RossAscends-mods.js';
import { collapseNewlines, power_user } from './power-user.js';
import { debounce_timeout } from './constants.js';
@@ -2786,54 +2786,32 @@ export function arraysEqual(a, b) {
* @param {string | HTMLElement} target - The CSS selector or the HTML element of the information block
* @param {string | HTMLElement?} content - The message to display inside the information block (supports HTML) or an HTML element
* @param {'hint' | 'info' | 'warning' | 'error'} [type='info'] - The type of message, which determines the styling of the information block
* @param {object} [options={}] - Optional settings
* @param {boolean} [options.animate=true] - Whether to animate the block sliding in when first shown
*/
export function setInfoBlock(target, content, type = 'info', { animate = true } = {}) {
export function setInfoBlock(target, content, type = 'info') {
if (!content) {
clearInfoBlock(target);
return;
}
const infoBlock = typeof target === 'string' ? document.querySelector(target) : target;
if (!infoBlock) return;
const wasVisible = infoBlock.classList.contains('info-block');
if (!wasVisible && animate) {
$(infoBlock).hide();
}
infoBlock.className = `info-block ${type}`;
if (typeof content === 'string') {
infoBlock.innerHTML = content;
} else {
infoBlock.innerHTML = '';
infoBlock.appendChild(content);
}
if (!wasVisible && animate) {
$(infoBlock).slideDown(animation_duration * 1.5);
if (infoBlock) {
infoBlock.className = `info-block ${type}`;
if (typeof content === 'string') {
infoBlock.innerHTML = content;
} else {
infoBlock.innerHTML = '';
infoBlock.appendChild(content);
}
}
}
/**
* Clears the content and style of an information block.
* @param {string | HTMLElement} target - The CSS selector or the HTML element of the information block
* @param {object} [options={}] - Optional settings
* @param {boolean} [options.animate=true] - Whether to animate the block fading out before clearing
*/
export function clearInfoBlock(target, { animate = true } = {}) {
export function clearInfoBlock(target) {
const infoBlock = typeof target === 'string' ? document.querySelector(target) : target;
if (!infoBlock || !infoBlock.classList.contains('info-block')) return;
if (animate) {
$(infoBlock).slideUp(animation_duration * 1.5, () => {
infoBlock.className = '';
infoBlock.innerHTML = '';
$(infoBlock).css('display', '');
});
} else {
if (infoBlock && infoBlock.classList.contains('info-block')) {
infoBlock.className = '';
infoBlock.innerHTML = '';
}
+20 -100
View File
@@ -1,7 +1,7 @@
import { Fuse } from '../lib.js';
import { saveSettings, substituteParams, getRequestHeaders, chat_metadata, this_chid, characters, saveCharacterDebounced, menu_type, eventSource, event_types, getExtensionPromptByName, saveMetadata, getCurrentChatId, extension_prompt_roles, create_save, createOrEditCharacter, name1, getOneCharacter, select_selected_character } from '../script.js';
import { download, debounce, initScrollHeight, resetScrollHeight, parseJsonFile, extractDataFromPng, getFileBuffer, getCharaFilename, getSortableDelay, escapeRegex, PAGINATION_TEMPLATE, navigation_option, waitUntilCondition, isTrueBoolean, setValueByPath, flashHighlight, select2ModifyOptions, getSelect2OptionId, dynamicSelect2DataViaAjax, highlightRegex, select2ChoiceClickSubscribe, isFalseBoolean, getSanitizedFilename, checkOverwriteExistingData, getStringHash, parseStringArray, cancelDebounce, findChar, onlyUnique, equalsIgnoreCaseAndAccents, uuidv4, normalizeArray, getUniqueName, logSlashCommandWarn, addLongPressEvent, escapeHtml, setInfoBlock, clearInfoBlock } from './utils.js';
import { download, debounce, initScrollHeight, resetScrollHeight, parseJsonFile, extractDataFromPng, getFileBuffer, getCharaFilename, getSortableDelay, escapeRegex, PAGINATION_TEMPLATE, navigation_option, waitUntilCondition, isTrueBoolean, setValueByPath, flashHighlight, select2ModifyOptions, getSelect2OptionId, dynamicSelect2DataViaAjax, highlightRegex, select2ChoiceClickSubscribe, isFalseBoolean, getSanitizedFilename, checkOverwriteExistingData, getStringHash, parseStringArray, cancelDebounce, findChar, onlyUnique, equalsIgnoreCaseAndAccents, uuidv4, normalizeArray, getUniqueName, logSlashCommandWarn, addLongPressEvent, escapeHtml } from './utils.js';
import { extension_settings, getContext } from './extensions.js';
import { NOTE_MODULE_NAME, metadata_keys, shouldWIAddPrompt } from './authors-note.js';
import { isMobile } from './RossAscends-mods.js';
@@ -2495,125 +2495,45 @@ async function displayWorldEntries(name, data, navigation = navigation_option.no
$('#world_apply_current_sorting').off('click').on('click', async () => {
const entryCount = Object.keys(data.entries).length;
const moreThan100 = entryCount > 100;
const contentEl = document.createElement('div');
let content = '<span>' + t`Apply your current sorting to the "Order" field. The Order values will go down from the chosen number.` + '</span>';
if (moreThan100) {
content += '<div class="m-t-1"><i class="fa-solid fa-triangle-exclamation" style="color: #FFD43B;"></i> ' + t`More than 100 entries in this world. If you don't choose a number higher than that, the lower entries will default to 0.<br />(Usual default: 100)<br />Minimum: ${entryCount}` + '</div>';
}
const heading = document.createElement('h3');
heading.textContent = t`Apply Current Sorting`;
contentEl.appendChild(heading);
const description = document.createElement('span');
const descriptionText = document.createElement('p');
descriptionText.innerHTML = t`Assigns Order values to all entries based on their current sort position.`;
contentEl.appendChild(descriptionText);
const descriptionDetail = document.createElement('p');
descriptionDetail.innerHTML = t`Entries are ordered <b>descending</b> by default — the first entry in the list gets the highest value and will be inserted first into the prompt.`;
contentEl.appendChild(descriptionDetail);
const entryCountText = document.createElement('small');
entryCountText.textContent = t`(${entryCount} entries total)`;
contentEl.appendChild(entryCountText);
contentEl.appendChild(description);
const warningEl = document.createElement('div');
contentEl.appendChild(warningEl);
/** @type {(startInput: HTMLInputElement, stepInput: HTMLInputElement, ascendingInput: HTMLInputElement) => void} */
const updateWarning = (startInput, stepInput, ascendingInput) => {
const startVal = Number(startInput.value);
const stepVal = Number(stepInput.value);
const isAscending = ascendingInput.checked;
if (!isAscending && !isNaN(startVal) && !isNaN(stepVal) && startVal - (entryCount - 1) * stepVal < 0) {
setInfoBlock(warningEl, t`Some entries will be clamped to Order 0, causing collisions at the bottom. The last entry would reach ${startVal - (entryCount - 1) * stepVal} (${entryCount} entries, step ${stepVal}).`, 'warning');
} else {
clearInfoBlock(warningEl);
}
};
/** @type {import('./popup.js').CustomPopupInput[]} */
const customInputs = [
{
id: 'wi_sort_start',
label: t`Starting value`,
tooltip: t`The Order value assigned to the first entry. In descending mode, values count down from here; in ascending mode, values count up from here.` + ' ' + t`(${entryCount} entries total)`,
type: 'number',
defaultState: '100',
min: 0,
step: 1,
autoFocus: true,
},
{
id: 'wi_sort_step',
label: t`Step`,
tooltip: t`The gap between each Order value. For example, a step of 5 produces values like 100, 95, 90... (descending) or 0, 5, 10... (ascending).`,
type: 'number',
defaultState: '1',
min: 1,
step: 1,
},
{
id: 'wi_sort_ascending',
label: t`Ascending order`,
tooltip: t`When checked, Order values count upward from the starting value (first sorted entry gets the lowest Order). When unchecked, values count downward (first sorted entry gets the highest Order).`,
type: 'checkbox',
defaultState: false,
},
];
const popup = new Popup(contentEl, POPUP_TYPE.TEXT, null, {
okButton: t`Apply`,
cancelButton: t`Cancel`,
customInputs,
});
const startInput = /** @type {HTMLInputElement} */ (popup.dlg.querySelector('#wi_sort_start'));
const stepInput = /** @type {HTMLInputElement} */ (popup.dlg.querySelector('#wi_sort_step'));
const ascendingInput = /** @type {HTMLInputElement} */ (popup.dlg.querySelector('#wi_sort_ascending'));
startInput.addEventListener('input', () => updateWarning(startInput, stepInput, ascendingInput));
stepInput.addEventListener('input', () => updateWarning(startInput, stepInput, ascendingInput));
ascendingInput.addEventListener('change', () => updateWarning(startInput, stepInput, ascendingInput));
updateWarning(startInput, stepInput, ascendingInput);
const result = await popup.show();
if (result !== POPUP_RESULT.AFFIRMATIVE) return;
const start = Number(popup.inputResults.get('wi_sort_start') ?? '100');
const step = Number(popup.inputResults.get('wi_sort_step') ?? '1');
const ascending = Boolean(popup.inputResults.get('wi_sort_ascending'));
const result = await Popup.show.input(t`Apply Current Sorting`, content, '100', { okButton: t`Apply`, cancelButton: 'Cancel' });
if (!result) return;
const start = Number(result);
if (isNaN(start) || start < 0) {
toastr.error(t`Invalid starting value: ${start}`, t`Apply Current Sorting`);
toastr.error(t`Invalid number: ${result}`, t`Apply Current Sorting`);
return;
}
if (isNaN(step) || step < 1) {
toastr.error(t`Invalid step value: ${step}`, t`Apply Current Sorting`);
return;
}
if (!ascending && start < entryCount) {
toastr.warning(t`A starting value lower than the entry count has been chosen. All entries below that will default to 0.`, t`Apply Current Sorting`);
if (start < entryCount) {
toastr.warning(t`A number lower than the entry count has been chosen. All entries below that will default to 0.`, t`Apply Current Sorting`);
}
// We need to sort the entries here, as the data source isn't sorted
const entries = Object.values(data.entries);
sortWorldInfoEntries(entries);
let updated = 0;
entries.forEach((entry, index) => {
const newOrder = ascending
? start + index * step
: Math.max(start - index * step, 0);
if (entry.order === newOrder) return;
let updated = 0, current = start;
for (const entry of entries) {
const newOrder = Math.max(current--, 0);
if (entry.order === newOrder) continue;
entry.order = newOrder;
setWIOriginalDataValue(data, entry.uid, 'order', entry.order);
setWIOriginalDataValue(data, entry.order, 'order', entry.order);
updated++;
});
}
if (updated > 0) {
toastr.info(t`Updated ${updated} Order values`, t`Apply Current Sorting`);
toastr.info(`Updated ${updated} Order values`, 'Apply Custom Sorting');
await saveWorldInfo(name, data, true);
updateEditor(navigation_option.previous);
} else {
toastr.info(t`All values up to date`, t`Apply Current Sorting`);
toastr.info('All values up to date', 'Apply Custom Sorting');
}
});
-5
View File
@@ -561,11 +561,6 @@ export const ZAI_ENDPOINT = {
CODING: 'coding',
};
export const POLLINATIONS_ENDPOINT = {
AUTHENTICATED: 'authenticated',
ANONYMOUS: 'anonymous',
};
export const SILICONFLOW_ENDPOINT = {
GLOBAL: 'global',
CN: 'cn',
+11 -17
View File
@@ -20,7 +20,6 @@ import {
SILICONFLOW_ENDPOINT,
MINIMAX_ENDPOINT,
ZAI_ENDPOINT,
POLLINATIONS_ENDPOINT,
} from '../../constants.js';
import {
forwardFetchResponse,
@@ -84,7 +83,6 @@ const API_DEEPSEEK = 'https://api.deepseek.com/beta';
const API_XAI = 'https://api.x.ai/v1';
const API_AIMLAPI = 'https://api.aimlapi.com/v1';
const API_POLLINATIONS = 'https://gen.pollinations.ai/v1';
const API_POLLINATIONS_ANON = 'https://text.pollinations.ai/v1';
const API_MOONSHOT = 'https://api.moonshot.ai/v1';
const API_FIREWORKS = 'https://api.fireworks.ai/inference/v1';
const API_COMETAPI = 'https://api.cometapi.com/v1';
@@ -1791,9 +1789,8 @@ router.post('/status', async function (request, statusResponse) {
apiKey = readSecret(request.user.directories, SECRET_KEYS.AIMLAPI, request.body.secret_id);
headers = { ...AIMLAPI_HEADERS };
} else if (request.body.chat_completion_source === CHAT_COMPLETION_SOURCES.POLLINATIONS) {
const isAnonymous = request.body.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS;
apiUrl = 'https://gen.pollinations.ai/text';
apiKey = isAnonymous ? 'anonymous' : readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS, request.body.secret_id);
apiKey = readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS, request.body.secret_id);
headers = {};
} else if (request.body.chat_completion_source === CHAT_COMPLETION_SOURCES.GROQ) {
apiUrl = API_GROQ;
@@ -2417,23 +2414,20 @@ router.post('/generate', async function (request, response) {
};
}
} else if (request.body.chat_completion_source === CHAT_COMPLETION_SOURCES.POLLINATIONS) {
const isAnonymous = request.body.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS;
apiUrl = isAnonymous ? API_POLLINATIONS_ANON : API_POLLINATIONS;
apiKey = isAnonymous ? 'anonymous' : readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS, request.body.secret_id);
apiUrl = API_POLLINATIONS;
apiKey = readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS, request.body.secret_id);
headers = {};
bodyParams = {
reasoning_effort: request.body.reasoning_effort,
seed: request.body.seed ?? Math.floor(Math.random() * 99999999),
};
if (!isAnonymous) {
bodyParams['reasoning_effort'] = request.body.reasoning_effort;
if (request.body.json_schema) {
bodyParams['response_format'] = {
type: 'json_schema',
json_schema: {
schema: request.body.json_schema.value,
},
};
}
if (request.body.json_schema) {
bodyParams['response_format'] = {
type: 'json_schema',
json_schema: {
schema: request.body.json_schema.value,
},
};
}
} else if (request.body.chat_completion_source === CHAT_COMPLETION_SOURCES.MOONSHOT) {
apiUrl = new URL(request.body.reverse_proxy || API_MOONSHOT).toString();
+1 -1
View File
@@ -140,7 +140,7 @@ router.post('/status', async function (req, res) {
}
try {
const response = await fetch(IMAGE_NOVELAI + '/user/subscription', {
const response = await fetch(API_NOVELAI + '/user/subscription', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
+2 -5
View File
@@ -8,7 +8,6 @@ import express from 'express';
import { getConfigValue, mergeObjectWithYaml, excludeKeysByYaml, trimV1, delay } from '../util.js';
import { setAdditionalHeaders } from '../additional-headers.js';
import { readSecret, SECRET_KEYS } from './secrets.js';
import { POLLINATIONS_ENDPOINT } from '../constants.js';
import { AIMLAPI_HEADERS, OPENROUTER_HEADERS, SILICONFLOW_ENDPOINT, ZAI_ENDPOINT } from '../constants.js';
export const router = express.Router();
@@ -99,8 +98,7 @@ router.post('/caption-image', async (request, response) => {
}
if (request.body.api === 'pollinations') {
const isAnonymous = request.body.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS;
key = isAnonymous ? 'anonymous' : readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS);
key = readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS);
bodyParams.seed = Math.floor(Math.random() * Math.pow(2, 32));
}
@@ -184,8 +182,7 @@ router.post('/caption-image', async (request, response) => {
}
if (request.body.api === 'pollinations') {
const isAnonymous = request.body.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS;
apiUrl = isAnonymous ? 'https://text.pollinations.ai/v1/chat/completions' : 'https://gen.pollinations.ai/v1/chat/completions';
apiUrl = 'https://gen.pollinations.ai/v1/chat/completions';
}
if (request.body.api === 'moonshot' && !request.body.reverse_proxy) {
+3 -5
View File
@@ -14,7 +14,7 @@ import tiktoken from 'tiktoken';
import { TEXTGEN_TYPES } from '../constants.js';
import { setAdditionalHeaders } from '../additional-headers.js';
import { getConfigValue, isValidUrl, trimV1 } from '../util.js';
import { getConfigValue, isValidUrl } from '../util.js';
/**
* @typedef { (req: import('express').Request, res: import('express').Response) => Promise<any> } TokenizationHandler
@@ -1086,7 +1086,7 @@ router.post('/remote/textgenerationwebui/encode', async function (request, respo
setAdditionalHeaders(request, args, baseUrl);
// Convert to string + remove trailing slash + /v1 suffix
let url = trimV1(baseUrl);
let url = String(baseUrl).replace(/\/$/, '').replace(/\/v1$/, '');
switch (request.body.api_type) {
case TEXTGEN_TYPES.TABBY:
@@ -1109,12 +1109,10 @@ router.post('/remote/textgenerationwebui/encode', async function (request, respo
url += '/v1/tokenize';
args.body = JSON.stringify({ 'model': model, 'prompt': text });
break;
case TEXTGEN_TYPES.OOBA:
default:
url += '/v1/internal/encode';
args.body = JSON.stringify({ 'text': text });
break;
default:
return response.sendStatus(400);
}
const result = await fetch(url, args);
+6 -43
View File
@@ -4,25 +4,15 @@ import crypto from 'node:crypto';
import storage from 'node-persist';
import express from 'express';
import { RateLimiterMemory, RateLimiterRes } from 'rate-limiter-flexible';
import { getUserAvatar, toKey, getPasswordHash, getPasswordSalt, createBackupArchive, ensurePublicDirectoriesExist, toAvatarKey, getAccountVersion } from '../users.js';
import { SETTINGS_FILE } from '../constants.js';
import { checkForNewContent, CONTENT_TYPES } from './content-manager.js';
import { color, Cache, getConfigValue } from '../util.js';
import { getIpAddress, retryAfter } from '../express-common.js';
const RESET_POINTS = getConfigValue('rateLimiting.accountsResetMaxAttempts', 5, 'number');
const PREFER_REAL_IP_HEADER = getConfigValue('rateLimiting.preferRealIpHeader', false, 'boolean');
const RESET_CACHE = new Cache(5 * 60 * 1000);
const generateResetCode = () => Array.from({ length: 6 }, () => crypto.randomInt(0, 10)).join('');
export const router = express.Router();
const resetLimiter = new RateLimiterMemory({
points: RESET_POINTS > 0 ? RESET_POINTS : Number.MAX_SAFE_INTEGER,
duration: 300,
});
router.post('/logout', async (request, response) => {
try {
@@ -233,27 +223,14 @@ router.post('/change-name', async (request, response) => {
router.post('/reset-step1', async (request, response) => {
try {
const ip = getIpAddress(request, PREFER_REAL_IP_HEADER);
const rateLimit = await resetLimiter.get(ip);
// Check for existing rate limits, but allow requesting a new code unless locked out
if (rateLimit !== null && rateLimit.consumedPoints > resetLimiter.points) {
throw rateLimit;
}
const resetCode = generateResetCode();
const resetCode = String(crypto.randomInt(1000, 9999));
console.log();
console.log(color.magenta(`${request.user.profile.name}, your account reset code is: `) + color.red(resetCode));
console.log();
RESET_CACHE.set(request.user.profile.handle, resetCode);
return response.sendStatus(204);
} catch (error) {
if (error instanceof RateLimiterRes) {
console.error('Reset step 1 failed: Rate limited from', getIpAddress(request, PREFER_REAL_IP_HEADER));
return retryAfter(response, error).status(429).send({ error: 'Too many attempts. Try again later or contact your admin.' });
}
console.error('Reset step 1 failed:', error);
console.error('Recover step 1 failed:', error);
return response.sendStatus(500);
}
});
@@ -261,27 +238,19 @@ router.post('/reset-step1', async (request, response) => {
router.post('/reset-step2', async (request, response) => {
try {
if (!request.body.code) {
console.warn('Reset step 2 failed: Missing required fields');
console.warn('Recover step 2 failed: Missing required fields');
return response.status(400).json({ error: 'Missing required fields' });
}
if (request.user.profile.password && request.user.profile.password !== getPasswordHash(request.body.password, request.user.profile.salt)) {
console.warn('Reset step 2 failed: Incorrect password');
console.warn('Recover step 2 failed: Incorrect password');
return response.status(400).json({ error: 'Incorrect password' });
}
const ip = getIpAddress(request, PREFER_REAL_IP_HEADER);
const rateLimit = await resetLimiter.get(ip);
if (rateLimit !== null && rateLimit.consumedPoints > resetLimiter.points) {
throw rateLimit;
}
const code = RESET_CACHE.get(request.user.profile.handle);
if (!code || code !== request.body.code) {
await resetLimiter.consume(ip);
console.warn('Reset step 2 failed: Incorrect code');
console.warn('Recover step 2 failed: Incorrect code');
return response.status(400).json({ error: 'Incorrect code' });
}
@@ -291,16 +260,10 @@ router.post('/reset-step2', async (request, response) => {
await ensurePublicDirectoriesExist();
await checkForNewContent([request.user.directories]);
await resetLimiter.delete(ip);
RESET_CACHE.remove(request.user.profile.handle);
return response.sendStatus(204);
} catch (error) {
if (error instanceof RateLimiterRes) {
console.error('Reset step 2 failed: Rate limited from', getIpAddress(request, PREFER_REAL_IP_HEADER));
return retryAfter(response, error).status(429).send({ error: 'Too many attempts. Try again later or contact your admin.' });
}
console.error('Reset step 2 failed:', error);
console.error('Recover step 2 failed:', error);
return response.sendStatus(500);
}
});
-38
View File
@@ -124,44 +124,6 @@ test.describe('MacroEngine', () => {
const output = await evaluateWithEngine(page, input);
expect(output).toBe('StartEnd');
});
test.describe('Scoped comment macro', () => {
test('should remove scoped comment block (basic)', async ({ page }) => {
const input = 'Before{{//}}This entire block is a comment.{{///}}After';
const output = await evaluateWithEngine(page, input);
expect(output).toBe('BeforeAfter');
});
test('should remove scoped comment block spanning multiple lines', async ({ page }) => {
const input = 'Start\n{{//}}\n This entire block is a comment.\n It can span multiple lines.\n{{///}}\nEnd';
const output = await evaluateWithEngine(page, input);
expect(output).toBe('Start\n\nEnd');
});
test('should remove scoped comment block with extra slashes in closing tag', async ({ page }) => {
const input = 'A{{//}}ignored{{////}}B';
const output = await evaluateWithEngine(page, input);
expect(output).toBe('AB');
});
test('should remove scoped comment block with macros inside (macros not evaluated)', async ({ page }) => {
const input = 'X{{//}}{{user}} should be ignored{{///}}Y';
const output = await evaluateWithEngine(page, input);
expect(output).toBe('XY');
});
test('should not treat bare {{//}} without matching closer as scoped', async ({ page }) => {
const input = 'A{{// just a comment}}B';
const output = await evaluateWithEngine(page, input);
expect(output).toBe('AB');
});
test('should handle scoped comment adjacent to other text and macros', async ({ page }) => {
const input = '{{user}}{{//}}ignored block{{///}}{{user}}';
const output = await evaluateWithEngine(page, input);
expect(output).toBe('UserUser');
});
});
});
test.describe('Trim macro', () => {
+1 -45
View File
@@ -508,49 +508,6 @@ test.describe('MacroLexer', () => {
expect(tokens).toEqual(expectedTokens);
});
// TODO: test invalid argument name identifiers
// REGRESSION TEST: https://github.com/SillyTavern/SillyTavern/issues/5618
// {{setvar::foo::|bar}} - pipe character should NOT be treated as Filter.Pipe (which breaks parsing)
test('should handle pipe character in argument values (issue #5618)', async ({ page }) => {
const input = '{{setvar::foo::|bar}}';
const tokens = await runLexerGetTokens(page, input);
const expectedTokens = [
{ type: 'Macro.Start', text: '{{' },
{ type: 'Macro.Identifier', text: 'setvar' },
{ type: 'Args.DoubleColon', text: '::' },
{ type: 'Identifier', text: 'foo' },
{ type: 'Args.DoubleColon', text: '::' },
// Pipe is captured as Unknown (not Filter.Pipe), which allows the macro to parse correctly
{ type: 'Unknown', text: '|' },
{ type: 'Identifier', text: 'bar' },
{ type: 'Macro.End', text: '}}' },
];
expect(tokens).toEqual(expectedTokens);
});
// Test multiple pipes in argument values
test('should handle multiple pipe characters in argument values', async ({ page }) => {
const input = '{{setvar::key::a|b|c}}';
const tokens = await runLexerGetTokens(page, input);
const expectedTokens = [
{ type: 'Macro.Start', text: '{{' },
{ type: 'Macro.Identifier', text: 'setvar' },
{ type: 'Args.DoubleColon', text: '::' },
{ type: 'Identifier', text: 'key' },
{ type: 'Args.DoubleColon', text: '::' },
{ type: 'Identifier', text: 'a' },
{ type: 'Unknown', text: '|' },
{ type: 'Identifier', text: 'b' },
{ type: 'Unknown', text: '|' },
{ type: 'Identifier', text: 'c' },
{ type: 'Macro.End', text: '}}' },
];
expect(tokens).toEqual(expectedTokens);
});
});
test.describe('Macro Execution Modifiers', () => {
@@ -974,8 +931,7 @@ test.describe('MacroLexer', () => {
});
});
// SKIPPED: Pipe/filter feature temporarily disabled. See https://github.com/SillyTavern/SillyTavern/issues/5618
test.describe.skip('Macro Output Modifiers', () => {
test.describe('Macro Output Modifiers', () => {
// {{macro | outputModifier}}
test('should support output modifier without arguments', async ({ page }) => {
const input = '{{macro | outputModifier}}';
-323
View File
@@ -1,323 +0,0 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
/**
* @typedef {import('../../public/scripts/message-formatter.js').MessageFormattingContext} MessageFormattingContext
*/
test.describe('MessageFormatter', () => {
// message-formatter.js imports script.js, which requires the full ST module
// graph to be settled before dynamic import works (otherwise hits SlashCommandParser TDZ).
test.beforeEach(testSetup.awaitST);
// -------------------------------------------------------------------------
// Module exports & singleton
// -------------------------------------------------------------------------
test.describe('Module exports & singleton', () => {
test('should export formatting_stage with expected keys', async ({ page }) => {
const stage = await page.evaluate(async () => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { formatting_stage } = await import('./scripts/message-formatter.js');
return formatting_stage;
});
expect(stage).toEqual({
BEFORE_REGEX: 'beforeRegex',
AFTER_REGEX: 'afterRegex',
AFTER_MARKDOWN: 'afterMarkdown',
});
});
test('should export hook_order with expected keys', async ({ page }) => {
const order = await page.evaluate(async () => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { hook_order } = await import('./scripts/message-formatter.js');
return hook_order;
});
expect(order).toMatchObject({
EARLIEST: 0,
EARLY: 10,
NORMAL: 50,
LATE: 90,
LATEST: 100,
});
});
test('should expose stage and order constants on the instance', async ({ page }) => {
const result = await page.evaluate(async () => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage, hook_order } = await import('./scripts/message-formatter.js');
return {
stageMatches: JSON.stringify(MessageFormatter.stage) === JSON.stringify(formatting_stage),
orderMatches: JSON.stringify(MessageFormatter.order) === JSON.stringify(hook_order),
};
});
expect(result.stageMatches).toBe(true);
expect(result.orderMatches).toBe(true);
});
});
// -------------------------------------------------------------------------
// addHook — registration validation
// -------------------------------------------------------------------------
test.describe('addHook — registration validation', () => {
test('should throw TypeError when registering a non-function hook', async ({ page }) => {
const errorMessage = await page.evaluate(async () => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { formatting_stage } = await import('./scripts/message-formatter.js');
// Use a fresh MessageFormatter instance so we don't pollute the singleton
const { MessageFormatter: MF } = await import('./scripts/message-formatter.js');
try {
// @ts-ignore intentional misuse
MF.addHook('not a function', { stage: formatting_stage.AFTER_MARKDOWN });
return null;
} catch (e) {
return { name: e.name, message: e.message };
}
});
expect(errorMessage).not.toBeNull();
expect(errorMessage.name).toBe('TypeError');
});
test('should throw TypeError when registering an async hook', async ({ page }) => {
const errorMessage = await page.evaluate(async () => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter } = await import('./scripts/message-formatter.js');
try {
MessageFormatter.addHook(async (mes) => mes);
return null;
} catch (e) {
return { name: e.name, message: e.message };
}
});
expect(errorMessage).not.toBeNull();
expect(errorMessage.name).toBe('TypeError');
expect(errorMessage.message).toContain('synchronous');
});
test('should throw RangeError when registering a hook with an unknown stage', async ({ page }) => {
const errorMessage = await page.evaluate(async () => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter } = await import('./scripts/message-formatter.js');
try {
// @ts-ignore intentional misuse
MessageFormatter.addHook((mes) => mes, { stage: 'nonExistentStage' });
return null;
} catch (e) {
return { name: e.name, message: e.message };
}
});
expect(errorMessage).not.toBeNull();
expect(errorMessage.name).toBe('RangeError');
expect(errorMessage.message).toContain('nonExistentStage');
});
test('should successfully register a valid synchronous hook', async ({ page }) => {
const threw = await page.evaluate(async () => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter } = await import('./scripts/message-formatter.js');
try {
MessageFormatter.addHook((mes) => mes);
return false;
} catch {
return true;
}
});
expect(threw).toBe(false);
});
});
// -------------------------------------------------------------------------
// runStage — hook execution
// -------------------------------------------------------------------------
test.describe('runStage — hook execution', () => {
/** @type {import('../../public/scripts/message-formatter.js').MessageFormattingBase} */
const BASE_CTX = { ch_name: 'Test', isSystem: false, isUser: false, messageId: 1, isReasoning: false };
test('should return the message unchanged when no hooks are registered for a stage', async ({ page }) => {
// Use a unique tag that no registered hook could produce so the result
// is deterministic regardless of hooks other tests added to the singleton.
const TAG = `__mf_test_nohooks_${Date.now()}`;
const output = await page.evaluate(async ({ base, tag }) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage } = await import('./scripts/message-formatter.js');
// No hook is registered that would append/modify `tag`, so it must come back unchanged.
return MessageFormatter.runStage(formatting_stage.AFTER_MARKDOWN, tag, base);
}, { base: BASE_CTX, tag: TAG });
expect(output).toBe(TAG);
});
test('should apply a registered hook and return the transformed text', async ({ page }) => {
const TAG = `__mf_test_transform_${Date.now()}`;
const output = await page.evaluate(async ({ base, tag }) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage } = await import('./scripts/message-formatter.js');
MessageFormatter.addHook((mes) => mes + tag, { stage: formatting_stage.BEFORE_REGEX });
return MessageFormatter.runStage(formatting_stage.BEFORE_REGEX, 'hello', base);
}, { base: BASE_CTX, tag: TAG });
expect(output).toBe(`hello${TAG}`);
});
test('should pass an immutable frozen context to hooks', async ({ page }) => {
const result = await page.evaluate(async (base) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage } = await import('./scripts/message-formatter.js');
let receivedCtx = null;
let isFrozen = false;
MessageFormatter.addHook((mes, ctx) => {
receivedCtx = { ...ctx };
isFrozen = Object.isFrozen(ctx);
return mes;
}, { stage: formatting_stage.AFTER_REGEX });
MessageFormatter.runStage(formatting_stage.AFTER_REGEX, 'text', base);
return { receivedCtx, isFrozen };
}, BASE_CTX);
expect(result.receivedCtx.stage).toBe('afterRegex');
expect(result.receivedCtx.ch_name).toBe(BASE_CTX.ch_name);
expect(result.isFrozen).toBe(true);
});
test('should inject the correct stage into the context', async ({ page }) => {
const stages = await page.evaluate(async (base) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage } = await import('./scripts/message-formatter.js');
const seen = [];
const hook = (mes, ctx) => { seen.push(ctx.stage); return mes; };
MessageFormatter.addHook(hook, { stage: formatting_stage.BEFORE_REGEX });
MessageFormatter.addHook(hook, { stage: formatting_stage.AFTER_REGEX });
MessageFormatter.addHook(hook, { stage: formatting_stage.AFTER_MARKDOWN });
MessageFormatter.runStage(formatting_stage.BEFORE_REGEX, 'a', base);
MessageFormatter.runStage(formatting_stage.AFTER_REGEX, 'b', base);
MessageFormatter.runStage(formatting_stage.AFTER_MARKDOWN, 'c', base);
return seen;
}, BASE_CTX);
expect(stages).toContain('beforeRegex');
expect(stages).toContain('afterRegex');
expect(stages).toContain('afterMarkdown');
});
test('should run hooks in ascending order within a stage', async ({ page }) => {
const TAG = `__mf_test_order_${Date.now()}`;
const output = await page.evaluate(async ({ base, tag }) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage, hook_order } = await import('./scripts/message-formatter.js');
MessageFormatter.addHook((mes) => mes + `[late${tag}]`, { stage: formatting_stage.AFTER_MARKDOWN, order: hook_order.LATE });
MessageFormatter.addHook((mes) => mes + `[early${tag}]`, { stage: formatting_stage.AFTER_MARKDOWN, order: hook_order.EARLY });
MessageFormatter.addHook((mes) => mes + `[normal${tag}]`, { stage: formatting_stage.AFTER_MARKDOWN, order: hook_order.NORMAL });
return MessageFormatter.runStage(formatting_stage.AFTER_MARKDOWN, '', base);
}, { base: BASE_CTX, tag: TAG });
// early → normal → late
const earlyIdx = output.indexOf(`[early${TAG}]`);
const normalIdx = output.indexOf(`[normal${TAG}]`);
const lateIdx = output.indexOf(`[late${TAG}]`);
expect(earlyIdx).toBeLessThan(normalIdx);
expect(normalIdx).toBeLessThan(lateIdx);
});
test('should continue pipeline and skip a hook that throws', async ({ page }) => {
const TAG = `__mf_test_throw_${Date.now()}`;
const output = await page.evaluate(async ({ base, tag }) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage, hook_order } = await import('./scripts/message-formatter.js');
// Hook 1: throws
MessageFormatter.addHook(() => { throw new Error('intentional test error'); }, {
stage: formatting_stage.BEFORE_REGEX,
order: hook_order.EARLY,
});
// Hook 2: appends tag to prove it still ran
MessageFormatter.addHook((mes) => mes + tag, {
stage: formatting_stage.BEFORE_REGEX,
order: hook_order.LATE,
});
return MessageFormatter.runStage(formatting_stage.BEFORE_REGEX, 'base', base);
}, { base: BASE_CTX, tag: TAG });
expect(output).toBe(`base${TAG}`);
});
test('should ignore a hook that returns a non-string and keep the previous text', async ({ page }) => {
const TAG = `__mf_test_nonstring_${Date.now()}`;
const result = await page.evaluate(async ({ base, tag }) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage, hook_order } = await import('./scripts/message-formatter.js');
const warnings = [];
const origWarn = console.warn.bind(console);
console.warn = (...args) => { warnings.push(args.join(' ')); origWarn(...args); };
// Hook 1: returns undefined (bad hook)
MessageFormatter.addHook(() => undefined, {
stage: formatting_stage.AFTER_REGEX,
order: hook_order.EARLY,
});
// Hook 2: valid, appends tag
MessageFormatter.addHook((mes) => mes + tag, {
stage: formatting_stage.AFTER_REGEX,
order: hook_order.LATE,
});
const output = MessageFormatter.runStage(formatting_stage.AFTER_REGEX, 'original', base);
console.warn = origWarn;
return { output, hasWarning: warnings.some(w => w.includes('undefined')) };
}, { base: BASE_CTX, tag: TAG });
expect(result.output).toBe(`original${TAG}`);
expect(result.hasWarning).toBe(true);
});
test('should warn and keep text when a hook returns a Promise (simulated async escape)', async ({ page }) => {
const result = await page.evaluate(async (base) => {
/** @type {import('../../public/scripts/message-formatter.js')} */
const { MessageFormatter, formatting_stage } = await import('./scripts/message-formatter.js');
const warnings = [];
const origWarn = console.warn.bind(console);
console.warn = (...args) => { warnings.push(args.join(' ')); origWarn(...args); };
// Bypasses registration check by wrapping async call inside a sync function
MessageFormatter.addHook(() => Promise.resolve('sneaky async'), {
stage: formatting_stage.BEFORE_REGEX,
});
const output = MessageFormatter.runStage(formatting_stage.BEFORE_REGEX, 'safe', base);
console.warn = origWarn;
return {
output,
hasPromiseWarning: warnings.some(w => w.toLowerCase().includes('promise')),
};
}, BASE_CTX);
expect(result.output).toBe('safe');
expect(result.hasPromiseWarning).toBe(true);
});
});
});
+246
View File
@@ -0,0 +1,246 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
test.describe('fixNestedEmphasis', () => {
test.beforeEach(testSetup.goST);
test.describe('Basic nested emphasis', () => {
test('should convert inner emphasis to bold within outer emphasis', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*She looks at you. *Are you okay?* she asks.*');
expect(result).toBe('*She looks at you. **Are you okay?** she asks.*');
});
test('should handle the issue example case', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*Some Text *Nested Emphasis Text* More text*');
expect(result).toBe('*Some Text **Nested Emphasis Text** More text*');
});
test('should handle short nested action/speech', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*action *speech* action*');
expect(result).toBe('*action **speech** action*');
});
test('should handle nested emphasis with punctuation in inner text', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*She sighs. *I never asked for this,* she mutters, turning away.*');
expect(result).toBe('*She sighs. **I never asked for this,** she mutters, turning away.*');
});
});
test.describe('Multiple nested pairs', () => {
test('should handle multiple nested pairs in same outer emphasis', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*action *speech1* middle *speech2* end*');
expect(result).toBe('*action **speech1** middle **speech2** end*');
});
test('should handle multiple nested pairs with longer text', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*She said *hello* and *goodbye* to him.*');
expect(result).toBe('*She said **hello** and **goodbye** to him.*');
});
});
test.describe('Text that should NOT be modified', () => {
test('should not modify simple emphasis', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*normal emphasis*');
expect(result).toBe('*normal emphasis*');
});
test('should not modify bold text', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**bold text**');
expect(result).toBe('**bold text**');
});
test('should not modify sequential (non-nested) emphasis', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*first emphasis* and *second emphasis*');
expect(result).toBe('*first emphasis* and *second emphasis*');
});
test('should not modify already-correct bold inside italic', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*text **already bold** text*');
expect(result).toBe('*text **already bold** text*');
});
test('should not modify triple emphasis', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '***triple emphasis***');
expect(result).toBe('***triple emphasis***');
});
test('should not modify plain text', async ({ page }) => {
const result = await runFixNestedEmphasis(page, 'no formatting at all');
expect(result).toBe('no formatting at all');
});
test('should not modify adjacent emphasis without spaces (non-nested pattern)', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*hello*world*bye*');
expect(result).toBe('*hello*world*bye*');
});
});
test.describe('Nested bold (** inside **)', () => {
test('should strip inner ** when nested inside outer **', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**This is **bold**, is it?**');
expect(result).toBe('**This is bold, is it?**');
});
test('should strip inner ** for simple nesting', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**text **nested** text**');
expect(result).toBe('**text nested text**');
});
test('should strip inner ** for short content', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**a **b** c**');
expect(result).toBe('**a b c**');
});
test('should strip inner ** with longer word', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**She said **hello** to him**');
expect(result).toBe('**She said hello to him**');
});
test('should handle multiple nested ** pairs', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**She **whispered** and then **shouted** at him**');
expect(result).toBe('**She whispered and then shouted at him**');
});
test('should not modify normal bold (no nesting)', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**normal bold**');
expect(result).toBe('**normal bold**');
});
test('should not modify sequential bold', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '**first** and **second**');
expect(result).toBe('**first** and **second**');
});
});
test.describe('Edge cases', () => {
test('should handle nested emphasis next to sequential emphasis', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*start *nested* end* and *another*');
expect(result).toBe('*start **nested** end* and *another*');
});
test('should not modify asterisk preceded by space (non-flanking)', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*single asterisk at end *');
expect(result).toBe('*single asterisk at end *');
});
test('should handle nested emphasis adjacent to punctuation', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*She said: *"Hello!"* quietly.*');
expect(result).toBe('*She said: **"Hello!"** quietly.*');
});
test('should handle tabs as whitespace around nested emphasis', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*She looks.\t*Are you okay?*\tshe asks.*');
expect(result).toBe('*She looks.\t**Are you okay?**\tshe asks.*');
});
test('should process each line independently for multi-line text', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '*first line\n*nested* second line*');
// Lines are processed independently - first line has only 1 asterisk, second has 3
expect(result).toBe('*first line\n*nested* second line*');
});
});
test.describe('Code block protection', () => {
test('should not modify content inside inline code', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '`*code *nested* code*`');
expect(result).toBe('`*code *nested* code*`');
});
test('should not modify content inside fenced code blocks', async ({ page }) => {
const result = await runFixNestedEmphasis(page, '```\n*code *nested* code*\n```');
expect(result).toBe('```\n*code *nested* code*\n```');
});
});
test.describe('Realistic roleplay examples', () => {
test('should handle dialogue within action narration', async ({ page }) => {
const input = '*She reaches out, her hand trembling. *Please... don\'t leave me,* she whispers, tears streaming down her face.*';
const expected = '*She reaches out, her hand trembling. **Please... don\'t leave me,** she whispers, tears streaming down her face.*';
const result = await runFixNestedEmphasis(page, input);
expect(result).toBe(expected);
});
test('should handle multiple dialogue lines within narration', async ({ page }) => {
const input = '*The door creaks open. *Who\'s there?* a voice calls out from the darkness. *Show yourself!* it demands.*';
const expected = '*The door creaks open. **Who\'s there?** a voice calls out from the darkness. **Show yourself!** it demands.*';
const result = await runFixNestedEmphasis(page, input);
expect(result).toBe(expected);
});
});
test.describe('Full pipeline (fixNestedEmphasis + showdown)', () => {
test('should render nested emphasis as italic with bold inside', async ({ page }) => {
const html = await runFullPipeline(page, '*action *speech* action*');
expect(html).toContain('<em>');
expect(html).toContain('<strong>');
expect(html).toContain('speech');
});
test('should render basic nested example correctly', async ({ page }) => {
const html = await runFullPipeline(page, '*Some Text *Nested Emphasis Text* More text*');
expect(html).toMatch(/<em>.*<strong>Nested Emphasis Text<\/strong>.*<\/em>/);
});
test('should not break normal emphasis rendering', async ({ page }) => {
const html = await runFullPipeline(page, '*normal emphasis*');
expect(html).toContain('<em>normal emphasis</em>');
});
test('should not break bold rendering', async ({ page }) => {
const html = await runFullPipeline(page, '**bold text**');
expect(html).toContain('<strong>bold text</strong>');
});
test('should not break sequential emphasis rendering', async ({ page }) => {
const html = await runFullPipeline(page, '*first* and *second*');
expect(html).toContain('<em>first</em>');
expect(html).toContain('<em>second</em>');
});
test('should render nested bold as single bold block', async ({ page }) => {
const html = await runFullPipeline(page, '**This is **bold**, is it?**');
expect(html).toContain('<strong>');
expect(html).toContain('This is bold');
expect(html).not.toContain('**');
});
test('should render stripped nested bold correctly', async ({ page }) => {
const html = await runFullPipeline(page, '**text **nested** text**');
expect(html).toMatch(/<strong>text nested text<\/strong>/);
});
});
});
/**
* Run fixNestedEmphasis in the browser context.
* @param {import('@playwright/test').Page} page
* @param {string} input
* @returns {Promise<string>}
*/
async function runFixNestedEmphasis(page, input) {
return await page.evaluate(async (text) => {
/** @type {import('../../public/scripts/showdown-emphasis.js')} */
const { fixNestedEmphasis } = await import('./scripts/showdown-emphasis.js');
return fixNestedEmphasis(text);
}, input);
}
/**
* Run fixNestedEmphasis followed by showdown conversion in the browser context.
* @param {import('@playwright/test').Page} page
* @param {string} input
* @returns {Promise<string>}
*/
async function runFullPipeline(page, input) {
return await page.evaluate(async (text) => {
/** @type {import('../../public/scripts/showdown-emphasis.js')} */
const { fixNestedEmphasis } = await import('./scripts/showdown-emphasis.js');
const { showdown } = await import('./lib.js');
const converter = new showdown.Converter({
literalMidWordUnderscores: true,
simpleLineBreaks: true,
});
const fixed = fixNestedEmphasis(text);
return converter.makeHtml(fixed);
}, input);
}