Compare commits

..
Author SHA1 Message Date
Cohee 0887658ac0 Merge branch 'staging' into feat/secret-data-encrypt 2026-05-02 20:10:56 +03:00
Cohee b2ed175a94 fix: eslint in test 2026-04-29 01:47:44 +03:00
Cohee 5e01aa6db8 fix: duplicate type check 2026-04-28 23:16:34 +03:00
CoheeandCopilot 49d8e6c308 fix: combine console logs on errors
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 22:45:51 +03:00
CoheeandCopilot 94cc6dc812 feat: implement master password for encrypting secrets
Co-authored-by: Copilot <copilot@github.com>
2026-04-28 22:06:37 +03:00
78 changed files with 732 additions and 3516 deletions
-1
View File
@@ -70,7 +70,6 @@ module.exports = {
'**/dist/**',
'**/.git/**',
'public/lib/**',
'public/scripts/extensions/third-party/**',
'backups/**',
'data/**',
'cache/**',
+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) 編寫
-1
View File
@@ -34,7 +34,6 @@ whitelist.txt
.vscode/**
!.vscode/extensions.json
.idea/
.windsurf/
secrets.json
/dist
/backups/
-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
+3 -2
View File
@@ -1,4 +1,7 @@
# -- DATA CONFIGURATION --
# This is the encryption password for user secrets and other sensitive data. If left empty, encryption will be disabled and data will be stored in plaintext.
# For better security, use a CLI argument or an environment variable (SILLYTAVERN_MASTERPASSWORD) instead of storing the password in the config file.
masterPassword: ''
# Root directory for user data storage
dataRoot: ./data
# -- SERVER CONFIGURATION --
@@ -198,8 +201,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:
+1 -1
View File
@@ -1,7 +1,7 @@
{
"chat_completion_source": "openai",
"openai_model": "gpt-4-turbo",
"claude_model": "claude-sonnet-5",
"claude_model": "claude-sonnet-4-5",
"openrouter_model": "OR_Website",
"openrouter_use_fallback": false,
"openrouter_group_models": false,
+1 -1
View File
@@ -622,7 +622,7 @@
},
"wi_format": "{0}",
"openai_model": "gpt-4-turbo",
"claude_model": "claude-sonnet-5",
"claude_model": "claude-sonnet-4-5",
"ai21_model": "jamba-large",
"openrouter_model": "OR_Website",
"reverse_proxy": "",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "sillytavern",
"version": "1.18.0",
"version": "1.17.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sillytavern",
"version": "1.18.0",
"version": "1.17.0",
"license": "AGPL-3.0",
"dependencies": {
"@adobe/css-tools": "^4.4.4",
+1 -1
View File
@@ -115,7 +115,7 @@
"type": "git",
"url": "https://github.com/SillyTavern/SillyTavern.git"
},
"version": "1.18.0",
"version": "1.17.0",
"scripts": {
"init": "node src/server-init.js",
"start": "node server.js",
+3 -4
View File
@@ -39,10 +39,9 @@ if (command === 'install') {
}
async function updatePlugins() {
const directories = fs.readdirSync(pluginsPath, { withFileTypes: true })
.filter(dirent => dirent.isDirectory() || dirent.isSymbolicLink())
.filter(dirent => !dirent.name.startsWith('.'))
.map(dirent => dirent.name);
const directories = fs.readdirSync(pluginsPath)
.filter(file => !file.startsWith('.'))
.filter(file => fs.statSync(path.join(pluginsPath, file)).isDirectory());
console.log(`Found ${color.cyan(directories.length)} directories in ./plugins`);
+37 -56
View File
@@ -809,21 +809,18 @@
<div class="inline-drawer-content">
<div class="range-block m-t-1">
<div class="justifyLeft" data-i18n="Main">Main</div>
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="main_prompt_quick_edit_textarea" data-i18n="[title]Expand the editor"></i>
<div class="wide100p">
<textarea id="main_prompt_quick_edit_textarea" class="text_pole textarea_compact autoSetHeight" rows="6" placeholder="&mdash;" data-pm-prompt="main"></textarea>
</div>
</div>
<div class="range-block m-t-1">
<div class="justifyLeft" data-i18n="Auxiliary">Auxiliary</div>
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="nsfw_prompt_quick_edit_textarea" data-i18n="[title]Expand the editor"></i>
<div class="wide100p">
<textarea id="nsfw_prompt_quick_edit_textarea" class="text_pole textarea_compact autoSetHeight" rows="6" placeholder="&mdash;" data-pm-prompt="nsfw"></textarea>
</div>
</div>
<div class="range-block m-t-1">
<div class="justifyLeft" data-i18n="Post-History Instructions">Post-History Instructions</div>
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="jailbreak_prompt_quick_edit_textarea" data-i18n="[title]Expand the editor"></i>
<div class="wide100p">
<textarea id="jailbreak_prompt_quick_edit_textarea" class="text_pole textarea_compact autoSetHeight" rows="6" placeholder="&mdash;" data-pm-prompt="jailbreak"></textarea>
</div>
@@ -2147,9 +2144,6 @@
<span data-i18n="Allows the model to return its thinking process.">
Allows the model to return its thinking process.
</span>
<strong data-i18n="This setting enables or disables reasoning generation by the model." data-source="deepseek,zai,moonshot">
This setting enables or disables reasoning generation by the model.
</strong>
<strong data-i18n="This setting affects visibility only." data-source-mode="except" data-source="zai,moonshot,openrouter,deepseek">
This setting affects visibility only.
</strong>
@@ -2169,14 +2163,14 @@
<option data-i18n="openai_reasoning_effort_high" value="high">High</option>
<option data-i18n="openai_reasoning_effort_maximum" value="max">Maximum</option>
</select>
<div class="toggle-description justifyLeft marginBot5" data-source="openai,custom,xai,aimlapi,openrouter,pollinations,perplexity,cometapi,electronhub,azure_openai,chutes" data-i18n="OpenAI-compatible effort levels vary by model. Minimum and maximum may use model-specific aliases. Auto does not send an effort level.">
OpenAI-compatible effort levels vary by model. Minimum and maximum may use model-specific aliases. Auto does not send an effort level.
<div class="toggle-description justifyLeft marginBot5" data-source="openai,custom,xai,aimlapi,openrouter,pollinations,perplexity,cometapi,electronhub,azure_openai,chutes" data-i18n="OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level.">
OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level.
</div>
<strong class="toggle-description justifyLeft marginBot5" data-source="openrouter">
Request model reasoning = Off with Reasoning Effort = Minimum disables reasoning entirely on models that support that, but can cause errors with some models.
</strong>
<div class="toggle-description justifyLeft marginBot5" data-source="claude" data-i18n="Selects an effort level on adaptive-thinking models. On older Claude models, it allocates a portion of the response length to thinking. Auto does not request thinking.">
Selects an effort level on adaptive-thinking models. On older Claude models, it allocates a portion of the response length to thinking. Auto does not request thinking.
<div class="toggle-description justifyLeft marginBot5" data-source="claude" data-i18n="Allocates a portion of the response length for thinking (min: 1024 tokens, low: 10%, medium: 25%, high: 50%, max: 95%), but minimum 1024 tokens. Auto does not request thinking.">
Allocates a portion of the response length for thinking (min: 1024 tokens, low: 10%, medium: 25%, high: 50%, max: 95%), but minimum 1024 tokens. Auto does not request thinking.
</div>
<div class="toggle-description justifyLeft marginBot5" data-source="makersuite,vertexai">
<span data-i18n="Sets a dynamic reasoning depth level for thinking (Flash 3/Pro 3). High and low are supported by both, minimal and medium are Flash 3 only. Auto lets the model decide.">
@@ -2204,7 +2198,7 @@
Constrains the verbosity of the model's response.
</div>
<strong class="toggle-description justifyLeft marginBot5" data-source="claude">
On adaptive-thinking Claude models, a non-automatic Reasoning Effort takes precedence over Verbosity.
On Opus 4.6 / Sonnet 4.6, a non-automatic Reasoning Effort takes precedence over Verbosity.
</strong>
</div>
</div>
@@ -3052,12 +3046,6 @@
<div>
<h4 data-i18n="OpenAI Model">OpenAI Model</h4>
<select id="model_openai_select">
<optgroup label="GPT-5.6">
<option value="gpt-5.6">gpt-5.6</option>
<option value="gpt-5.6-sol">gpt-5.6-sol</option>
<option value="gpt-5.6-terra">gpt-5.6-terra</option>
<option value="gpt-5.6-luna">gpt-5.6-luna</option>
</optgroup>
<optgroup label="GPT-5.5">
<option value="gpt-5.5">gpt-5.5</option>
<option value="gpt-5.5-2026-04-23">gpt-5.5-2026-04-23</option>
@@ -3182,10 +3170,6 @@
<h4 data-i18n="Claude Model">Claude Model</h4>
<select id="model_claude_select">
<optgroup label="Versions">
<option value="claude-fable-5">claude-fable-5</option>
<option value="claude-opus-5">claude-opus-5</option>
<option value="claude-sonnet-5">claude-sonnet-5</option>
<option value="claude-opus-4-8">claude-opus-4-8</option>
<option value="claude-opus-4-7">claude-opus-4-7</option>
<option value="claude-opus-4-6">claude-opus-4-6</option>
<option value="claude-opus-4-5">claude-opus-4-5</option>
@@ -3195,10 +3179,21 @@
<option value="claude-sonnet-4-5-20250929">claude-sonnet-4-5-20250929</option>
<option value="claude-haiku-4-5">claude-haiku-4-5</option>
<option value="claude-haiku-4-5-20251001">claude-haiku-4-5-20251001</option>
<option value="claude-opus-4-0">claude-opus-4-0 (deprecated)</option>
<option value="claude-opus-4-20250514">claude-opus-4-20250514 (deprecated)</option>
<option value="claude-sonnet-4-0">claude-sonnet-4-0 (deprecated)</option>
<option value="claude-sonnet-4-20250514">claude-sonnet-4-20250514 (deprecated)</option>
<option value="claude-opus-4-1">claude-opus-4-1</option>
<option value="claude-opus-4-1-20250805">claude-opus-4-1-20250805</option>
<option value="claude-opus-4-0">claude-opus-4-0</option>
<option value="claude-opus-4-20250514">claude-opus-4-20250514</option>
<option value="claude-sonnet-4-0">claude-sonnet-4-0</option>
<option value="claude-sonnet-4-20250514">claude-sonnet-4-20250514</option>
<option value="claude-3-7-sonnet-latest">claude-3-7-sonnet-latest</option>
<option value="claude-3-7-sonnet-20250219">claude-3-7-sonnet-20250219</option>
<option value="claude-3-5-sonnet-latest">claude-3-5-sonnet-latest</option>
<option value="claude-3-5-sonnet-20241022">claude-3-5-sonnet-20241022</option>
<option value="claude-3-5-sonnet-20240620">claude-3-5-sonnet-20240620</option>
<option value="claude-3-5-haiku-latest">claude-3-5-haiku-latest</option>
<option value="claude-3-5-haiku-20241022">claude-3-5-haiku-20241022</option>
<option value="claude-3-opus-20240229">claude-3-opus-20240229</option>
<option value="claude-3-haiku-20240307">claude-3-haiku-20240307</option>
</optgroup>
</select>
</div>
@@ -3306,17 +3301,14 @@
<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">gemini-3.1-flash-lite</option>
<option value="gemini-3.1-flash-image">gemini-3.1-flash-image</option>
<option value="gemini-3.1-flash-lite-preview">gemini-3.1-flash-lite-preview</option>
<option value="gemini-3.1-flash-image-preview">gemini-3.1-flash-image-preview</option>
</optgroup>
<optgroup label="Gemini 3.0">
<option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
<option value="gemini-3-pro-image">gemini-3-pro-image</option>
<option value="gemini-3-pro-image-preview">gemini-3-pro-image-preview</option>
<option value="gemini-3-flash-preview">gemini-3-flash-preview</option>
</optgroup>
<optgroup label="Gemini 2.5">
@@ -3489,17 +3481,14 @@
<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">gemini-3.1-flash-lite</option>
<option value="gemini-3.1-flash-image">gemini-3.1-flash-image</option>
<option value="gemini-3.1-flash-lite-preview">gemini-3.1-flash-lite-preview</option>
<option value="gemini-3.1-flash-image-preview">gemini-3.1-flash-image-preview</option>
</optgroup>
<optgroup label="Gemini 3.0">
<option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
<option value="gemini-3-pro-image">gemini-3-pro-image</option>
<option value="gemini-3-pro-image-preview">gemini-3-pro-image-preview</option>
<option value="gemini-3-flash-preview">gemini-3-flash-preview</option>
</optgroup>
<optgroup label="Gemini 2.5">
@@ -3879,24 +3868,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">
@@ -3950,7 +3932,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>
+1 -1
View File
@@ -717,7 +717,7 @@
"Click to set a new User Name": "Cliquez pour définir un nouveau nom d'utilisateur",
"Click to lock your selected persona to the current chat. Click again to remove the lock.": "Cliquez pour verrouiller votre persona sélectionnée sur la discussion actuelle. Cliquez à nouveau pour supprimer le verrou.",
"Click to set user name for all messages": "Cliquez pour définir le nom d'utilisateur pour tous les messages",
"Persona Description": "Description du persona",
"Persona Description": "Description de la persona",
"Example: [{{user}} is a 28-year-old Romanian cat girl.]": "Exemple : [{{user}} est une fille chat roumaine de 28 ans.]",
"Tokens persona description": "Description des tokens",
"Position:": "Position :",
+9 -42
View File
@@ -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,12 @@ 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 },
);
}
if (power_user.auto_fix_generated_markdown) {
@@ -1918,10 +1889,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 -1
View File
@@ -96,7 +96,7 @@ function setNotePositionCommand(_, text) {
return;
}
$(`input[name="extension_floating_position"][value="${position}"]`).prop('checked', true).trigger('input').trigger('change');
$(`input[name="extension_floating_position"][value="${position}"]`).prop('checked', true).trigger('input');
toastr.info(t`Author's Note position updated`);
}
return Object.keys(validPositions).find(key => validPositions[key] == chat_metadata[metadata_keys.position]);
+3 -13
View File
@@ -126,17 +126,9 @@ export class AutoComplete {
});
textarea.addEventListener('blur', () => this.hide());
if (isFloating) {
textarea.addEventListener('scroll', () => {
if (this.isActive) {
this.updateFloatingPositionDebounced();
}
});
textarea.addEventListener('scroll', () => this.updateFloatingPositionDebounced());
}
window.addEventListener('resize', () => {
if (this.isActive) {
this.updatePositionDebounced();
}
});
window.addEventListener('resize', () => this.updatePositionDebounced());
}
/**
@@ -674,9 +666,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`;
+2 -2
View File
@@ -94,7 +94,7 @@ async function getBookmarkName({ isReplace = false, forceName = null } = {}) {
return `${cleanName} - ${bookmarkNameToken}${i}`;
}
const existingChats = await getExistingChatNames();
const suggestedName = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildCheckpointName, startIndex: 1 });
const suggestedName = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildCheckpointName });
const body = await renderTemplateAsync('createCheckpoint', { isReplace: isReplace, suggestedName: suggestedName });
let name = forceName ?? await Popup.show.input('Create Checkpoint', body, suggestedName);
@@ -212,7 +212,7 @@ export async function createBranch(mesId, { swipeId = null } = {}) {
return `${cleanName} - Branch #${i}`;
}
const existingChats = await getExistingChatNames();
const name = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildBranchName, startIndex: 1 });
const name = getUniqueName(mainChatName, (x) => existingChats.includes(x), { nameBuilder: buildBranchName });
if (!name) {
console.error('Could not generate a unique branch name.');
toastr.error('Could not generate a unique branch name.', 'Branch creation failed');
+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 -13
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';
@@ -18,11 +18,6 @@ const MODULE_NAME = 'caption';
const PROMPT_DEFAULT = 'What\'s in this image?';
const TEMPLATE_DEFAULT = '[{{user}} sends {{char}} a picture that contains: {{caption}}]';
const GOOGLE_MODEL_MIGRATIONS = new Map([
['gemini-3.1-flash-lite-preview', 'gemini-3.1-flash-lite'],
['gemini-3.1-flash-image-preview', 'gemini-3.1-flash-image'],
['gemini-3-pro-image-preview', 'gemini-3-pro-image'],
]);
/**
* Migrates old extension settings to the new format.
@@ -45,11 +40,6 @@ function migrateSettings() {
extension_settings.caption.multimodal_model = 'gpt-4-turbo';
}
if (['google', 'vertexai'].includes(extension_settings.caption.multimodal_api)) {
extension_settings.caption.multimodal_model = GOOGLE_MODEL_MIGRATIONS.get(extension_settings.caption.multimodal_model)
?? extension_settings.caption.multimodal_model;
}
if (!extension_settings.caption.multimodal_api) {
extension_settings.caption.multimodal_api = 'openai';
}
@@ -540,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;
}
}
+17 -16
View File
@@ -54,10 +54,6 @@
<option data-type="cohere" value="c4ai-aya-vision-8b">c4ai-aya-vision-8b</option>
<option data-type="cohere" value="c4ai-aya-vision-32b">c4ai-aya-vision-32b</option>
<option data-type="cohere" value="command-a-vision-07-2025">command-a-vision-07-2025</option>
<option data-type="openai" value="gpt-5.6">gpt-5.6</option>
<option data-type="openai" value="gpt-5.6-sol">gpt-5.6-sol</option>
<option data-type="openai" value="gpt-5.6-terra">gpt-5.6-terra</option>
<option data-type="openai" value="gpt-5.6-luna">gpt-5.6-luna</option>
<option data-type="openai" value="gpt-5.5">gpt-5.5</option>
<option data-type="openai" value="gpt-5.5-2026-04-23">gpt-5.5-2026-04-23</option>
<option data-type="openai" value="gpt-5.4">gpt-5.4</option>
@@ -100,10 +96,6 @@
<option data-type="openai" value="o4-mini-2025-04-16">o4-mini-2025-04-16</option>
<option data-type="openai" value="gpt-4.5-preview">gpt-4.5-preview</option>
<option data-type="openai" value="gpt-4.5-preview-2025-02-27">gpt-4.5-preview-2025-02-27</option>
<option data-type="anthropic" value="claude-fable-5">claude-fable-5</option>
<option data-type="anthropic" value="claude-opus-5">claude-opus-5</option>
<option data-type="anthropic" value="claude-sonnet-5">claude-sonnet-5</option>
<option data-type="anthropic" value="claude-opus-4-8">claude-opus-4-8</option>
<option data-type="anthropic" value="claude-opus-4-7">claude-opus-4-7</option>
<option data-type="anthropic" value="claude-opus-4-6">claude-opus-4-6</option>
<option data-type="anthropic" value="claude-opus-4-5">claude-opus-4-5</option>
@@ -113,16 +105,26 @@
<option data-type="anthropic" value="claude-sonnet-4-5-20250929">claude-sonnet-4-5-20250929</option>
<option data-type="anthropic" value="claude-haiku-4-5">claude-haiku-4-5</option>
<option data-type="anthropic" value="claude-haiku-4-5-20251001">claude-haiku-4-5-20251001</option>
<option data-type="anthropic" value="claude-opus-4-1">claude-opus-4-1</option>
<option data-type="anthropic" value="claude-opus-4-1-20250805">claude-opus-4-1-20250805</option>
<option data-type="anthropic" value="claude-opus-4-0">claude-opus-4-0</option>
<option data-type="anthropic" value="claude-opus-4-20250514">claude-opus-4-20250514</option>
<option data-type="anthropic" value="claude-sonnet-4-0">claude-sonnet-4-0</option>
<option data-type="anthropic" value="claude-sonnet-4-20250514">claude-sonnet-4-20250514</option>
<option data-type="google" value="gemini-3.5-flash">gemini-3.5-flash</option>
<option data-type="anthropic" value="claude-3-7-sonnet-latest">claude-3-7-sonnet-latest</option>
<option data-type="anthropic" value="claude-3-7-sonnet-20250219">claude-3-7-sonnet-20250219</option>
<option data-type="anthropic" value="claude-3-5-sonnet-latest">claude-3-5-sonnet-latest</option>
<option data-type="anthropic" value="claude-3-5-sonnet-20241022">claude-3-5-sonnet-20241022</option>
<option data-type="anthropic" value="claude-3-5-sonnet-20240620">claude-3-5-sonnet-20240620</option>
<option data-type="anthropic" value="claude-3-5-haiku-latest">claude-3-5-haiku-latest</option>
<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.1-pro-preview">gemini-3.1-pro-preview</option>
<option data-type="google" value="gemini-3.1-flash-lite">gemini-3.1-flash-lite</option>
<option data-type="google" value="gemini-3.1-flash-image">gemini-3.1-flash-image</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>
<option data-type="google" value="gemini-3-pro-preview">gemini-3-pro-preview</option>
<option data-type="google" value="gemini-3-pro-image">gemini-3-pro-image</option>
<option data-type="google" value="gemini-3-pro-image-preview">gemini-3-pro-image-preview</option>
<option data-type="google" value="gemini-3-flash-preview">gemini-3-flash-preview</option>
<option data-type="google" value="gemini-2.5-pro">gemini-2.5-pro</option>
<option data-type="google" value="gemini-2.5-pro-preview-06-05">gemini-2.5-pro-preview-06-05</option>
@@ -156,12 +158,11 @@
<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">gemini-3.1-flash-lite</option>
<option data-type="vertexai" value="gemini-3.1-flash-image">gemini-3.1-flash-image</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>
<option data-type="vertexai" value="gemini-3-pro-preview">gemini-3-pro-preview</option>
<option data-type="vertexai" value="gemini-3-pro-image">gemini-3-pro-image</option>
<option data-type="vertexai" value="gemini-3-pro-image-preview">gemini-3-pro-image-preview</option>
<option data-type="vertexai" value="gemini-3-flash-preview">gemini-3-flash-preview</option>
<option data-type="vertexai" value="gemini-2.5-pro">gemini-2.5-pro</option>
<option data-type="vertexai" value="gemini-2.5-flash">gemini-2.5-flash</option>
+33 -176
View File
@@ -18,8 +18,6 @@ import { generateWebLlmChatPrompt, isWebLlmSupported } from '../shared.js';
import { Popup, POPUP_RESULT } from '../../popup.js';
import { t } from '../../i18n.js';
import { removeReasoningFromString } from '../../reasoning.js';
import { macros } from '../../macros/macro-system.js';
import { MacrosParser } from '/scripts/macros.js';
export { MODULE_NAME };
/**
@@ -105,19 +103,6 @@ let lastServerResponseTime = 0;
/** @type {{[characterName: string]: string}} */
export let lastExpression = {};
/**
* Gets the current fallback expression, including the labels for when it is not set
* @returns {string|null}
*/
function getCurrentFallbackExpression() {
const expression = extension_settings?.expressions.fallback_expression;
const showEmojis = extension_settings?.expressions?.showDefault;
if (!expression && showEmojis) return OPTION_EMOJI_FALLBACK;
if (!expression) return OPTION_NO_FALLBACK;
return expression;
}
/**
* Returns a placeholder image object for a given expression
* @param {string} expression - The expression label
@@ -801,48 +786,13 @@ async function setSpriteSlashCommand({ type }, searchTerm) {
return label;
}
/**
* Get all the currently set expression labels.
* @param {Object} args
* @param {'true'|'false'|'only'} [args.custom] - Whether to filter out or return only custom expressions
* @param {'true'|'false'} [args.filter] - Filter the list to only include expressions that have available sprites for the current character
* @param {import('../../slash-commands/SlashCommandReturnHelper.js').SlashCommandReturnType} [args.return] - In which format must the expressions be returned
* @param {string} characterName
* @returns {Promise<string>}
*/
async function getExpressionListSlashCommand(args, characterName) {
const { custom, filter = 'true', return: returnType = 'pipe' } = args;
const expressions = await getExpressionsList({ filterAvailable: !isFalseBoolean(filter) });
const customExpressions = extension_settings?.expressions?.custom || [];
const expressionsMap = {
default: expressions.filter(expression => !customExpressions.includes(expression)),
custom: customExpressions,
all: expressions,
};
let expressionIndex = 'all';
if (custom === 'false') expressionIndex = 'default';
if (custom === 'only') expressionIndex = 'custom';
try {
return await slashCommandReturnHelper.doReturn(returnType, expressionsMap[expressionIndex], {
objectToStringFunc: list => list.join(', '),
});
} catch (err) {
console.error(err);
return '';
}
}
/**
* @param {string} expressionName - Label of the expression to set as fallback
*/
function setFallBackExpressionSlashCommand(args, expressionName) {
expressionName = expressionName.trim().toLowerCase();
if (!expressionName) return getCurrentFallbackExpression();
if (!expressionName) return extension_settings?.expressions?.fallback_expression || '';
const select = /** @type {HTMLSelectElement} */(document.getElementById('expression_fallback'));
const fallbackExpressions = Array
@@ -1201,24 +1151,15 @@ export async function getExpressionLabel(text, expressionsApi = extension_settin
}
}
/**
* @param {Object} [options]
* @param {string} [options.characterName] Filters last message to the one of the target character
*/
function getLastCharacterMessage({ characterName = '' } = {}) {
function getLastCharacterMessage() {
const context = getContext();
const reversedChat = context.chat.slice().reverse();
const ignoreCharName = !characterName;
for (let mes of reversedChat) {
if (mes.is_user || mes.is_system || mes.extra?.type === system_message_types.NARRATOR) {
continue;
}
if (!ignoreCharName && mes.name !== characterName) {
continue;
}
return { mes: mes.mes, name: mes.name, original_avatar: mes.original_avatar, force_avatar: mes.force_avatar };
}
@@ -1522,30 +1463,6 @@ export async function getExpressionsList({ filterAvailable = false } = {}) {
}
}
/**
* Gets the last expression used in the chat by the active character.
* @param {Object} [options]
* @param {string} [options.characterName] Filters last expression to the one of the target character instead
* @returns {string}
*/
function getLastExpression({ characterName = '' } = {}) {
if (typeof characterName !== 'string') throw new Error('Character name must be a string');
if (!characterName) {
characterName = characters[this_chid]?.avatar || '';
}
const char = findChar({ name: characterName, quiet: true });
const currentLastMessage = getLastCharacterMessage({ characterName });
const finalCharacterName = currentLastMessage?.name ?? char?.name ?? characterName;
const spriteFolderName = getSpriteFolderName(currentLastMessage, finalCharacterName);
const sprite = lastExpression[spriteFolderName.split('/')[0]] ?? '';
return sprite;
}
/**
* Selects a sprite from the given sprite folder for the given expression.
*
@@ -2434,15 +2351,15 @@ export async function init() {
typeList: [ARGUMENT_TYPE.STRING],
isRequired: false,
enumProvider: () => [
new SlashCommandEnumValue(OPTION_NO_FALLBACK, 'Sets the fallback expression to no image'),
new SlashCommandEnumValue(OPTION_EMOJI_FALLBACK, 'Sets the fallback expression to emojis'),
new SlashCommandEnumValue('#none', 'Sets the fallback expression to no image'),
new SlashCommandEnumValue('#emoji', 'Sets the fallback expression to emojis'),
...localEnumProviders.expressions(),
],
}),
],
helpString: `
<div>
Gets the currently selected global fallback expression.<br />
Gets the currently selected expression fallback for all characters.<br />
If a valid expression label is sent, it will be set as the new fallback.
</div>
<div>
@@ -2493,8 +2410,23 @@ export async function init() {
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'expression-last',
aliases: ['lastsprite'],
/** @type {(args: object, name: string) => string} */
callback: (_, name) => getLastExpression({ characterName: (name || '') }),
/** @type {(args: object, name: string) => Promise<string>} */
callback: async (_, name) => {
if (typeof name !== 'string') throw new Error('name must be a string');
if (!name) {
if (selected_group) {
toastr.error(t`In group chats, you must specify a character name.`, t`No character name specified`);
return '';
}
name = characters[this_chid]?.avatar;
}
const char = findChar({ name: name });
if (!char) toastr.warning(t`Couldn't find character ${name}.`, t`Character not found`);
const sprite = lastExpression[char?.name ?? name] ?? '';
return sprite;
},
returns: 'the last set expression for the named character.',
unnamedArgumentList: [
SlashCommandArgument.fromProps({
@@ -2508,14 +2440,23 @@ export async function init() {
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'expression-list',
aliases: ['expressions'],
callback: getExpressionListSlashCommand,
/** @type {(args: {return: string, filter: string}) => Promise<string>} */
callback: async (args) => {
let returnType =
/** @type {import('../../slash-commands/SlashCommandReturnHelper.js').SlashCommandReturnType} */
(args.return);
const list = await getExpressionsList({ filterAvailable: !isFalseBoolean(args.filter) });
return await slashCommandReturnHelper.doReturn(returnType ?? 'pipe', list, { objectToStringFunc: list => list.join(', ') });
},
namedArgumentList: [
SlashCommandNamedArgument.fromProps({
name: 'return',
description: 'The way how you want the return value to be provided',
typeList: [ARGUMENT_TYPE.STRING],
defaultValue: 'pipe',
enumList: slashCommandReturnHelper.enumList({ allowObject: true, allowPopup: true }),
enumList: slashCommandReturnHelper.enumList({ allowObject: true }),
forceEnum: true,
}),
SlashCommandNamedArgument.fromProps({
@@ -2525,21 +2466,6 @@ export async function init() {
enumList: commonEnumProviders.boolean('trueFalse')(),
defaultValue: 'true',
}),
SlashCommandNamedArgument.fromProps({
name: 'custom',
description: t`Whether to include, filter out or return only custom expressions`,
typeList: [
ARGUMENT_TYPE.STRING,
ARGUMENT_TYPE.BOOLEAN,
],
isRequired: false,
defaultValue: 'true',
enumList: [
new SlashCommandEnumValue('true', '(default) Custom expressions will be included in the result'),
new SlashCommandEnumValue('false', 'Custom expressions will not be included in the result'),
new SlashCommandEnumValue('only', 'Only custom expressions will be included in the result'),
],
}),
],
returns: 'The comma-separated list of available expressions, including custom expressions.',
helpString: 'Returns a list of available expressions, including custom expressions.',
@@ -2647,73 +2573,4 @@ export async function init() {
</div>
`,
}));
if (power_user.experimental_macro_engine) {
macros.register('defaultExpression', {
handler: getCurrentFallbackExpression,
category: macros.category.MISC,
description: 'Returns the global fallback expression.',
returns: 'Expression label',
exampleUsage: '{{defaultExpression}}',
});
macros.register('lastExpression', {
handler: function ({ args: [name = '{{char}}'], resolve }) {
try {
return getLastExpression({ characterName: resolve(name || '') });
} catch (error) {
console.error(error);
return '';
}
},
unnamedArgs: [{
name: 'name',
description: 'The name of the target character',
defaultValue: '{{char}}',
optional: true,
type: macros.valueType.STRING,
}],
delayArgResolution: true,
category: macros.category.MISC,
description: 'Returns the last expression used by the selected character. The currently active character is used if no character name is provided.',
returns: 'Expression label',
exampleUsage: [
'{{lastExpression}}',
'{{lastExpression::John}}',
'{{lastExpression::{{char}}}}',
],
});
macros.register('availableExpressions', {
handler: function () {
return getCachedExpressions().join(', ');
},
category: macros.category.MISC,
description: 'Returns a list with all the available expressions provided by the Classifier API.',
returns: 'Expression label list',
exampleUsage: '{{availableExpressions}}',
});
} else {
MacrosParser.registerMacro('defaultExpression',
getCurrentFallbackExpression,
t`Returns the global fallback expression.`,
);
MacrosParser.registerMacro('lastExpression',
() => {
try {
return getLastExpression();
} catch (error) {
console.error(error);
return '';
}
},
t`Returns the last expression used.`,
);
MacrosParser.registerMacro('availableExpressions',
() => getCachedExpressions().join(', '),
t`Returns a list with all the available expressions provided by the Classifier API.`,
);
}
}
@@ -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);
+6 -11
View File
@@ -1,7 +1,7 @@
import { CONNECT_API_MAP, createModelIcon, getRequestHeaders, substituteParams } from '../../script.js';
import { CONNECT_API_MAP, createModelIcon, getRequestHeaders } from '../../script.js';
import { extension_settings, openThirdPartyExtensionMenu } from '../extensions.js';
import { t } from '../i18n.js';
import { oai_settings, proxies, ZAI_ENDPOINT, 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';
@@ -117,19 +117,15 @@ export async function getMultimodalCaption(base64Img, prompt) {
}
requestBody.server_url = oai_settings.custom_url;
requestBody.custom_include_headers = substituteParams(oai_settings.custom_include_headers);
requestBody.custom_include_body = substituteParams(oai_settings.custom_include_body);
requestBody.custom_exclude_body = substituteParams(oai_settings.custom_exclude_body);
requestBody.custom_include_headers = oai_settings.custom_include_headers;
requestBody.custom_include_body = oai_settings.custom_include_body;
requestBody.custom_exclude_body = oai_settings.custom_exclude_body;
}
if (extension_settings.caption.multimodal_api === 'zai') {
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'],
@@ -344,7 +344,7 @@
<div data-sd-source="bfl">
<div class="flex-container flexnowrap alignItemsBaseline marginBot5">
<a href="https://api.bfl.ai/" target="_blank" rel="noopener noreferrer">
<a href="https://api.bfl.ml/" target="_blank" rel="noopener noreferrer">
<strong data-i18n="API Key">API Key</strong>
<i class="fa-solid fa-share-from-square"></i>
</a>
@@ -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),
-1
View File
@@ -52,7 +52,6 @@ export const macros = {
// enums
category: MacroCategory,
valueType: MacroValueType,
// shorthand functions
register: MacroRegistry.registerMacro.bind(MacroRegistry),
-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;
+9 -87
View File
@@ -133,7 +133,6 @@ const max_200k = 200 * 1000;
const max_256k = 256 * 1000;
const max_400k = 400 * 1000;
const max_1mil = 1000 * 1000;
const max_1050k = 1050 * 1000;
const max_2mil = 2000 * 1000;
const unlocked_max = max_2mil;
const oai_max_temp = 2.0;
@@ -268,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',
@@ -341,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],
@@ -437,7 +430,7 @@ const default_settings = {
sort_models: 'alphabetically',
group_models: false,
openai_model: 'gpt-4-turbo',
claude_model: 'claude-sonnet-5',
claude_model: 'claude-sonnet-4-5',
google_model: 'gemini-2.5-pro',
vertexai_model: 'gemini-2.5-pro',
ai21_model: 'jamba-large',
@@ -458,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',
@@ -2557,9 +2549,6 @@ function getReasoningEffort(settings = null, model = null) {
switch (settings.reasoning_effort) {
case reasoning_effort_types.auto:
return undefined;
case reasoning_effort_types.min:
case reasoning_effort_types.low:
return reasoning_effort_types.low;
case reasoning_effort_types.max:
return reasoning_effort_types.max;
default:
@@ -2595,7 +2584,7 @@ function getReasoningEffort(settings = null, model = null) {
}
if ([chat_completion_sources.OPENAI, chat_completion_sources.AZURE_OPENAI].includes(settings.chat_completion_source)) {
if (/^gpt-5\.(4|5|6)/.test(model)) {
if (/^gpt-5\.(4|5)/.test(model)) {
return 'none';
}
if (/^gpt-5/.test(model)) {
@@ -2605,11 +2594,6 @@ function getReasoningEffort(settings = null, model = null) {
return reasoning_effort_types.low;
case reasoning_effort_types.max:
if ([chat_completion_sources.OPENAI, chat_completion_sources.AZURE_OPENAI].includes(settings.chat_completion_source)
&& /^gpt-5\.6/.test(model)) {
// GPT-5.6 reserves "max" effort for the Responses API.
return 'xhigh';
}
return reasoning_effort_types.high;
default:
return settings.reasoning_effort;
@@ -2708,7 +2692,6 @@ export async function createGenerationParameters(settings, model, type, messages
const logprobsSupportedSources = [
chat_completion_sources.OPENAI,
chat_completion_sources.AZURE_OPENAI,
chat_completion_sources.OPENROUTER,
chat_completion_sources.CUSTOM,
chat_completion_sources.DEEPSEEK,
chat_completion_sources.XAI,
@@ -2873,9 +2856,9 @@ export async function createGenerationParameters(settings, model, type, messages
if (settings.chat_completion_source === chat_completion_sources.CUSTOM) {
generate_data.custom_url = settings.custom_url;
generate_data.custom_include_body = substituteParams(settings.custom_include_body);
generate_data.custom_exclude_body = substituteParams(settings.custom_exclude_body);
generate_data.custom_include_headers = substituteParams(settings.custom_include_headers);
generate_data.custom_include_body = settings.custom_include_body;
generate_data.custom_exclude_body = settings.custom_exclude_body;
generate_data.custom_include_headers = settings.custom_include_headers;
}
if (settings.chat_completion_source === chat_completion_sources.COHERE) {
@@ -2950,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;
}
@@ -3046,22 +3025,6 @@ export async function createGenerationParameters(settings, model, type, messages
}
}
// Claude Fable and Claude 5 generation models removed sampling parameters and reject
// them with HTTP 400, including via OpenAI-compatible proxies. Unanchored to also match
// prefixed ids like 'anthropic/claude-fable-5'.
if (/claude-(fable|opus-5|sonnet-5)/.test(model)) {
delete generate_data.temperature;
delete generate_data.top_p;
delete generate_data.top_k;
delete generate_data.frequency_penalty;
delete generate_data.presence_penalty;
// Keep reasoning_effort for the native Claude source, where the backend maps it to
// adaptive thinking; proxies may translate it into a thinking budget that Fable rejects.
if (settings.chat_completion_source !== chat_completion_sources.CLAUDE) {
delete generate_data.reasoning_effort;
}
}
if (jsonSchema) {
generate_data.json_schema = jsonSchema;
}
@@ -3266,7 +3229,6 @@ function parseChatCompletionLogprobs(data) {
: parseOpenAITextLogprobs(data.choices[0]?.logprobs);
case chat_completion_sources.OPENAI:
case chat_completion_sources.AZURE_OPENAI:
case chat_completion_sources.OPENROUTER:
case chat_completion_sources.DEEPSEEK:
case chat_completion_sources.XAI:
case chat_completion_sources.CUSTOM:
@@ -4220,12 +4182,6 @@ function migrateChatCompletionSettings(settings) {
{ oldKey: 'chat_completion_source', oldValue: 'palm', newKey: 'chat_completion_source', newValue: chat_completion_sources.MAKERSUITE },
{ oldKey: 'custom_prompt_post_processing', oldValue: custom_prompt_post_processing_types.CLAUDE, newKey: 'custom_prompt_post_processing', newValue: custom_prompt_post_processing_types.MERGE },
{ oldKey: 'ai21_model', oldValue: /^j2-/, newKey: 'ai21_model', newValue: 'jamba-large' },
{ oldKey: 'google_model', oldValue: 'gemini-3.1-flash-lite-preview', newKey: 'google_model', newValue: 'gemini-3.1-flash-lite' },
{ oldKey: 'vertexai_model', oldValue: 'gemini-3.1-flash-lite-preview', newKey: 'vertexai_model', newValue: 'gemini-3.1-flash-lite' },
{ oldKey: 'google_model', oldValue: 'gemini-3.1-flash-image-preview', newKey: 'google_model', newValue: 'gemini-3.1-flash-image' },
{ oldKey: 'vertexai_model', oldValue: 'gemini-3.1-flash-image-preview', newKey: 'vertexai_model', newValue: 'gemini-3.1-flash-image' },
{ oldKey: 'google_model', oldValue: 'gemini-3-pro-image-preview', newKey: 'google_model', newValue: 'gemini-3-pro-image' },
{ oldKey: 'vertexai_model', oldValue: 'gemini-3-pro-image-preview', newKey: 'vertexai_model', newValue: 'gemini-3-pro-image' },
{ oldKey: 'image_inlining', oldValue: false, newKey: 'media_inlining', newValue: false },
{ oldKey: 'image_inlining', oldValue: true, newKey: 'media_inlining', newValue: true },
{ oldKey: 'video_inlining', oldValue: true, newKey: 'media_inlining', newValue: true },
@@ -4451,7 +4407,7 @@ async function getStatusOpen() {
if (oai_settings.chat_completion_source === chat_completion_sources.CUSTOM) {
$('.model_custom_select').empty();
data.custom_url = oai_settings.custom_url;
data.custom_include_headers = substituteParams(oai_settings.custom_include_headers);
data.custom_include_headers = oai_settings.custom_include_headers;
}
if (oai_settings.chat_completion_source === chat_completion_sources.AZURE_OPENAI) {
@@ -4472,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`);
@@ -4942,23 +4894,6 @@ async function onLogitBiasPresetDeleteClick() {
saveSettingsDebounced();
}
/**
* Promise that resolves when the most recently started preset application has fully completed.
* The change handler defers the actual apply behind an event emission, so programmatic preset
* switches (e.g. /preset, connection profiles) must await this to sequence follow-up commands
* such as /api and /model correctly.
* @type {Promise<void>}
*/
let presetApplicationPromise = Promise.resolve();
/**
* Gets a promise that resolves when the currently pending preset application completes.
* @returns {Promise<void>} Promise that resolves when the preset is fully applied.
*/
export function getPresetApplicationPromise() {
return presetApplicationPromise;
}
// Load OpenAI preset settings
function onSettingsPresetChange() {
const presetNameBefore = oai_settings.preset_settings_openai;
@@ -4974,7 +4909,7 @@ function onSettingsPresetChange() {
const updateCheckbox = (selector, value) => $(selector).prop('checked', value).trigger('input', { source: 'preset' });
// Allow subscribers to alter the preset before applying deltas
presetApplicationPromise = eventSource.emit(event_types.OAI_PRESET_CHANGED_BEFORE, {
eventSource.emit(event_types.OAI_PRESET_CHANGED_BEFORE, {
preset: preset,
presetName: presetName,
settingsToUpdate: settingsToUpdate,
@@ -5035,7 +4970,6 @@ function getMaxContextOpenAI(value) {
/** @type {[RegExp, number][]} */
const contextMap = [
[/^gpt-5\.6/, max_1050k],
[/^gpt-5\.[45]/, max_1mil],
[/^gpt-5/, max_400k],
[/gpt-4\.1/, max_1mil],
@@ -5084,7 +5018,6 @@ function getGeminiMaxContext(model, isUnlocked) {
/** @type {[RegExp, number][]} */
const contextMap = [
[/gemini-2\.5-flash-image/, max_32k],
[/gemini-3\.1-flash-image/, max_128k],
[/gemini-3-pro-image/, max_64k],
[/gemini-(?:3[.\d]*|2\.(?:5|0))-(pro|flash)/, max_1mil],
[/(gemini-exp|learnlm-2\.0-flash|gemini-robotics)/, max_1mil],
@@ -5204,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,
@@ -5672,7 +5604,7 @@ async function onModelChange() {
if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
if (oai_settings.max_context_unlocked) {
$('#openai_max_context').attr('max', unlocked_max);
} else if (/^claude-(sonnet-4-5|sonnet-4-6|opus-4-6|opus-4-7|opus-4-8|fable|opus-5|sonnet-5)/.test(value)) {
} else if (/^claude-(sonnet-4-5|sonnet-4-6|opus-4-6|opus-4-7)/.test(value)) {
$('#openai_max_context').attr('max', max_1mil);
} else if (/^claude-(3|opus|haiku|sonnet)/.test(value)) {
$('#openai_max_context').attr('max', max_200k);
@@ -6002,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 },
};
@@ -6085,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');
@@ -6191,9 +6122,6 @@ export function isImageInliningSupported() {
'o4-mini',
// Claude
'claude-3',
'claude-fable',
'claude-opus-5',
'claude-sonnet-5',
'claude-opus-4',
'claude-sonnet-4',
'claude-haiku-4',
@@ -7265,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', () => {
+4 -11
View File
@@ -23,7 +23,7 @@ import { t } from './i18n.js';
import { instruct_presets } from './instruct-mode.js';
import { kai_settings } from './kai-settings.js';
import { convertNovelPreset } from './nai-settings.js';
import { getPresetApplicationPromise, oai_settings, openai_setting_names, openai_settings } from './openai.js';
import { oai_settings, openai_setting_names, openai_settings } from './openai.js';
import { POPUP_RESULT, POPUP_TYPE, Popup } from './popup.js';
import { context_presets, getContextSettings, power_user } from './power-user.js';
import { reasoning_templates } from './reasoning.js';
@@ -406,21 +406,14 @@ class PresetManager {
/**
* Selects a preset by option value.
* The returned promise resolves when the preset is fully applied. Chat Completion presets
* apply asynchronously after the change event, so callers that run follow-up commands
* (e.g. /preset followed by /api) must await it to avoid overriding their own changes.
* @param {string} value Preset option value
* @returns {Promise<void>}
*/
async selectPreset(value) {
selectPreset(value) {
const option = $(this.select).filter(function () {
return $(this).val() === value;
});
option.prop('selected', true);
$(this.select).val(value).trigger('change');
if (this.apiId === 'openai') {
await getPresetApplicationPromise();
}
}
/**
@@ -945,7 +938,7 @@ async function presetCommandCallback(_, name) {
const presetValue = presetManager.findPreset(exactMatch);
if (presetValue) {
await presetManager.selectPreset(presetValue);
presetManager.selectPreset(presetValue);
shouldReconnect && await waitForConnection();
}
}
@@ -968,7 +961,7 @@ async function presetCommandCallback(_, name) {
console.log('Found fuzzy preset match', fuzzyPresetName);
if (currentPreset !== fuzzyPresetName) {
await presetManager.selectPreset(fuzzyPresetValue);
presetManager.selectPreset(fuzzyPresetValue);
shouldReconnect && await waitForConnection();
}
}
+12 -51
View File
@@ -73,25 +73,6 @@ function getMessageFromJquery(element) {
return { messageId: messageId, message, messageBlock };
}
/**
* Collapses reasoning blocks that cannot be closed by their header.
* @param {JQuery<HTMLElement>} messageBlock Message block
*/
function closeReasoningDetailsWithoutContent(messageBlock) {
const details = messageBlock.find('.mes_reasoning_details');
if (details.attr('data-has-content') !== 'true') {
details.removeAttr('open');
}
}
/**
* Opens reasoning blocks only when they have visible content.
* @param {JQuery<HTMLElement>} details Reasoning details elements
*/
function openReasoningDetailsWithContent(details) {
details.filter('[data-has-content="true"]').attr('open', '');
}
/**
* Toggles the auto-expand state of reasoning blocks.
*/
@@ -99,7 +80,7 @@ function toggleReasoningAutoExpand() {
const reasoningBlocks = document.querySelectorAll('details.mes_reasoning_details');
reasoningBlocks.forEach((block) => {
if (block instanceof HTMLDetailsElement) {
block.open = power_user.reasoning.auto_expand && block.dataset.hasContent === 'true';
block.open = power_user.reasoning.auto_expand;
}
});
}
@@ -383,7 +364,7 @@ export class ReasoningHandler {
this.updateDom(messageId);
if (power_user.reasoning.auto_expand && this.messageReasoningDetailsDom.dataset.hasContent === 'true') {
if (power_user.reasoning.auto_expand && this.state !== ReasoningState.Hidden) {
this.messageReasoningDetailsDom.open = true;
}
}
@@ -570,12 +551,7 @@ export class ReasoningHandler {
setDatasetProperty(this.messageReasoningDetailsDom, 'type', this.type);
// Update the reasoning message
const rawReasoning = this.reasoningDisplayText ?? this.reasoning;
const reasoning = trimSpaces(rawReasoning);
// Keep whitespace-only saved reasoning editable without showing it as visible content.
const hasStoredReasoning = Boolean(this.reasoningDisplayText || this.reasoning);
const hasReasoningContent = Boolean(String(rawReasoning ?? '').trim());
setDatasetProperty(this.messageReasoningDetailsDom, 'hasContent', hasReasoningContent ? 'true' : null);
const reasoning = trimSpaces(this.reasoningDisplayText ?? this.reasoning);
const displayReasoning = messageFormatting(reasoning, '', false, false, messageId, {}, true);
if (power_user.stream_fade_in) {
@@ -587,8 +563,7 @@ export class ReasoningHandler {
// Update tooltip for hidden reasoning edit
/** @type {HTMLElement} */
const button = this.messageDom.querySelector('.mes_edit_add_reasoning');
const isHiddenLikeReasoning = this.state === ReasoningState.Hidden || (hasStoredReasoning && !hasReasoningContent);
button.title = isHiddenLikeReasoning ? t`Hidden reasoning - Add reasoning block` : t`Add reasoning block`;
button.title = this.state === ReasoningState.Hidden ? t`Hidden reasoning - Add reasoning block` : t`Add reasoning block`;
// Make sure that hidden reasoning headers are collapsed by default, to not show a useless edit button
if (this.state === ReasoningState.Hidden) {
@@ -959,9 +934,8 @@ function registerReasoningSlashCommands() {
closeMessageEditor('reasoning');
updateMessageBlock(messageId, message);
const details = $(`#chat [mesid="${messageId}"] .mes_reasoning_details`);
if (isTrueBoolean(String(args.collapse))) details.removeAttr('open');
if (isFalseBoolean(String(args.collapse))) openReasoningDetailsWithContent(details);
if (isTrueBoolean(String(args.collapse))) $(`#chat [mesid="${messageId}"] .mes_reasoning_details`).removeAttr('open');
if (isFalseBoolean(String(args.collapse))) $(`#chat [mesid="${messageId}"] .mes_reasoning_details`).attr('open', '');
return message.extra.reasoning;
},
}));
@@ -1160,7 +1134,7 @@ function registerReasoningSlashCommands() {
unnamedArgumentList: reasoningVisibilityArgs,
callback: (_args, value) => {
const details = getReasoningDetailsElements(value.toString());
if (details) openReasoningDetailsWithContent(details);
if (details) details.attr('open', '');
return '';
},
}));
@@ -1177,7 +1151,7 @@ function registerReasoningSlashCommands() {
const $el = $(this);
if ($el.attr('open') !== undefined) {
$el.removeAttr('open');
} else if ($el.attr('data-has-content') === 'true') {
} else {
$el.attr('open', '');
}
});
@@ -1224,8 +1198,8 @@ function setReasoningEventHandlers() {
$(document).on('click', '.mes_reasoning_header', function (e) {
const details = $(this).closest('.mes_reasoning_details');
// Keep click behavior aligned with CSS: only blocks with backing content can toggle or enter edit mode.
if (details.attr('data-has-content') !== 'true') {
// Along with the CSS rules to mark blocks not toggle-able when they are empty, prevent them from actually being toggled, or being edited
if (details.find('.mes_reasoning').is(':empty')) {
e.preventDefault();
return;
}
@@ -1254,10 +1228,6 @@ function setReasoningEventHandlers() {
return;
}
if (messageBlock.find('.reasoning_edit_textarea').length > 0) {
return;
}
const reasoning = String(message?.extra?.reasoning ?? '');
const chatElement = document.getElementById('chat');
const textarea = document.createElement('textarea');
@@ -1295,7 +1265,6 @@ function setReasoningEventHandlers() {
e.stopPropagation();
e.preventDefault();
$('.mes_reasoning_details[open]:not([data-has-content="true"])').removeAttr('open');
$('.mes_reasoning_details[open] .mes_reasoning_header').trigger('click');
});
@@ -1312,13 +1281,11 @@ function setReasoningEventHandlers() {
newReasoning = substituteParams(newReasoning);
textarea.remove();
if (newReasoning === message.extra.reasoning) {
closeReasoningDetailsWithoutContent(messageBlock);
return;
}
updateReasoningFromValue(message, newReasoning);
await saveChatConditional();
updateMessageBlock(messageId, message);
closeReasoningDetailsWithoutContent(messageBlock);
messageBlock.find('.mes_edit_done:visible').trigger('click');
await eventSource.emit(event_types.MESSAGE_REASONING_EDITED, messageId);
@@ -1335,7 +1302,6 @@ function setReasoningEventHandlers() {
messageBlock.find('.mes_reasoning_edit_cancel:visible').trigger('click');
updateReasoningUI(messageBlock);
closeReasoningDetailsWithoutContent(messageBlock);
});
$(document).on('click', '.mes_edit_add_reasoning', async function () {
@@ -1344,12 +1310,7 @@ function setReasoningEventHandlers() {
return;
}
const details = messageBlock.find('.mes_reasoning_details');
if (details.find('.reasoning_edit_textarea').length > 0) {
return;
}
if (message.extra.reasoning && details.attr('data-has-content') === 'true') {
if (message.extra.reasoning) {
toastr.info(t`Reasoning already exists.`, t`Edit Message`);
return;
}
@@ -1363,7 +1324,7 @@ function setReasoningEventHandlers() {
}
// Open the reasoning area so we can actually edit it
details.attr('open', '');
messageBlock.find('.mes_reasoning_details').attr('open', '');
messageBlock.find('.mes_reasoning_edit').trigger('click');
await saveChatConditional();
});
+11 -38
View File
@@ -38,7 +38,6 @@ import {
newAssistantChat,
online_status,
reloadCurrentChat,
refreshSwipeButtons,
removeMacros,
renameCharacter,
renameChat,
@@ -58,11 +57,11 @@ import {
swipe,
stopGeneration,
substituteParams,
syncMesToSwipe,
system_avatar,
system_message_types,
this_chid,
updateMessageElement,
updateSwipeCounter,
} from '../script.js';
import { SlashCommandParser } from './slash-commands/SlashCommandParser.js';
import { SlashCommandParserError } from './slash-commands/SlashCommandParserError.js';
@@ -71,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';
@@ -2971,9 +2970,9 @@ export function initDefaultSlashCommands() {
}));
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'tokens',
callback: async (_, text) => {
callback: (_, text) => {
if (text instanceof SlashCommandClosure || Array.isArray(text)) throw new Error(t`Unnamed argument cannot be a closure for command /tokens`);
return String(await getTokenCountAsync(text));
return getTokenCountAsync(text).then(count => String(count));
},
returns: t`number of tokens`,
unnamedArgumentList: [
@@ -3136,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')),
],
@@ -3170,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>
`,
}));
@@ -4617,7 +4615,6 @@ async function echoCallback(args, value) {
* @param {string} value - The swipe text to add (unnamed argument)
*/
async function addSwipeCallback(args, value) {
const lastMessageId = chat.length - 1;
const lastMessage = chat[chat.length - 1];
if (!lastMessage) {
@@ -4665,13 +4662,15 @@ async function addSwipeCallback(args, value) {
const newSwipeId = lastMessage.swipes.length - 1;
if (isTrueBoolean(args.switch)) {
await swipe(null, SWIPE_DIRECTION.RIGHT, { source: SWIPE_SOURCE.SLASH_COMMAND, repeated: false, forceMesId: lastMessageId, forceSwipeId: newSwipeId });
} else {
await updateSwipeCounter(lastMessageId, { message: lastMessage });
refreshSwipeButtons();
// Make sure ad-hoc changes to extras are saved before swiping away
syncMesToSwipe();
lastMessage.swipe_id = newSwipeId;
lastMessage.mes = lastMessage.swipes[newSwipeId];
lastMessage.extra = structuredClone(lastMessage.swipe_info?.[newSwipeId]?.extra ?? lastMessage.extra ?? {});
}
await saveChatConditional();
await reloadCurrentChat();
return String(newSwipeId);
}
@@ -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>
+2 -22
View File
@@ -49,7 +49,6 @@ const OPENROUTER_PROVIDERS = [
'Clarifai',
'Cloudflare',
'Cohere',
'Crucible',
'Crusoe',
'DeepInfra',
'DeepSeek',
@@ -81,17 +80,14 @@ const OPENROUTER_PROVIDERS = [
'Morph',
'NCompass',
'Nebius',
'Nex AGI',
'NextBit',
'Novita',
'Nvidia',
'OpenAI',
'OpenInference',
'Parasail',
'Perceptron',
'Perplexity',
'Phala',
'Poolside',
'Recraft',
'Reka',
'Relace',
@@ -216,7 +212,7 @@ const NANOGPT_PROVIDERS = [
},
{
'id': 'ionet',
'label': 'io.net',
'label': 'Io Net',
},
{
'id': 'inceptron',
@@ -260,11 +256,7 @@ const NANOGPT_PROVIDERS = [
},
{
'id': 'neuralwatt',
'label': 'NeuralWatt',
},
{
'id': 'tensorix',
'label': 'Tensorix',
'label': 'Neuralwatt',
},
{
'id': 'nextbit',
@@ -310,26 +302,14 @@ const NANOGPT_PROVIDERS = [
'id': 'together',
'label': 'Together',
},
{
'id': 'uomi',
'label': 'UOMI',
},
{
'id': 'venice',
'label': 'Venice',
},
{
'id': 'wafer',
'label': 'Wafer',
},
{
'id': 'wandb',
'label': 'Weights & Biases',
},
{
'id': 'xiaomi',
'label': 'Xiaomi',
},
{
'id': 'zai',
'label': 'Z.AI',
+4 -4
View File
@@ -552,7 +552,7 @@ export function getTokenCount(str, padding = undefined) {
* @deprecated Use counterWrapperOpenAIAsync instead.
*/
function counterWrapperOpenAI(text) {
const message = { content: text };
const message = { role: 'system', content: text };
return countTokensOpenAI(message, true);
}
@@ -562,7 +562,7 @@ function counterWrapperOpenAI(text) {
* @returns {Promise<number>} Token count.
*/
function counterWrapperOpenAIAsync(text) {
const message = { content: text };
const message = { role: 'system', content: text };
return countTokensOpenAIAsync(message, true);
}
@@ -801,7 +801,7 @@ export function countTokensOpenAI(messages, full = false) {
messages = [messages];
}
let token_count = 0;
let token_count = -1;
for (const message of messages) {
const model = getTokenizerModel();
@@ -851,7 +851,7 @@ export async function countTokensOpenAIAsync(messages, full = false) {
messages = [messages];
}
let token_count = 0;
let token_count = -1;
for (const message of messages) {
const model = getTokenizerModel();
+16 -37
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';
@@ -692,12 +692,13 @@ export function isElementInViewport(el) {
* @param {{ (name: string): boolean; }} exists Function to check if name exists.
* @param {Object} [options] The options.
* @param {((baseName: string, i: number) => string)|null} [options.nameBuilder=null] Function to build the name.
* Starts with the index provided by `startIndex` (default is 0). If not provided, uses `baseName` for index 0 and "${baseName} (${i})" for higher indices.
* Starts with the index provided by `startIndex` (default is 1). If not provided, uses "${baseName} (${i})".
* @param {number} [options.maxTries=1000] The maximum number of tries to find a unique name. Default is 1000.
* @param {number} [options.startIndex=0] The index to start with when building the name. Default is 0.
* @param {number} [options.startIndex=1] The index to start with when building the name. Default is 1.
* When set to 0, the intention is to also check if the basename (without applied index) is free.
* @returns {string|null} A unique name. Null if no unique name could be found in `maxTries`.
*/
export function getUniqueName(baseName, exists, { nameBuilder = null, maxTries = 1000, startIndex = 0 } = {}) {
export function getUniqueName(baseName, exists, { nameBuilder = null, maxTries = 1000, startIndex = 1 } = {}) {
nameBuilder ??= (baseName, i) => i === 0 ? baseName : `${baseName} (${i})`;
let i = startIndex;
let name;
@@ -2786,54 +2787,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 = '';
}
+28 -147
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');
}
});
@@ -4203,12 +4123,11 @@ async function renameWorldInfo(name, data) {
}
const entryPreviouslySelected = selected_world_info.findIndex((e) => e === oldName);
const retargetPersonaLore = power_user.persona_description_lorebook === oldName;
await saveWorldInfo(newName, data, true);
await deleteWorldInfo(oldName);
await updateWorldInfoLinks(oldName, newName, { retargetPersonaLore });
await updateWorldInfoLinks(oldName, newName);
if (entryPreviouslySelected !== -1) {
const wiElement = getWIElement(newName);
@@ -4226,10 +4145,9 @@ async function renameWorldInfo(name, data) {
* Retargets all character lore links from an old world info name to a new one, with an optional confirmation for primary lorebook links
* @param {string} oldName Previous WI file name
* @param {string} newName New WI file name
* @param {{ retargetPersonaLore?: boolean }} [options] Additional relink options
* @returns {Promise<void>}
*/
async function updateWorldInfoLinks(oldName, newName, { retargetPersonaLore } = {}) {
async function updateWorldInfoLinks(oldName, newName) {
const existingCharLores = world_info.charLore?.filter((e) => e.extraBooks.includes(oldName));
if (existingCharLores && existingCharLores.length > 0) {
existingCharLores.forEach((charLore) => {
@@ -4240,36 +4158,6 @@ async function updateWorldInfoLinks(oldName, newName, { retargetPersonaLore } =
saveSettingsDebounced();
}
// Update link for active persona
if (retargetPersonaLore) {
power_user.persona_description_lorebook = newName;
const object = getOrCreatePersonaDescriptor();
object.lorebook = newName;
setPersonaDescription();
saveSettingsDebounced();
}
// Update links for other personas
Object.keys(power_user.personas).forEach((persona) => {
if (user_avatar === persona) {
return;
}
const descriptor = power_user.persona_descriptions[persona];
if (!descriptor) {
return;
}
if (descriptor.lorebook === oldName) {
descriptor.lorebook = newName;
saveSettingsDebounced();
}
});
// update the world info key to the new name if it's still set to the old one
if (chat_metadata[METADATA_KEY] === oldName) {
chat_metadata[METADATA_KEY] = newName;
await saveMetadata();
}
// find all characters using the old lorebook name as their primary world
const linkedChIDs = [];
characters.forEach((character, chid) => {
@@ -4991,19 +4879,12 @@ export async function checkWorldInfo(chat, maxContext, isDryRun, globalScanData
console.debug(`[WI] Search done. Found ${activatedNow.size} possible entries.`);
// Sort the entries for the probability and the budget limit checks
let newEntries;
if (activatedNow.size > 1) {
const sortedEntriesIndex = new Map(sortedEntries.map((entry, index) => [entry, index]));
newEntries = [...activatedNow]
.sort((a, b) => {
const isASticky = timedEffects.isEffectActive('sticky', a) ? 1 : 0;
const isBSticky = timedEffects.isEffectActive('sticky', b) ? 1 : 0;
return isBSticky - isASticky
|| (sortedEntriesIndex.get(a) ?? -1) - (sortedEntriesIndex.get(b) ?? -1);
});
} else {
newEntries = [...activatedNow];
}
const newEntries = [...activatedNow]
.sort((a, b) => {
const isASticky = timedEffects.isEffectActive('sticky', a) ? 1 : 0;
const isBSticky = timedEffects.isEffectActive('sticky', b) ? 1 : 0;
return isBSticky - isASticky || sortedEntries.indexOf(a) - sortedEntries.indexOf(b);
});
let newContent = '';
+7 -10
View File
@@ -466,7 +466,7 @@ input[type='checkbox']:focus-visible {
align-items: baseline;
}
.mes_reasoning_details:not([data-has-content="true"]) .mes_reasoning_header {
.mes:has(.mes_reasoning:empty) .mes_reasoning_header {
cursor: default;
}
@@ -489,11 +489,10 @@ input[type='checkbox']:focus-visible {
.mes_reasoning_details:has(.reasoning_edit_textarea) .mes_reasoning_actions .mes_button:not(.edit_button),
.mes_reasoning_details:not(:has(.reasoning_edit_textarea)) .mes_reasoning_actions .edit_button,
.mes_block:has(.edit_textarea):has(.reasoning_edit_textarea) .mes_reasoning_actions,
.mes.reasoning:has(.mes_reasoning_details[data-has-content="true"]) .mes_edit_add_reasoning,
.mes:has(.mes_reasoning_details .reasoning_edit_textarea) .mes_edit_add_reasoning,
.mes_reasoning_details:not([data-has-content="true"]) .mes_reasoning_arrow,
.mes_reasoning_details:not([data-has-content="true"]) .mes_reasoning,
.mes_reasoning_details:not([data-has-content="true"]) .mes_reasoning_copy {
.mes.reasoning:not([data-reasoning-state="hidden"]) .mes_edit_add_reasoning,
.mes:has(.mes_reasoning:empty) .mes_reasoning_arrow,
.mes:has(.mes_reasoning:empty) .mes_reasoning,
.mes:has(.mes_reasoning:empty) .mes_reasoning_copy {
display: none;
}
@@ -501,10 +500,8 @@ input[type='checkbox']:focus-visible {
background-color: color-mix(in srgb, var(--SmartThemeQuoteColor) 33%, var(--SmartThemeBlurTintColor) 66%);
}
/** If hidden reasoning should not be shown, we hide all blocks that don't have content,
* except the one currently being edited.
*/
#chat:not([data-show-hidden-reasoning="true"]) .mes_reasoning_details:not([data-has-content="true"]):not(:has(.reasoning_edit_textarea)) {
/** If hidden reasoning should not be shown, we hide all blocks that don't have content */
#chat:not([data-show-hidden-reasoning="true"]):not(:has(.reasoning_edit_textarea)) .mes:has(.mes_reasoning:empty) .mes_reasoning_details {
display: none;
}
+8
View File
@@ -9,6 +9,7 @@ import { initConfig } from './config-init.js';
/**
* @typedef {object} CommandLineArguments Parsed command line arguments
* @property {string} masterPassword Master password for encrypting secrets (if not set, secrets will be stored in plaintext)
* @property {string} configPath Path to the config file
* @property {string} dataRoot Data root directory
* @property {number} port Port number
@@ -57,6 +58,7 @@ export class CommandLineParser {
return Object.freeze({
configPath: configPath,
dataRoot: dataPath,
masterPassword: '',
port: 8000,
listen: false,
listenAddressIPv6: '[::]',
@@ -119,6 +121,11 @@ export class CommandLineParser {
default: null,
describe: 'Path to the config file (only for standalone mode)',
})
.option('masterPassword', {
type: 'string',
default: null,
describe: 'Master password for encrypting secrets (if not set, secrets will be stored in plaintext)',
})
.option('enableIPv6', {
type: 'string',
default: null,
@@ -300,6 +307,7 @@ export class CommandLineParser {
const result = {
configPath: configPath,
dataRoot: dataRoot,
masterPassword: cliArguments.masterPassword ?? getConfigValue('masterPassword', defaultConfig.masterPassword),
port: cliArguments.port ?? getConfigValue('port', defaultConfig.port, 'number'),
listen: cliArguments.listen ?? getConfigValue('listen', defaultConfig.listen, 'boolean'),
listenAddressIPv6: cliArguments.listenAddressIPv6 ?? getConfigValue('listenAddress.ipv6', defaultConfig.listenAddressIPv6),
-9
View File
@@ -487,10 +487,6 @@ export const OPENAI_REASONING_EFFORT_MODELS = [
'gpt-5.4-nano-2026-03-17',
'gpt-5.5',
'gpt-5.5-2026-04-23',
'gpt-5.6',
'gpt-5.6-sol',
'gpt-5.6-terra',
'gpt-5.6-luna',
];
export const OPENAI_REASONING_EFFORT_MAP = {
@@ -565,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',
+20 -39
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';
@@ -233,17 +231,13 @@ async function sendClaudeRequest(request, response) {
const useTools = Array.isArray(request.body.tools) && request.body.tools.length > 0;
const useSystemPrompt = Boolean(request.body.use_sysprompt);
const convertedPrompt = convertClaudeMessages(request.body.messages, request.body.assistant_prefill, useSystemPrompt, useTools, getPromptNames(request));
// Unanchored to also match prefixed ids passed through proxies, e.g. 'anthropic/claude-fable-5'
const isFableModel = /claude-fable/.test(request.body.model);
// Claude 5 generation (opus-5, sonnet-5): adaptive-only thinking, sampling parameters removed, no prefill
const isClaude5Model = /^claude-(opus-5|sonnet-5)/.test(request.body.model);
const useThinking = /^claude-(3-7|opus-4|sonnet-4|haiku-4-5|opus-4-5|opus-4-6|sonnet-4-6|opus-4-7)/.test(request.body.model) || isFableModel || isClaude5Model;
const useWebSearch = (/^claude-(3-5|3-7|opus-4|sonnet-4|haiku-4-5|opus-4-5|opus-4-6|sonnet-4-6|opus-4-7)/.test(request.body.model) || isFableModel || isClaude5Model) && Boolean(request.body.enable_web_search);
const useThinking = /^claude-(3-7|opus-4|sonnet-4|haiku-4-5|opus-4-5|opus-4-6|sonnet-4-6|opus-4-7)/.test(request.body.model);
const useWebSearch = /^claude-(3-5|3-7|opus-4|sonnet-4|haiku-4-5|opus-4-5|opus-4-6|sonnet-4-6|opus-4-7)/.test(request.body.model) && Boolean(request.body.enable_web_search);
const isLimitedSampling = /^claude-(opus-4-1|sonnet-4-5|haiku-4-5|opus-4-5|opus-4-6|sonnet-4-6)/.test(request.body.model);
const useVerbosity = /^claude-(opus-4-5|opus-4-6|sonnet-4-6|opus-4-7|opus-4-8)/.test(request.body.model) || isFableModel || isClaude5Model;
const noPrefillModel = /^claude-(opus-4-6|sonnet-4-6|opus-4-7|opus-4-8)/.test(request.body.model) || isFableModel || isClaude5Model;
const isAdaptiveModel = /^claude-(opus-4-7|opus-4-8)/.test(request.body.model) || isFableModel || isClaude5Model || (enableAdaptiveThinking && /^claude-(opus-4-6|sonnet-4-6)/.test(request.body.model));
const noSamplingModel = /^claude-(opus-4-7|opus-4-8)/.test(request.body.model) || isFableModel || isClaude5Model;
const useVerbosity = /^claude-(opus-4-5|opus-4-6|sonnet-4-6|opus-4-7)/.test(request.body.model);
const noPrefillModel = /^claude-(opus-4-6|sonnet-4-6|opus-4-7)/.test(request.body.model);
const isAdaptiveModel = /^claude-(opus-4-7)/.test(request.body.model) || (enableAdaptiveThinking && /^claude-(opus-4-6|sonnet-4-6)/.test(request.body.model));
const noSamplingModel = /^claude-(opus-4-7)/.test(request.body.model);
let fixThinkingPrefill = false;
// Add custom stop sequences
const stopSequences = [];
@@ -327,13 +321,13 @@ async function sendClaudeRequest(request, response) {
}
const reasoningEffort = request.body.reasoning_effort;
const includeReasoning = Boolean(request.body.include_reasoning);
const budgetTokens = calculateClaudeBudgetTokens(requestBody.max_tokens, reasoningEffort, requestBody.stream, isAdaptiveModel);
// Adaptive thinking: returns a string effort level (like Gemini 3)
if (useThinking && typeof budgetTokens === 'string') {
fixThinkingPrefill = true;
requestBody.thinking = { type: 'adaptive' };
const includeReasoning = Boolean(request.body.include_reasoning);
if (noSamplingModel && includeReasoning) {
requestBody.thinking.display = 'summarized';
}
@@ -341,10 +335,6 @@ async function sendClaudeRequest(request, response) {
requestBody.output_config.effort = budgetTokens;
// top_k is not allowed in adaptive mode
delete requestBody.top_k;
} else if (useThinking && isFableModel && reasoningEffort === 'auto' && includeReasoning) {
// Fable auto thinking is already enabled, but readable summaries require an explicit display request.
fixThinkingPrefill = true;
requestBody.thinking = { type: 'adaptive', display: 'summarized' };
} else if (useThinking && Number.isInteger(budgetTokens)) {
// Traditional thinking: returns a numeric budget
fixThinkingPrefill = true;
@@ -495,8 +485,8 @@ async function sendMakerSuiteRequest(request, response) {
'gemini-2.0-flash-preview-image-generation',
'gemini-2.5-flash-image-preview',
'gemini-2.5-flash-image',
'gemini-3-pro-image',
'gemini-3.1-flash-image',
'gemini-3-pro-image-preview',
'gemini-3.1-flash-image-preview',
];
const isThinkingConfigModel = m => (/^gemini-2.5-(flash|pro)/.test(m) && !/-image(-preview)?$/.test(m)) || (/^gemini-3[.\d]*-(flash|pro)/.test(m));
@@ -1799,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;
@@ -2238,11 +2227,6 @@ router.post('/generate', async function (request, response) {
},
};
if (request.body.logprobs > 0) {
bodyParams['top_logprobs'] = request.body.logprobs;
bodyParams['logprobs'] = true;
}
if (request.body.min_p !== undefined) {
bodyParams['min_p'] = request.body.min_p;
}
@@ -2430,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();
+22 -69
View File
@@ -319,25 +319,12 @@ async function checkChatIntegrity(filePath, integritySlug) {
return true;
}
// If the chat file is empty, there is nothing that could be lost by overwriting it
if (fs.statSync(filePath).size === 0) {
return true;
}
// Parse the first line of the chat file as JSON. Strip a UTF-8 BOM an external editor may have added.
// Parse the first line of the chat file as JSON
const firstLine = await readFirstLine(filePath);
const jsonData = tryParse(String(firstLine ?? '').replace(/^\uFEFF/, ''));
// If the first line of a non-empty file is not a JSON object, the file may be corrupted or truncated.
// Fail the check so the client asks for an explicit overwrite confirmation instead of silently losing data.
if (typeof jsonData !== 'object' || jsonData === null || Array.isArray(jsonData)) {
console.warn(`File "${filePath}" is not empty, but its first line could not be parsed as a chat header. Overwriting it requires an explicit confirmation.`);
return false;
}
const jsonData = tryParse(firstLine);
const chatIntegrity = jsonData?.chat_metadata?.integrity;
// If the chat has no integrity metadata, assume it's intact (legacy chats created before integrity checks existed)
// If the chat has no integrity metadata, assume it's intact
if (!chatIntegrity) {
console.debug(`File "${filePath}" does not have integrity metadata matching "${integritySlug}". The integrity validation has been skipped.`);
return true;
@@ -370,66 +357,33 @@ async function checkChatIntegrity(filePath, integritySlug) {
* @typedef {(textArray: string[]) => boolean} ChatMatchFunction
*/
export async function getChatInfo(pathToFile, additionalData = {}, withMetadata = false, matcher = null) {
const parsedPath = path.parse(pathToFile);
const hasMatcher = (typeof matcher === 'function');
return new Promise(async (res) => {
const parsedPath = path.parse(pathToFile);
const stats = await fs.promises.stat(pathToFile);
const hasMatcher = (typeof matcher === 'function');
// A chat that is deleted while a scan is running is not an error: treat it like a corrupted chat and move on.
const chatVanished = () => {
console.warn('Chat file was deleted while it was being scanned:', pathToFile);
return { match: false };
};
const chatData = {
match: false,
file_id: parsedPath.name,
file_name: parsedPath.base,
file_size: formatBytes(stats.size),
chat_items: 0,
mes: '[The chat is empty]',
last_mes: stats.mtimeMs,
...additionalData,
};
let stats;
try {
stats = await fs.promises.stat(pathToFile);
} catch (error) {
if (error.code === 'ENOENT') {
return chatVanished();
if (stats.size === 0) {
res(chatData);
return;
}
throw error;
}
const chatData = {
match: false,
file_id: parsedPath.name,
file_name: parsedPath.base,
file_size: formatBytes(stats.size),
chat_items: 0,
mes: '[The chat is empty]',
last_mes: stats.mtimeMs,
...additionalData,
};
if (stats.size === 0) {
return chatData;
}
return new Promise((res, rej) => {
const fileStream = fs.createReadStream(pathToFile);
// The file can still disappear between the stat above and the stream opening
fileStream.on('error', (error) => {
if (error.code === 'ENOENT') {
res(chatVanished());
return;
}
rej(error);
});
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
// readline re-emits input stream errors; without a listener the emit throws
rl.on('error', (error) => {
if (error.code === 'ENOENT') {
res(chatVanished());
return;
}
rej(error);
});
let lastLine;
let itemCounter = 0;
let hasAnyMatch = false;
@@ -456,6 +410,8 @@ export async function getChatInfo(pathToFile, additionalData = {}, withMetadata
lastLine = line;
});
rl.on('close', () => {
rl.close();
if (lastLine) {
const jsonData = tryParse(lastLine);
if (jsonData && (jsonData.name || jsonData.character_name || jsonData.chat_metadata)) {
@@ -469,9 +425,6 @@ export async function getChatInfo(pathToFile, additionalData = {}, withMetadata
console.warn('Found an invalid or corrupted chat file:', pathToFile);
res({});
}
} else {
// The file was truncated after the stat reported a non-zero size
res({});
}
});
});
+9 -9
View File
@@ -556,6 +556,11 @@ async function downloadPygmalionCharacter(id) {
*/
function parseChubUrl(str) {
const splitStr = str.split('/');
const length = splitStr.length;
if (length < 2) {
return null;
}
let domainIndex = -1;
@@ -565,25 +570,20 @@ function parseChubUrl(str) {
}
});
const cleanUrl = domainIndex !== -1 ? splitStr.slice(domainIndex + 1) : splitStr;
const length = cleanUrl.length;
const lastTwo = domainIndex !== -1 ? splitStr.slice(domainIndex + 1) : splitStr;
if (length < 2) {
return null;
}
const firstPart = cleanUrl[0].toLowerCase();
const firstPart = lastTwo[0].toLowerCase();
if (firstPart === 'characters' || firstPart === 'lorebooks') {
const type = firstPart === 'characters' ? 'character' : 'lorebook';
const id = type === 'character' ? cleanUrl.slice(1).join('/') : cleanUrl.join('/');
const id = type === 'character' ? lastTwo.slice(1).join('/') : lastTwo.join('/');
return {
id: id,
type: type,
};
} else if (length === 2) {
return {
id: cleanUrl.join('/'),
id: lastTwo.join('/'),
type: 'character',
};
}
+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 -13
View File
@@ -6,7 +6,6 @@ import { decode } from 'html-entities';
import { readSecret, SECRET_KEYS } from './secrets.js';
import { trimV1 } from '../util.js';
import { setAdditionalHeaders } from '../additional-headers.js';
import { getUntrustedRequestAgent } from '../private-request-filter.js';
export const router = express.Router();
@@ -417,14 +416,8 @@ router.post('/visit', async (request, response) => {
throw new Error('Invalid port');
}
// Reject IP addresses. A bracketed IPv6 literal keeps its brackets in URL.hostname.
const bareHostname = urlObj.hostname.replace(/^\[|\]$/g, '');
if (ipRegex.v4({ exact: true }).test(bareHostname) || ipRegex.v6({ exact: true }).test(bareHostname)) {
throw new Error('Invalid hostname');
}
// Reject localhost and .localhost domains to prevent SSRF bypass
if (urlObj.hostname === 'localhost' || urlObj.hostname.endsWith('.localhost')) {
// Reject IP addresses
if (ipRegex.v4({ exact: true }).test(urlObj.hostname) || ipRegex.v6({ exact: true }).test(urlObj.hostname)) {
throw new Error('Invalid hostname');
}
} catch (error) {
@@ -434,10 +427,7 @@ router.post('/visit', async (request, response) => {
console.info('Visiting web URL', url);
// The URL checks above only guard the literal input. The agent enforces the actual network
// boundary: it blocks connections to private addresses after DNS resolution, on every redirect
// hop, and pins the connection to the validated IP to prevent DNS rebinding.
const result = await fetch(url, { headers: visitHeaders, agent: getUntrustedRequestAgent() });
const result = await fetch(url, { headers: visitHeaders });
if (!result.ok) {
console.error(`Visit failed ${result.status} ${result.statusText}`);
+109 -7
View File
@@ -3,7 +3,8 @@ import path from 'node:path';
import express from 'express';
import { sync as writeFileAtomicSync } from 'write-file-atomic';
import { color, getConfigValue, uuidv4 } from '../util.js';
import { color, getConfigValue, tryParse, uuidv4 } from '../util.js';
import { decryptObjectAes256, encryptObjectAes256, isEncryptedData } from '../util-crypto.js';
export const SECRETS_FILE = 'secrets.json';
export const SECRET_KEYS = {
@@ -111,6 +112,14 @@ export const allowKeysExposure = !!getConfigValue('allowKeysExposure', false, 'b
* SecretManager class to handle all secret operations
*/
export class SecretManager {
/**
* Master password for encrypting secrets, loaded from command-line arguments or config (if set)
* @type {string}
*/
static get #masterPassword() {
return String(globalThis.COMMAND_LINE_ARGS.masterPassword ?? '');
}
/**
* @param {import('../users.js').UserDirectoryList} directories
*/
@@ -120,13 +129,92 @@ export class SecretManager {
this.defaultSecrets = {};
}
/**
* Ensures that the secrets file is encrypted if a master password is set, and migrates existing secrets if necessary
* @param {import('../users.js').UserDirectoryList[]} directoriesLists List of user directories to check and encrypt secrets for
* @return {Promise<import('../users.js').UserDirectoryList[]>} The input list of user directories, returned for chaining purposes
*/
static async ensureEncryption(directoriesLists) {
if (!SecretManager.#masterPassword) {
console.warn();
console.warn(color.yellow('Warning: masterPassword is not set. Secrets will be stored in plaintext.'));
console.warn();
return directoriesLists;
}
console.info();
console.info(color.green('Master password is set.'), 'Make sure to keep it secure. It cannot be recovered if lost.');
console.info();
for (const directories of directoriesLists) {
const manager = new SecretManager(directories);
if (!manager._isSecretsFileEncrypted()) {
console.info(path.basename(directories.root), color.yellow('Encrypting existing secrets file with master password...'));
try {
const secrets = manager._readSecretsFile();
manager._writeSecretsFile(secrets);
console.info(path.basename(directories.root), color.green('Secrets file encrypted successfully.'));
} catch (error) {
console.error(path.basename(directories.root), color.red('Failed to encrypt secrets file:'), error);
}
}
}
return directoriesLists;
}
/**
* Prepares secret data for writing, applying encryption if masterPassword is set
* @param {object} data The secret data to prepare
* @return {string} The prepared JSON-serialized data, encrypted if masterPassword is set
*/
#prepareDataWrite(data) {
if (SecretManager.#masterPassword) {
const encryptedData = encryptObjectAes256(data, SecretManager.#masterPassword);
return JSON.stringify(encryptedData, null, 4);
}
return JSON.stringify(data, null, 4);
}
/**
* Parses secret data from a string, applying decryption if masterPassword is set
* @param {string} data The secret data string to parse
* @returns {object} The parsed secret data
*/
#parseDataRead(data) {
const parsedData = tryParse(data);
if (!parsedData) {
throw new Error('Secrets file is empty or contains invalid JSON');
}
if (SecretManager.#masterPassword) {
try {
// Data is not encrypted, return as-is (handles unencrypted secrets file when master password is set)
if (!isEncryptedData(parsedData)) {
return parsedData;
}
return decryptObjectAes256(parsedData, SecretManager.#masterPassword);
} catch (error) {
throw new Error('Decryption failed', { cause: error });
}
}
if (isEncryptedData(parsedData)) {
throw new Error('Secrets file appears to be encrypted but no master password is set. Unable to read secrets.');
}
return parsedData;
}
/**
* Ensures the secrets file exists, creating an empty one if necessary
* @private
*/
_ensureSecretsFile() {
if (!fs.existsSync(this.filePath)) {
writeFileAtomicSync(this.filePath, JSON.stringify(this.defaultSecrets), 'utf-8');
writeFileAtomicSync(this.filePath, this.#prepareDataWrite(this.defaultSecrets), 'utf-8');
}
}
@@ -138,7 +226,21 @@ export class SecretManager {
_readSecretsFile() {
this._ensureSecretsFile();
const fileContents = fs.readFileSync(this.filePath, 'utf-8');
return /** @type {SecretKeys} */ (JSON.parse(fileContents));
return /** @type {SecretKeys} */ (this.#parseDataRead(fileContents));
}
/**
* Checks if the secrets file is encrypted by attempting to parse it as JSON and checking for the encrypted format
* @returns {boolean} True if the secrets file is encrypted, false otherwise
*/
_isSecretsFileEncrypted() {
this._ensureSecretsFile();
const fileContents = fs.readFileSync(this.filePath, 'utf-8');
const parsedData = tryParse(fileContents);
if (parsedData) {
return isEncryptedData(parsedData);
}
return false;
}
/**
@@ -147,7 +249,7 @@ export class SecretManager {
* @param {SecretKeys} secrets
*/
_writeSecretsFile(secrets) {
writeFileAtomicSync(this.filePath, JSON.stringify(secrets, null, 4), 'utf-8');
writeFileAtomicSync(this.filePath, this.#prepareDataWrite(secrets), 'utf-8');
}
/**
@@ -383,8 +485,8 @@ export class SecretManager {
return;
}
const fileContents = fs.readFileSync(this.filePath, 'utf8');
const secrets = /** @type {FlatSecretKeys} */ (JSON.parse(fileContents));
const fileContents = /** @type {any} */ (this._readSecretsFile());
const secrets = /** @type {FlatSecretKeys} */ (fileContents);
const values = Object.values(secrets);
// Check if already migrated
@@ -501,7 +603,7 @@ export function migrateFlatSecrets(directoriesList) {
const manager = new SecretManager(directories);
manager.migrateFlatSecrets();
} catch (error) {
console.warn(color.red(`Failed to migrate secrets for ${directories.root}:`), error);
console.warn(color.red(`Failed to migrate secrets for ${path.basename(directories.root)}:`), error);
}
}
}
+3 -9
View File
@@ -586,7 +586,7 @@ comfy.post('/generate', async (request, response) => {
/** @type {any} */
const data = await promptResult.json();
const id = data.prompt_id;
const historyUrl = new URL(urlJoin(request.body.url, `/history/${id}`));
const historyUrl = new URL(urlJoin(request.body.url, '/history'));
while (true) {
const result = await fetch(historyUrl);
if (!result.ok) {
@@ -1528,7 +1528,7 @@ bfl.post('/generate', async (request, response) => {
console.debug('BFL request:', requestBody);
const result = await fetch(`https://api.bfl.ai/v1/${request.body.model}`, {
const result = await fetch(`https://api.bfl.ml/v1/${request.body.model}`, {
method: 'POST',
body: JSON.stringify(requestBody),
headers: {
@@ -1545,18 +1545,12 @@ bfl.post('/generate', async (request, response) => {
/** @type {any} */
const taskData = await result.json();
const { id } = taskData;
const pollingUrl = taskData.polling_url ?? `https://api.bfl.ai/v1/get_result?id=${id}`;
const MAX_ATTEMPTS = 100;
for (let i = 0; i < MAX_ATTEMPTS; i++) {
await delay(2500);
// The bfl.ai API requires authentication on the polling request as well
const statusResult = await fetch(pollingUrl, {
headers: {
'x-key': key,
},
});
const statusResult = await fetch(`https://api.bfl.ml/v1/get_result?id=${id}`);
if (!statusResult.ok) {
const text = await statusResult.text();
+9 -9
View File
@@ -12,9 +12,10 @@ import { Tokenizer } from '@agnai/web-tokenizers';
import { SentencePieceProcessor } from '@agnai/sentencepiece-js';
import tiktoken from 'tiktoken';
import { convertClaudePrompt } from '../prompt-converters.js';
import { TEXTGEN_TYPES } from '../constants.js';
import { setAdditionalHeaders } from '../additional-headers.js';
import { getConfigValue, isValidUrl, trimV1 } from '../util.js';
import { getConfigValue, isValidUrl } from '../util.js';
/**
* @typedef { (req: import('express').Request, res: import('express').Response) => Promise<any> } TokenizationHandler
@@ -544,14 +545,15 @@ export function getTiktokenTokenizer(model) {
* @returns {number} Number of tokens
*/
export function countWebTokenizerTokens(tokenizer, messages) {
const jsonBody = messages.flatMap(x => Object.values(x)).join('\n\n');
// Should be fine if we use the old conversion method instead of the messages API one i think?
const convertedPrompt = convertClaudePrompt(messages, false, '', false, false, '', false);
// Fallback to strlen estimation
if (!tokenizer) {
return guesstimate(jsonBody);
return guesstimate(convertedPrompt);
}
const count = tokenizer.encode(jsonBody).length;
const count = tokenizer.encode(convertedPrompt).length;
return count;
}
@@ -1086,12 +1088,12 @@ 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:
url += '/v1/token/encode';
args.body = JSON.stringify({ 'text': text, 'add_bos_token': false, 'encode_special_tokens': false });
args.body = JSON.stringify({ 'text': text, 'add_bos_token': false });
break;
case TEXTGEN_TYPES.KOBOLDCPP:
url += '/api/extra/tokencount';
@@ -1109,12 +1111,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);
}
});
+1 -33
View File
@@ -196,35 +196,6 @@ class PrivateRequestAgent extends Agent {
}
}
/**
* Whether requests to untrusted URLs should follow the global agent chain instead of the strict agent:
* either the private request filter is enabled (the global agents filter with the user's configured
* whitelist), or a request proxy owns outbound routing and a direct connection would bypass it.
* @type {boolean}
*/
let untrustedFilteringDelegated = false;
/** @type {PrivateRequestAgent|null} */
let strictAgent = null;
/**
* Get the agent to use for outbound requests to untrusted, user-supplied URLs (e.g. /api/search/visit).
* Returns a strict agent that blocks all private addresses at connection time, including on redirect hops,
* regardless of whether the private request filter is enabled. Returns undefined when the global agent
* chain already handles these requests (private request filter enabled, or request proxy owns routing),
* so the default agent selection applies.
* @returns {PrivateRequestAgent|undefined} The agent to pass to the outbound request, or undefined.
*/
export function getUntrustedRequestAgent() {
if (untrustedFilteringDelegated) {
return undefined;
}
if (!strictAgent) {
strictAgent = new PrivateRequestAgent({ privateAddressWhitelist: [], logBlocked: true, logAllowed: false, allowUnresolvedHosts: false, enableKeepAlive: false });
}
return strictAgent;
}
/**
* Initialize the private request filter by replacing the global HTTP and HTTPS agents with an instance of PrivateRequestAgent.
* @param {object} options Options for initializing the private request filter.
@@ -235,11 +206,8 @@ export function getUntrustedRequestAgent() {
* @param {boolean} options.logAllowed Whether to log allowed requests to the console.
* @param {boolean} options.allowUnresolvedHosts Whether to allow requests to hosts that cannot be resolved.
* @param {boolean} options.enableKeepAlive Whether to enable HTTP/HTTPS keep-alive.
* @param {boolean} [options.requestProxyEnabled] Whether a request proxy is enabled and owns outbound routing.
*/
export default function initPrivateRequestFilter({ listen, enabled, privateAddressWhitelist, logBlocked, logAllowed, allowUnresolvedHosts, enableKeepAlive, requestProxyEnabled }) {
untrustedFilteringDelegated = !!enabled || !!requestProxyEnabled;
export default function initPrivateRequestFilter({ listen, enabled, privateAddressWhitelist, logBlocked, logAllowed, allowUnresolvedHosts, enableKeepAlive }) {
if (!enabled) {
if (listen) {
console.warn();
+2 -2
View File
@@ -72,7 +72,7 @@ import { checkForNewContent } from './endpoints/content-manager.js';
import { init as settingsInit } from './endpoints/settings.js';
import { redirectDeprecatedEndpoints, ServerStartup, setupPrivateEndpoints } from './server-startup.js';
import { diskCache } from './endpoints/characters.js';
import { migrateFlatSecrets } from './endpoints/secrets.js';
import { migrateFlatSecrets, SecretManager } from './endpoints/secrets.js';
import { migrateGroupChatsMetadataFormat } from './endpoints/groups.js';
// Work around a node v20.0.0, v20.1.0, and v20.2.0 bug. The issue was fixed in v20.3.0.
@@ -343,7 +343,6 @@ async function preSetupTasks() {
logAllowed: !!getConfigValue('privateAddressWhitelist.log.allowedRequests', false, 'boolean'),
allowUnresolvedHosts: !!getConfigValue('privateAddressWhitelist.allowUnresolvedHosts', false, 'boolean'),
enableKeepAlive: cliArgs.enableKeepAlive,
requestProxyEnabled: !!cliArgs.requestProxyEnabled,
};
initPrivateRequestFilter(requestFilterOptions);
@@ -480,6 +479,7 @@ function setDnsResolutionOrder() {
initUserStorage(globalThis.DATA_ROOT)
.then(setDnsResolutionOrder)
.then(ensurePublicDirectoriesExist)
.then(SecretManager.ensureEncryption.bind(SecretManager))
.then(migrateUserData)
.then(migrateSystemPrompts)
.then(migratePublicOverrides)
+72
View File
@@ -0,0 +1,72 @@
import crypto from 'node:crypto';
const SALT_LENGTH = 32;
const KEY_LENGTH = 32;
/**
* @typedef {object} EncryptedData
* @property {string} salt Hex string of the salt used for key derivation
* @property {string} iv Hex string of the initialization vector used for encryption
* @property {string} encrypted Hex string of the encrypted data
* @property {string} authTag Hex string of the authentication tag from encryption
*/
/**
* Decrypts data encrypted with AES-256-OCB using the provided key.
* The key is derived from the password using scrypt.
* @param {EncryptedData} data Encrypted data in the format { salt, iv, encrypted, authTag }
* @param {string} keyString Encryption key as a UTF-8 string
* @returns {any} Decrypted data
*/
export function decryptObjectAes256(data, keyString) {
const salt = new Uint8Array(Buffer.from(data.salt, 'hex'));
const iv = new Uint8Array(Buffer.from(data.iv, 'hex'));
const key = new Uint8Array(crypto.scryptSync(keyString, salt, KEY_LENGTH));
const decipher = crypto.createDecipheriv('aes-256-ocb', key, iv, { authTagLength: 16 });
decipher.setAuthTag(new Uint8Array(Buffer.from(data.authTag, 'hex')));
const decrypted = decipher.update(data.encrypted, 'hex', 'utf8') + decipher.final('utf8');
return JSON.parse(decrypted);
}
/**
* Encrypts data using AES-256-OCB with the provided key.
* The key is derived from the password using scrypt with a random salt.
* @param {any} data JSON-serializable data to encrypt
* @param {string} keyString Encryption key as a UTF-8 string
* @returns {EncryptedData} Encrypted data in the format { salt, iv, encrypted, authTag }
*/
export function encryptObjectAes256(data, keyString) {
const salt = new Uint8Array(crypto.randomBytes(SALT_LENGTH));
const iv = new Uint8Array(crypto.randomBytes(12));
const key = new Uint8Array(crypto.scryptSync(keyString, salt, KEY_LENGTH));
const cipher = crypto.createCipheriv('aes-256-ocb', key, iv, { authTagLength: 16 });
const encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex') + cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
const saltString = Buffer.from(salt).toString('hex');
const ivString = Buffer.from(iv).toString('hex');
return { salt: saltString, iv: ivString, encrypted, authTag };
}
/**
* Checks if the given object is an encrypted data object by verifying it has the required properties and that they are valid hex strings.
* @param {EncryptedData} data Data object to check
* @returns {boolean} True if the data is in the format of encrypted data, false otherwise
*/
export function isEncryptedData(data) {
if (!data || typeof data !== 'object' || Array.isArray(data)) {
return false;
}
const requiredProps = ['salt', 'iv', 'encrypted', 'authTag'];
for (const prop of requiredProps) {
if (!Object.hasOwn(data, prop)) {
return false;
}
const value = data[prop];
if (typeof value !== 'string' || !/^[0-9a-fA-F]+$/.test(value)) {
return false;
}
}
return true;
}
+14 -23
View File
@@ -666,7 +666,18 @@ export function removeOldBackups(directory, prefix, limit = null) {
* @returns {string[]} List of image file names
*/
export function getImages(directoryPath, sortBy = 'name', type = MEDIA_REQUEST_TYPE.IMAGE) {
const files = fs
function getSortFunction() {
switch (sortBy) {
case 'name':
return Intl.Collator().compare;
case 'date':
return (a, b) => fs.statSync(path.join(directoryPath, a)).mtimeMs - fs.statSync(path.join(directoryPath, b)).mtimeMs;
default:
return (_a, _b) => 0;
}
}
return fs
.readdirSync(directoryPath, { withFileTypes: true })
.filter(dirent => dirent.isFile())
.map(dirent => dirent.name)
@@ -685,28 +696,8 @@ export function getImages(directoryPath, sortBy = 'name', type = MEDIA_REQUEST_T
return true;
}
return false;
});
switch (sortBy) {
case 'name':
return files.sort(Intl.Collator().compare);
case 'date': {
const mtimes = new Map();
for (const file of files) {
try {
mtimes.set(file, fs.statSync(path.join(directoryPath, file)).mtimeMs);
} catch (err) {
if (err?.code !== 'ENOENT') {
throw err;
}
mtimes.set(file, 0);
}
}
return files.sort((a, b) => mtimes.get(a) - mtimes.get(b));
}
default:
return files;
}
})
.sort(getSortFunction());
}
/**
-2
View File
@@ -12,8 +12,6 @@ module.exports = {
env: {
es6: true,
node: true,
browser: true,
jquery: true,
'jest/globals': true,
},
parserOptions: {
-102
View File
@@ -1,102 +0,0 @@
import { beforeAll, beforeEach, afterEach, describe, test, expect, jest } from '@jest/globals';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// chats.js reads these config values at module load. Environment variables take
// precedence over config.yaml, so the module imports without a config file.
process.env.SILLYTAVERN_BACKUPS_CHAT_ENABLED = 'false';
process.env.SILLYTAVERN_BACKUPS_CHAT_MAXTOTALBACKUPS = '-1';
process.env.SILLYTAVERN_BACKUPS_CHAT_THROTTLEINTERVAL = '0';
process.env.SILLYTAVERN_BACKUPS_CHAT_CHECKINTEGRITY = 'true';
/** @type {import('../src/endpoints/chats.js')} */
let chats;
beforeAll(async () => {
chats = await import('../src/endpoints/chats.js');
});
function makeChatJsonl() {
return [
JSON.stringify({ user_name: 'User', character_name: 'Char', chat_metadata: { note: 'meta' } }),
JSON.stringify({ name: 'Char', is_user: false, mes: 'First message', send_date: '2026-01-01T00:00:00.000Z' }),
JSON.stringify({ name: 'User', is_user: true, mes: 'Second message', send_date: '2026-01-02T00:00:00.000Z' }),
].join('\n');
}
describe('getChatInfo', () => {
let tmpDir;
let chatFile;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'st-chat-info-'));
chatFile = path.join(tmpDir, 'chat.jsonl');
});
afterEach(() => {
jest.restoreAllMocks();
fs.rmSync(tmpDir, { recursive: true, force: true });
});
test('reads info from a normal chat file', async () => {
fs.writeFileSync(chatFile, makeChatJsonl());
const info = await chats.getChatInfo(chatFile, {}, true);
expect(info.file_id).toBe('chat');
expect(info.file_name).toBe('chat.jsonl');
expect(info.chat_items).toBe(2);
expect(info.mes).toBe('Second message');
expect(info.last_mes).toBe('2026-01-02T00:00:00.000Z');
expect(info.match).toBe(true);
expect(info.chat_metadata).toEqual({ note: 'meta' });
});
test('returns defaults for an empty chat file', async () => {
fs.writeFileSync(chatFile, '');
const info = await chats.getChatInfo(chatFile);
expect(info.file_name).toBe('chat.jsonl');
expect(info.chat_items).toBe(0);
expect(info.mes).toBe('[The chat is empty]');
expect(info.match).toBe(false);
});
test('applies the matcher against message content', async () => {
fs.writeFileSync(chatFile, makeChatJsonl());
const matching = await chats.getChatInfo(chatFile, {}, false, lines => lines.some(l => l.includes('Second')));
expect(matching.match).toBe(true);
const nonMatching = await chats.getChatInfo(chatFile, {}, false, lines => lines.some(l => l.includes('nope')));
expect(nonMatching.match).toBe(false);
});
test('resolves without match when the file was already deleted', async () => {
const info = await chats.getChatInfo(path.join(tmpDir, 'gone.jsonl'));
expect(info).toEqual({ match: false });
});
test('resolves without match when the file is deleted between stat and read', async () => {
// Simulate the race: stat succeeds, but the file is gone when the stream opens
jest.spyOn(fs.promises, 'stat').mockResolvedValue(/** @type {any} */({ size: 100, mtimeMs: 1_000_000 }));
const info = await chats.getChatInfo(path.join(tmpDir, 'ghost.jsonl'));
expect(info).toEqual({ match: false });
});
test('resolves instead of hanging when the file is truncated between stat and read', async () => {
// Simulate the race: stat reports content, but the file is empty when read
fs.writeFileSync(chatFile, '');
jest.spyOn(fs.promises, 'stat').mockResolvedValue(/** @type {any} */({ size: 100, mtimeMs: 1_000_000 }));
const info = await chats.getChatInfo(chatFile);
expect(info).toEqual({});
});
test('rejects with the original error for non-ENOENT stat failures', async () => {
const eacces = Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });
jest.spyOn(fs.promises, 'stat').mockRejectedValue(eacces);
await expect(chats.getChatInfo(chatFile)).rejects.toThrow('EACCES');
});
test('resolves an empty object for a corrupted chat file', async () => {
fs.writeFileSync(chatFile, 'not json at all\nstill not json');
const info = await chats.getChatInfo(chatFile);
expect(info).toEqual({});
});
});
-167
View File
@@ -1,167 +0,0 @@
import { beforeAll, beforeEach, afterEach, describe, test, expect } from '@jest/globals';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// chats.js reads these config values at module load. Environment variables take
// precedence over config.yaml, so setting them here lets the module import
// without a config file present. The throttle interval is zeroed so lodash
// throttle timers don't keep the Jest process alive.
process.env.SILLYTAVERN_BACKUPS_CHAT_ENABLED = 'false';
process.env.SILLYTAVERN_BACKUPS_CHAT_MAXTOTALBACKUPS = '-1';
process.env.SILLYTAVERN_BACKUPS_CHAT_THROTTLEINTERVAL = '0';
process.env.SILLYTAVERN_BACKUPS_CHAT_CHECKINTEGRITY = 'true';
/** @type {import('../src/endpoints/chats.js')} */
let chats;
beforeAll(async () => {
chats = await import('../src/endpoints/chats.js');
});
const BOM = String.fromCharCode(0xFEFF);
const SLUG = '1e6905db-bab6-4901-913b-06d18cab5a8f';
const OTHER_SLUG = 'f1c1d103-464a-418a-a643-f9dab81589b9';
/**
* Builds a chat array like the client sends it.
* @param {string|null} slug Integrity slug for the header, or null for none
* @returns {object[]} Chat array
*/
function makeChat(slug) {
const metadata = slug ? { integrity: slug } : {};
return [
{ user_name: 'User', character_name: 'Char', chat_metadata: metadata },
{ name: 'Char', is_user: false, mes: 'Hello' },
];
}
/**
* Serializes a chat array the same way trySaveChat does.
* @param {object[]} chatData Chat array
* @returns {string} JSONL string
*/
function toJsonl(chatData) {
return chatData.map(m => JSON.stringify(m)).join('\n');
}
describe('trySaveChat integrity check', () => {
let tmpDir;
let chatFile;
let backupDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'st-chat-integrity-'));
chatFile = path.join(tmpDir, 'chat.jsonl');
backupDir = path.join(tmpDir, 'backups');
fs.mkdirSync(backupDir);
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
function save(chatData, { force = false } = {}) {
return chats.trySaveChat(chatData, chatFile, force, 'default-user', 'Char', backupDir);
}
test('writes a new file when none exists', async () => {
const chatData = makeChat(SLUG);
await save(chatData);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(chatData));
});
test('overwrites when the integrity slug matches', async () => {
fs.writeFileSync(chatFile, toJsonl(makeChat(SLUG)));
const newChat = makeChat(SLUG);
newChat[1].mes = 'Updated';
await save(newChat);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(newChat));
});
test('refuses to overwrite when the integrity slug mismatches and keeps the original bytes', async () => {
const originalBytes = toJsonl(makeChat(SLUG));
fs.writeFileSync(chatFile, originalBytes);
await expect(save(makeChat(OTHER_SLUG))).rejects.toThrow(/integrity check failed/i);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(originalBytes);
});
test('overwrites a legacy chat whose header has no integrity metadata', async () => {
const legacyHeader = JSON.stringify({ user_name: 'User', character_name: 'Char', create_date: '2023-01-01' });
fs.writeFileSync(chatFile, legacyHeader + '\n' + JSON.stringify({ name: 'Char', mes: 'Old' }));
const newChat = makeChat(SLUG);
await save(newChat);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(newChat));
});
test('overwrites an empty file', async () => {
fs.writeFileSync(chatFile, '');
const newChat = makeChat(SLUG);
await save(newChat);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(newChat));
});
test('refuses to overwrite a non-empty file with an unparseable first line and keeps the original bytes', async () => {
const originalBytes = 'this is not json{{{';
fs.writeFileSync(chatFile, originalBytes);
await expect(save(makeChat(SLUG))).rejects.toThrow(/integrity check failed/i);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(originalBytes);
});
test('refuses to overwrite a truncated header and keeps the original bytes', async () => {
const originalBytes = toJsonl(makeChat(SLUG)).slice(0, 25);
fs.writeFileSync(chatFile, originalBytes);
await expect(save(makeChat(SLUG))).rejects.toThrow(/integrity check failed/i);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(originalBytes);
});
test('refuses to overwrite when the first line parses to a non-object', async () => {
const originalBytes = '42\n' + JSON.stringify({ name: 'Char', mes: 'Orphan' });
fs.writeFileSync(chatFile, originalBytes);
await expect(save(makeChat(SLUG))).rejects.toThrow(/integrity check failed/i);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(originalBytes);
});
test('refuses to overwrite when the file starts with a blank line but has content below', async () => {
const originalBytes = '\n' + toJsonl(makeChat(SLUG));
fs.writeFileSync(chatFile, originalBytes);
await expect(save(makeChat(SLUG))).rejects.toThrow(/integrity check failed/i);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(originalBytes);
});
test('ignores a UTF-8 BOM in front of a valid matching header', async () => {
fs.writeFileSync(chatFile, BOM + toJsonl(makeChat(SLUG)));
const newChat = makeChat(SLUG);
newChat[1].mes = 'Updated';
await save(newChat);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(newChat));
});
test('still checks the integrity slug behind a UTF-8 BOM', async () => {
const originalBytes = BOM + toJsonl(makeChat(SLUG));
fs.writeFileSync(chatFile, originalBytes);
await expect(save(makeChat(OTHER_SLUG))).rejects.toThrow(/integrity check failed/i);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(originalBytes);
});
test('force overwrites a corrupted file when the user confirmed', async () => {
fs.writeFileSync(chatFile, 'this is not json{{{');
const newChat = makeChat(SLUG);
await save(newChat, { force: true });
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(newChat));
});
test('force overwrites a mismatching file when the user confirmed', async () => {
fs.writeFileSync(chatFile, toJsonl(makeChat(SLUG)));
const newChat = makeChat(OTHER_SLUG);
await save(newChat, { force: true });
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(newChat));
});
test('skips the check when the incoming chat has no integrity slug (existing behavior)', async () => {
fs.writeFileSync(chatFile, toJsonl(makeChat(SLUG)));
const newChat = makeChat(null);
await save(newChat);
expect(fs.readFileSync(chatFile, 'utf8')).toBe(toJsonl(newChat));
});
});
-106
View File
@@ -1,106 +0,0 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
test.describe('/addswipe without chat reload', () => {
test.beforeEach(testSetup.awaitST);
test('adds swipes in place without reloading the chat', async ({ page }) => {
const result = await page.evaluate(async () => {
const { newAssistantChat } = await import('./script.js');
const ctx = window.SillyTavern.getContext();
const commands = ctx.SlashCommandParser.commands;
const args = { quiet: 'true' };
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function waitFor(condition, timeoutMs = 5000, intervalMs = 50) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (condition()) return true;
await delay(intervalMs);
}
throw new Error('Timed out waiting for condition');
}
// A fresh account runs onboarding on load: dismiss its popup and wait for the
// welcome messages to finish arriving, so they don't land inside the test chat.
for (let i = 0; i < 10; i++) {
const okButton = document.querySelector('.popup:popover-open .popup-button-ok, dialog[open] .popup-button-ok');
if (!okButton) break;
okButton.click();
await delay(300);
}
const chat = ctx.chat;
let settledLength = -1;
await waitFor(() => {
const stable = chat.length === settledLength;
settledLength = chat.length;
return stable;
}, 10000, 700);
await newAssistantChat({ temporary: true });
const message = {
name: 'Assistant',
is_user: false,
is_system: false,
send_date: new Date().toISOString(),
mes: 'Original greeting',
extra: {},
};
chat.push(message);
await ctx.addOneMessage(message);
const mesId = chat.length - 1;
await waitFor(() => document.querySelector(`.mes[mesid="${mesId}"]`) !== null);
const mesDiv = document.querySelector(`.mes[mesid="${mesId}"]`);
// A full chat reload replaces the message elements, so element identity
// and ad-hoc DOM state prove the chat was updated in place.
mesDiv.dataset.tempUiState = 'alive';
const domAlive = () => mesDiv.isConnected && mesDiv.dataset.tempUiState === 'alive';
const counter = () => document.querySelector(`.mes[mesid="${mesId}"] .swipes-counter`)
?.textContent?.replace(/\u200b/g, '')?.trim();
const noSwitch = { returned: await commands['addswipe'].callback({ ...args }, 'Added swipe A') };
await delay(500);
Object.assign(noSwitch, {
swipes: chat[mesId].swipes.length,
swipeId: chat[mesId].swipe_id,
mes: chat[mesId].mes,
domAlive: domAlive(),
counter: counter(),
});
const warnings = [];
const origWarning = window.toastr.warning;
window.toastr.warning = (msg, ...rest) => { warnings.push(String(msg)); return origWarning.call(window.toastr, msg, ...rest); };
const preSwitchState = { len: chat.length, last: { name: chat[chat.length - 1]?.name, is_user: chat[chat.length - 1]?.is_user, is_system: chat[chat.length - 1]?.is_system, mes: chat[chat.length - 1]?.mes?.slice(0, 30) } };
const withSwitch = { returned: await commands['addswipe'].callback({ ...args, switch: 'true' }, 'Added swipe B') };
window.toastr.warning = origWarning;
withSwitch.debug = { preSwitchState, warnings };
await delay(1000);
Object.assign(withSwitch, {
swipes: chat[mesId].swipes.length,
swipeId: chat[mesId].swipe_id,
mes: chat[mesId].mes,
domAlive: domAlive(),
counter: counter(),
visibleText: document.querySelector(`.mes[mesid="${mesId}"] .mes_text`)?.textContent?.trim(),
});
return { noSwitch, withSwitch };
});
expect(result.noSwitch.returned).toBe('1');
expect(result.noSwitch.swipes).toBe(2);
expect(result.noSwitch.swipeId).toBe(0);
expect(result.noSwitch.mes).toBe('Original greeting');
expect(result.noSwitch.domAlive).toBe(true);
expect(result.noSwitch.counter).toBe('1/2');
expect(result.withSwitch.returned, JSON.stringify(result.withSwitch.debug)).toBe('2');
expect(result.withSwitch.swipes).toBe(3);
expect(result.withSwitch.swipeId).toBe(2);
expect(result.withSwitch.mes).toBe('Added swipe B');
expect(result.withSwitch.domAlive).toBe(true);
expect(result.withSwitch.counter).toBe('3/3');
expect(result.withSwitch.visibleText).toBe('Added swipe B');
});
});
-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);
});
});
});
-741
View File
@@ -1,741 +0,0 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
function createEditableReasoningMessageHtml({ detailsAttributes = 'data-has-content="false"', includeMessageContainers = false, includeMessageEditControls = false } = {}) {
const messageContainers = includeMessageContainers
? `
<div class="mes_text"></div>
<div class="mes_media_wrapper"></div>
<div class="mes_file_wrapper"></div>`
: '';
const messageEditControls = includeMessageEditControls
? `
<div class="mes_edit_done menu_button edit_button">Done message</div>
<div class="mes_edit_cancel menu_button edit_button">Cancel message</div>`
: '';
const messageButtons = includeMessageEditControls
? `
<div class="mes_buttons" style="display: flex;"></div>
<div class="mes_bias"></div>`
: '';
return `
<div class="mes reasoning" mesid="0" data-reasoning-state="done">
<div class="mes_block">
${messageButtons}
<div class="mes_edit_buttons" style="display: inline-flex;">
<div class="mes_edit_add_reasoning menu_button">Add reasoning</div>${messageEditControls}
</div>${messageContainers}
<details class="mes_reasoning_details"${detailsAttributes ? ` ${detailsAttributes}` : ''}>
<summary class="mes_reasoning_summary">
<div class="mes_reasoning_header">
<span class="mes_reasoning_header_title">Thought for some time</span>
</div>
<div class="mes_reasoning_actions">
<div class="mes_button edit_button mes_reasoning_edit">Edit</div>
<div class="mes_reasoning_edit_done menu_button edit_button">Done</div>
<div class="mes_reasoning_edit_cancel menu_button edit_button">Cancel</div>
</div>
</summary>
<div class="mes_reasoning"></div>
</details>
</div>
</div>
`;
}
test.describe('Reasoning hidden blocks', () => {
test.beforeEach(testSetup.awaitST);
test('keeps unrelated hidden reasoning blocks hidden while another block is being edited', async ({ page }) => {
const result = await page.evaluate(() => {
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
chat.removeAttribute('data-show-hidden-reasoning');
chat.innerHTML = `
<div class="mes reasoning" mesid="1">
<details class="mes_reasoning_details" data-has-content="false">
<summary class="mes_reasoning_summary">
<div class="mes_reasoning_header">
<span class="mes_reasoning_header_title">Thought for some time</span>
</div>
</summary>
<div class="mes_reasoning_actions">
<button class="mes_button edit_button mes_reasoning_edit">Edit</button>
<button class="mes_button mes_reasoning_edit_done">Done</button>
<button class="mes_button mes_reasoning_edit_cancel">Cancel</button>
</div>
<div class="mes_reasoning"></div>
</details>
</div>
<div class="mes reasoning" mesid="2">
<details class="mes_reasoning_details" data-has-content="false">
<summary class="mes_reasoning_summary">
<div class="mes_reasoning_header">
<span class="mes_reasoning_header_title">Thought for some time</span>
</div>
</summary>
<div class="mes_reasoning_actions">
<button class="mes_button edit_button mes_reasoning_edit">Edit</button>
<button class="mes_button mes_reasoning_edit_done">Done</button>
<button class="mes_button mes_reasoning_edit_cancel">Cancel</button>
</div>
<div class="mes_reasoning"></div>
</details>
</div>
`;
const firstDetails = chat.querySelector('[mesid="1"] .mes_reasoning_details');
const secondDetails = chat.querySelector('[mesid="2"] .mes_reasoning_details');
if (!firstDetails || !secondDetails) {
throw new Error('Missing reasoning blocks');
}
const before = {
first: getComputedStyle(firstDetails).display,
second: getComputedStyle(secondDetails).display,
};
const textarea = document.createElement('textarea');
textarea.className = 'reasoning_edit_textarea';
textarea.value = ' ';
firstDetails.querySelector('.mes_reasoning').before(textarea);
const after = {
first: getComputedStyle(firstDetails).display,
second: getComputedStyle(secondDetails).display,
textarea: getComputedStyle(textarea).display,
};
return { before, after };
});
expect(result.before.first).toBe('none');
expect(result.before.second).toBe('none');
expect(result.after.first).not.toBe('none');
expect(result.after.second).toBe('none');
expect(result.after.textarea).not.toBe('none');
});
test('hides add reasoning button while hidden-like reasoning is being edited', async ({ page }) => {
const addReasoningDisplay = await page.evaluate(() => {
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
chat.removeAttribute('data-show-hidden-reasoning');
chat.innerHTML = `
<div class="mes reasoning" mesid="1" data-reasoning-state="done">
<div class="mes_block">
<div class="mes_edit_buttons" style="display: inline-flex;">
<button class="mes_edit_add_reasoning menu_button">Add reasoning</button>
</div>
<details class="mes_reasoning_details" data-has-content="false" open>
<summary class="mes_reasoning_summary">
<div class="mes_reasoning_header">
<span class="mes_reasoning_header_title">Thought for some time</span>
</div>
</summary>
<div class="mes_reasoning_actions">
<button class="mes_button edit_button mes_reasoning_edit">Edit</button>
</div>
<textarea class="reasoning_edit_textarea">\n</textarea>
<div class="mes_reasoning"></div>
</details>
</div>
</div>
`;
const addReasoning = chat.querySelector('.mes_edit_add_reasoning');
if (!addReasoning) {
throw new Error('Missing add reasoning button');
}
return getComputedStyle(addReasoning).display;
});
expect(addReasoningDisplay).toBe('none');
});
test('does not create duplicate reasoning editors when add is clicked repeatedly', async ({ page }) => {
const result = await page.evaluate(async () => {
const reasoningModule = await import('/scripts/reasoning.js');
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.removeAttribute('data-show-hidden-reasoning');
chat.innerHTML = `
<div class="mes reasoning" mesid="0" data-reasoning-state="done">
<div class="mes_block">
<div class="mes_edit_buttons" style="display: inline-flex;">
<div class="mes_edit_add_reasoning menu_button">Add reasoning</div>
</div>
<details class="mes_reasoning_details" data-has-content="false">
<summary class="mes_reasoning_summary">
<div class="mes_reasoning_header">
<span class="mes_reasoning_header_title">Thought for some time</span>
</div>
<div class="mes_reasoning_actions">
<div class="mes_button edit_button mes_reasoning_edit">Edit</div>
</div>
</summary>
<div class="mes_reasoning"></div>
</details>
</div>
</div>
`;
const addReasoning = chat.querySelector('.mes_edit_add_reasoning');
if (!addReasoning) {
throw new Error('Missing add reasoning button');
}
addReasoning.click();
addReasoning.click();
await new Promise(resolve => setTimeout(resolve, 100));
const textareas = chat.querySelectorAll('.reasoning_edit_textarea');
return {
addDisplay: getComputedStyle(addReasoning).display,
detailsOpen: chat.querySelector('.mes_reasoning_details')?.open,
textareaCount: textareas.length,
textareaValue: textareas[0]?.value,
};
});
expect(result.detailsOpen).toBe(true);
expect(result.addDisplay).toBe('none');
expect(result.textareaCount).toBe(1);
expect(result.textareaValue).toBe('\n');
});
test('close all collapses stale open hidden-like reasoning details', async ({ page }) => {
const result = await page.evaluate(async () => {
const reasoningModule = await import('/scripts/reasoning.js');
reasoningModule.initReasoning();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = `
<button class="mes_reasoning_close_all">Close all</button>
<div class="mes reasoning" mesid="0">
<details class="mes_reasoning_details" data-has-content="false" open>
<summary class="mes_reasoning_summary">
<div class="mes_reasoning_header">
<span class="mes_reasoning_header_title">Thought for some time</span>
</div>
</summary>
<div class="mes_reasoning"></div>
</details>
</div>
<div class="mes reasoning" mesid="1">
<details class="mes_reasoning_details" data-has-content="true" open>
<summary class="mes_reasoning_summary">
<div class="mes_reasoning_header">
<span class="mes_reasoning_header_title">Thought for some time</span>
</div>
</summary>
<div class="mes_reasoning">visible reasoning</div>
</details>
</div>
`;
const hiddenDetails = chat.querySelector('[mesid="0"] .mes_reasoning_details');
const visibleDetails = chat.querySelector('[mesid="1"] .mes_reasoning_details');
const closeAll = chat.querySelector('.mes_reasoning_close_all');
if (!hiddenDetails || !visibleDetails || !closeAll) {
throw new Error('Missing close-all test elements');
}
const before = {
hiddenOpen: hiddenDetails.open,
visibleOpen: visibleDetails.open,
};
closeAll.click();
await new Promise(resolve => setTimeout(resolve, 100));
return {
before,
after: {
hiddenOpen: hiddenDetails.open,
visibleOpen: visibleDetails.open,
},
};
});
expect(result.before.hiddenOpen).toBe(true);
expect(result.before.visibleOpen).toBe(true);
expect(result.after.hiddenOpen).toBe(false);
expect(result.after.visibleOpen).toBe(false);
});
test('collapses whitespace-only reasoning after confirming edit with show hidden enabled', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const reasoningModule = await import('/scripts/reasoning.js');
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
const addReasoning = chat.querySelector('.mes_edit_add_reasoning');
if (!addReasoning) {
throw new Error('Missing add reasoning button');
}
addReasoning.click();
await new Promise(resolve => setTimeout(resolve, 100));
const details = chat.querySelector('.mes_reasoning_details');
const textarea = chat.querySelector('.reasoning_edit_textarea');
const beforeDone = {
detailsOpen: details?.open,
textareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
textareaValue: textarea?.value,
};
chat.querySelector('.mes_reasoning_edit_done')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
return {
beforeDone,
afterDone: {
detailsOpen: details?.open,
textareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
},
};
}, createEditableReasoningMessageHtml());
expect(result.beforeDone.detailsOpen).toBe(true);
expect(result.beforeDone.textareaCount).toBe(1);
expect(result.beforeDone.textareaValue).toBe('\n');
expect(result.afterDone.textareaCount).toBe(0);
expect(result.afterDone.detailsOpen).toBe(false);
});
test('collapses whitespace-only reasoning after canceling edit with show hidden enabled', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const reasoningModule = await import('/scripts/reasoning.js');
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
const addReasoning = chat.querySelector('.mes_edit_add_reasoning');
if (!addReasoning) {
throw new Error('Missing add reasoning button');
}
addReasoning.click();
await new Promise(resolve => setTimeout(resolve, 100));
const details = chat.querySelector('.mes_reasoning_details');
const beforeCancel = {
detailsOpen: details?.open,
textareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
};
chat.querySelector('.mes_reasoning_edit_cancel')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
return {
beforeCancel,
afterCancel: {
detailsOpen: details?.open,
textareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
},
};
}, createEditableReasoningMessageHtml());
expect(result.beforeCancel.detailsOpen).toBe(true);
expect(result.beforeCancel.textareaCount).toBe(1);
expect(result.afterCancel.textareaCount).toBe(0);
expect(result.afterCancel.detailsOpen).toBe(false);
});
test('collapses whitespace-only reasoning after confirming message edit with reasoning edit open', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const [reasoningModule, scriptModule] = await Promise.all([
import('/scripts/reasoning.js'),
import('/script.js'),
]);
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
chat.querySelector('.mes_edit_add_reasoning')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
await scriptModule.messageEdit(0);
await new Promise(resolve => setTimeout(resolve, 100));
const editTextarea = chat.querySelector('#curEditTextarea');
if (editTextarea) {
editTextarea.value = 'Foo edited';
}
const beforeDone = {
detailsOpen: chat.querySelector('.mes_reasoning_details')?.open,
reasoningTextareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
messageTextareaCount: chat.querySelectorAll('#curEditTextarea').length,
};
chat.querySelector('.mes_edit_done')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
return {
beforeDone,
afterDone: {
detailsOpen: chat.querySelector('.mes_reasoning_details')?.open,
reasoningTextareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
messageTextareaCount: chat.querySelectorAll('#curEditTextarea').length,
messageValue: context.chat[0]?.mes,
reasoningValue: context.chat[0]?.extra?.reasoning,
},
};
}, createEditableReasoningMessageHtml({ includeMessageContainers: true, includeMessageEditControls: true }));
expect(result.beforeDone.detailsOpen).toBe(true);
expect(result.beforeDone.reasoningTextareaCount).toBe(1);
expect(result.beforeDone.messageTextareaCount).toBe(1);
expect(result.afterDone.reasoningTextareaCount).toBe(0);
expect(result.afterDone.messageTextareaCount).toBe(0);
expect(result.afterDone.detailsOpen).toBe(false);
expect(result.afterDone.messageValue).toBe('Foo edited');
expect(result.afterDone.reasoningValue).toBe('\n');
});
test('collapses whitespace-only reasoning after canceling message edit with reasoning edit open', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const [reasoningModule, scriptModule] = await Promise.all([
import('/scripts/reasoning.js'),
import('/script.js'),
]);
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
chat.querySelector('.mes_edit_add_reasoning')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
await scriptModule.messageEdit(0);
await new Promise(resolve => setTimeout(resolve, 100));
const editTextarea = chat.querySelector('#curEditTextarea');
if (editTextarea) {
editTextarea.value = 'Foo should cancel';
}
const beforeCancel = {
detailsOpen: chat.querySelector('.mes_reasoning_details')?.open,
reasoningTextareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
messageTextareaCount: chat.querySelectorAll('#curEditTextarea').length,
};
chat.querySelector('.mes_edit_cancel')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
return {
beforeCancel,
afterCancel: {
detailsOpen: chat.querySelector('.mes_reasoning_details')?.open,
reasoningTextareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
messageTextareaCount: chat.querySelectorAll('#curEditTextarea').length,
messageValue: context.chat[0]?.mes,
reasoningValue: context.chat[0]?.extra?.reasoning,
},
};
}, createEditableReasoningMessageHtml({ includeMessageContainers: true, includeMessageEditControls: true }));
expect(result.beforeCancel.detailsOpen).toBe(true);
expect(result.beforeCancel.reasoningTextareaCount).toBe(1);
expect(result.beforeCancel.messageTextareaCount).toBe(1);
expect(result.afterCancel.reasoningTextareaCount).toBe(0);
expect(result.afterCancel.messageTextareaCount).toBe(0);
expect(result.afterCancel.detailsOpen).toBe(false);
expect(result.afterCancel.messageValue).toBe('Foo');
expect(result.afterCancel.reasoningValue).toBe('\n');
});
test('keeps whitespace-only reasoning collapsed when auto-expand is enabled', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const [reasoningModule, powerUserModule] = await Promise.all([
import('/scripts/reasoning.js'),
import('/scripts/power-user.js'),
]);
reasoningModule.initReasoning();
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo', gen_started: new Date().toISOString() });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
const previousAutoExpand = powerUserModule.power_user.reasoning.auto_expand;
powerUserModule.power_user.reasoning.auto_expand = true;
try {
reasoningModule.updateReasoningUI(chat.querySelector('.mes'));
} finally {
powerUserModule.power_user.reasoning.auto_expand = previousAutoExpand;
}
const details = chat.querySelector('.mes_reasoning_details');
return {
detailsOpen: details?.open,
hasContent: details?.getAttribute('data-has-content'),
};
}, createEditableReasoningMessageHtml({ detailsAttributes: '' }));
expect(result.hasContent).toBeNull();
expect(result.detailsOpen).toBe(false);
});
test('treats whitespace-only reasoning as hidden-like when trim spaces is disabled', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const [reasoningModule, powerUserModule] = await Promise.all([
import('/scripts/reasoning.js'),
import('/scripts/power-user.js'),
]);
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo', gen_started: new Date().toISOString() });
chat.removeAttribute('data-show-hidden-reasoning');
chat.innerHTML = messageHtml;
const previousTrimSpaces = powerUserModule.power_user.trim_spaces;
try {
powerUserModule.power_user.trim_spaces = false;
reasoningModule.updateReasoningUI(chat.querySelector('.mes'));
} finally {
powerUserModule.power_user.trim_spaces = previousTrimSpaces;
}
const details = chat.querySelector('.mes_reasoning_details');
const beforeAddDisplay = details ? getComputedStyle(details).display : null;
const addReasoning = chat.querySelector('.mes_edit_add_reasoning');
addReasoning?.click();
await new Promise(resolve => setTimeout(resolve, 100));
const textarea = chat.querySelector('.reasoning_edit_textarea');
return {
beforeAddDisplay,
afterAddDisplay: details ? getComputedStyle(details).display : null,
detailsOpen: details?.open,
hasContent: details?.getAttribute('data-has-content'),
textareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
textareaValue: textarea?.value,
};
}, createEditableReasoningMessageHtml({ detailsAttributes: '' }));
expect(result.hasContent).toBeNull();
expect(result.beforeAddDisplay).toBe('none');
expect(result.afterAddDisplay).not.toBe('none');
expect(result.detailsOpen).toBe(true);
expect(result.textareaCount).toBe(1);
expect(result.textareaValue).toBe('\n');
});
test('does not expand whitespace-only reasoning through slash commands', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const [reasoningModule, slashCommandsModule] = await Promise.all([
import('/scripts/reasoning.js'),
import('/scripts/slash-commands.js'),
]);
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
const details = chat.querySelector('.mes_reasoning_details');
await slashCommandsModule.executeSlashCommandsWithOptions('/reasoning-expand 0');
const afterExpand = details?.open;
await slashCommandsModule.executeSlashCommandsWithOptions('/reasoning-toggle 0');
const afterToggle = details?.open;
return {
afterExpand,
afterToggle,
hasContent: details?.getAttribute('data-has-content'),
};
}, createEditableReasoningMessageHtml());
expect(result.hasContent).toBe('false');
expect(result.afterExpand).toBe(false);
expect(result.afterToggle).toBe(false);
});
test('expands visible reasoning through slash commands', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const [reasoningModule, slashCommandsModule] = await Promise.all([
import('/scripts/reasoning.js'),
import('/scripts/slash-commands.js'),
]);
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: 'visible reasoning' }, name: 'Ilo', mes: 'Foo' });
chat.innerHTML = messageHtml;
const details = chat.querySelector('.mes_reasoning_details');
await slashCommandsModule.executeSlashCommandsWithOptions('/reasoning-expand 0');
const afterExpand = details?.open;
await slashCommandsModule.executeSlashCommandsWithOptions('/reasoning-toggle 0');
const afterToggleClosed = details?.open;
await slashCommandsModule.executeSlashCommandsWithOptions('/reasoning-toggle 0');
const afterToggleOpen = details?.open;
return {
afterExpand,
afterToggleClosed,
afterToggleOpen,
hasContent: details?.getAttribute('data-has-content'),
};
}, createEditableReasoningMessageHtml({ detailsAttributes: 'data-has-content="true"' }));
expect(result.hasContent).toBe('true');
expect(result.afterExpand).toBe(true);
expect(result.afterToggleClosed).toBe(false);
expect(result.afterToggleOpen).toBe(true);
});
test('keeps reasoning expanded after changing whitespace-only reasoning to visible content', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const reasoningModule = await import('/scripts/reasoning.js');
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
chat.querySelector('.mes_edit_add_reasoning')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
const textarea = chat.querySelector('.reasoning_edit_textarea');
textarea.value = 'visible reasoning';
chat.querySelector('.mes_reasoning_edit_done')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
const details = chat.querySelector('.mes_reasoning_details');
return {
detailsOpen: details?.open,
hasContent: details?.getAttribute('data-has-content'),
textareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
reasoningText: chat.querySelector('.mes_reasoning')?.textContent,
};
}, createEditableReasoningMessageHtml({ includeMessageContainers: true }));
expect(result.textareaCount).toBe(0);
expect(result.hasContent).toBe('true');
expect(result.detailsOpen).toBe(true);
expect(result.reasoningText).toContain('visible reasoning');
});
test('collapses reasoning after changing whitespace-only reasoning to different whitespace', async ({ page }) => {
const result = await page.evaluate(async (messageHtml) => {
const reasoningModule = await import('/scripts/reasoning.js');
reasoningModule.initReasoning();
const context = window.SillyTavern.getContext();
const chat = document.getElementById('chat');
if (!chat) {
throw new Error('Missing #chat container');
}
context.chat.length = 0;
context.chat.push({ extra: { reasoning: '\n' }, name: 'Ilo', mes: 'Foo' });
chat.setAttribute('data-show-hidden-reasoning', 'true');
chat.innerHTML = messageHtml;
chat.querySelector('.mes_edit_add_reasoning')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
const textarea = chat.querySelector('.reasoning_edit_textarea');
textarea.value = ' ';
chat.querySelector('.mes_reasoning_edit_done')?.click();
await new Promise(resolve => setTimeout(resolve, 100));
const details = chat.querySelector('.mes_reasoning_details');
return {
detailsOpen: details?.open,
hasContent: details?.getAttribute('data-has-content'),
textareaCount: chat.querySelectorAll('.reasoning_edit_textarea').length,
};
}, createEditableReasoningMessageHtml({ includeMessageContainers: true }));
expect(result.textareaCount).toBe(0);
expect(result.hasContent).toBeNull();
expect(result.detailsOpen).toBe(false);
});
});
@@ -1,79 +0,0 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
test.describe('World Info Rename Chat Lore', () => {
test.beforeEach(testSetup.awaitST);
test('should retarget chat lore metadata after lorebook rename', async ({ page }) => {
const oldName = 'STAGE_REPRO_ALPHA';
const newName = 'STAGE_REPRO_BETA';
const result = await page.evaluate(async ({ oldName, newName }) => {
const { createNewWorldInfo, deleteWorldInfo, openWorldInfoEditor, METADATA_KEY, world_names } = await import('./scripts/world-info.js');
const { chat_metadata } = await import('./script.js');
const { Popup, POPUP_RESULT } = await import('./scripts/popup.js');
async function waitFor(condition, timeoutMs = 5000, intervalMs = 50) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (condition()) return true;
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
return false;
}
const originalInput = Popup.show.input;
const originalConfirm = Popup.show.confirm;
try {
if (world_names.includes(oldName)) {
await deleteWorldInfo(oldName);
}
if (world_names.includes(newName)) {
await deleteWorldInfo(newName);
}
const created = await createNewWorldInfo(oldName, { interactive: false });
if (!created) {
throw new Error(`Failed to create world info '${oldName}'`);
}
chat_metadata[METADATA_KEY] = oldName;
await openWorldInfoEditor(oldName);
Popup.show.input = async () => newName;
Popup.show.confirm = async () => POPUP_RESULT.NEGATIVE;
const renameButton = document.querySelector('#world_popup_name_button');
if (!renameButton) {
throw new Error('Could not find #world_popup_name_button');
}
renameButton.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
const renameApplied = await waitFor(() => {
const editorValue = String($('#world_editor_select').find(':selected').text());
const optionTexts = $('#world_editor_select option').map((_, option) => String($(option).text())).get();
return editorValue === newName && optionTexts.includes(newName) && !optionTexts.includes(oldName);
});
if (!renameApplied) {
throw new Error('Rename operation did not complete in time');
}
return {
metadataAfter: chat_metadata[METADATA_KEY],
hasOldWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === oldName),
hasNewWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === newName),
};
} finally {
Popup.show.input = originalInput;
Popup.show.confirm = originalConfirm;
}
}, { oldName, newName });
expect(result.hasOldWorld).toBe(false);
expect(result.hasNewWorld).toBe(true);
expect(result.metadataAfter).toBe(newName);
});
});
@@ -1,85 +0,0 @@
import { test, expect } from '@playwright/test';
import { testSetup } from './frontent-test-utils.js';
test.describe('World Info Rename Persona Lore', () => {
test.beforeEach(testSetup.awaitST);
test('should retarget persona lore metadata after lorebook rename', async ({ page }) => {
const oldName = 'STAGE_REPRO_PERSONA_ALPHA';
const newName = 'STAGE_REPRO_PERSONA_BETA';
const result = await page.evaluate(async ({ oldName, newName }) => {
const { createNewWorldInfo, deleteWorldInfo, openWorldInfoEditor, world_names } = await import('./scripts/world-info.js');
const { Popup, POPUP_RESULT } = await import('./scripts/popup.js');
const { power_user } = await import('./scripts/power-user.js');
const { getOrCreatePersonaDescriptor, user_avatar } = await import('./scripts/personas.js');
async function waitFor(condition, timeoutMs = 5000, intervalMs = 50) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (condition()) return true;
await new Promise(resolve => setTimeout(resolve, intervalMs));
}
return false;
}
const originalInput = Popup.show.input;
const originalConfirm = Popup.show.confirm;
try {
if (world_names.includes(oldName)) {
await deleteWorldInfo(oldName);
}
if (world_names.includes(newName)) {
await deleteWorldInfo(newName);
}
const created = await createNewWorldInfo(oldName, { interactive: false });
if (!created) {
throw new Error(`Failed to create world info '${oldName}'`);
}
power_user.personas[user_avatar] = power_user.personas[user_avatar] || 'STAGE_REPRO_PERSONA';
power_user.persona_description_lorebook = oldName;
const descriptor = getOrCreatePersonaDescriptor();
descriptor.lorebook = oldName;
await openWorldInfoEditor(oldName);
Popup.show.input = async () => newName;
Popup.show.confirm = async () => POPUP_RESULT.NEGATIVE;
const renameButton = document.querySelector('#world_popup_name_button');
if (!renameButton) {
throw new Error('Could not find #world_popup_name_button');
}
renameButton.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
const renameApplied = await waitFor(() => {
const editorValue = String($('#world_editor_select').find(':selected').text());
const optionTexts = $('#world_editor_select option').map((_, option) => String($(option).text())).get();
return editorValue === newName && optionTexts.includes(newName) && !optionTexts.includes(oldName);
});
if (!renameApplied) {
throw new Error('Rename operation did not complete in time');
}
return {
personaLoreAfter: power_user.persona_description_lorebook,
descriptorLoreAfter: descriptor.lorebook,
hasOldWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === oldName),
hasNewWorld: $('#world_editor_select option').toArray().some(option => String($(option).text()) === newName),
};
} finally {
Popup.show.input = originalInput;
Popup.show.confirm = originalConfirm;
}
}, { oldName, newName });
expect(result.hasOldWorld).toBe(false);
expect(result.hasNewWorld).toBe(true);
expect(result.personaLoreAfter).toBe(newName);
expect(result.descriptorLoreAfter).toBe(newName);
});
});
+2 -30
View File
@@ -1,5 +1,3 @@
const baseURL = process.env.ST_BASE_URL || process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:8000';
export const testSetup = {
/**
* Navigates to the home page without waiting for SillyTavern to load.
@@ -17,34 +15,8 @@ export const testSetup = {
*/
awaitST: async ({ page }) => {
await page.goto('/');
if (await testSetup.isLoginPage({ page })) {
// eslint-disable-next-line playwright/no-networkidle
await page.waitForLoadState('networkidle');
// Try accounts from last to first: clicking a password-protected account stays on the login page
const userSelects = page.locator('#userList .userSelect');
const userCount = await userSelects.count();
for (let i = userCount - 1; i >= 0; i--) {
await userSelects.nth(i).click();
const loggedIn = await page
.waitForURL(url => url.toString().startsWith(baseURL) && url.pathname !== '/login', { timeout: 3000 })
.then(() => true, () => false);
if (loggedIn) {
break;
}
}
if (await testSetup.isLoginPage({ page })) {
throw new Error('Could not log into any account without a password.');
}
}
await page.click('#userList .userSelect:last-child');
await page.waitForURL('http://127.0.0.1:8000');
await page.waitForFunction('document.getElementById("preloader") === null', { timeout: 0 });
},
/**
* Checks if the current page is the login page by looking for a body element with the class 'login'.
* @param {Object} params
* @param {import('@playwright/test').Page} params.page
*/
isLoginPage: async ({ page }) => {
return await page.locator('body.login').count() > 0;
},
};
+1 -3
View File
@@ -1,11 +1,9 @@
import { defineConfig } from '@playwright/test';
const baseURL = process.env.ST_BASE_URL || process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:8000';
export default defineConfig({
testMatch: '*.e2e.js',
use: {
baseURL,
baseURL: 'http://127.0.0.1:8000',
video: 'only-on-failure',
screenshot: 'only-on-failure',
},
+3 -72
View File
@@ -31,8 +31,6 @@ jest.unstable_mockModule('../src/express-common.js', () => ({
/** @type {import('../src/private-request-filter.js').default} */
let initPrivateRequestFilter;
/** @type {import('../src/private-request-filter.js').getUntrustedRequestAgent} */
let getUntrustedRequestAgent;
/** @type {import('node:http').default} */
let http;
/** @type {import('node:https').default} */
@@ -41,7 +39,7 @@ let originalHttpGlobalAgent;
let originalHttpsGlobalAgent;
beforeAll(async () => {
({ default: initPrivateRequestFilter, getUntrustedRequestAgent } = await import('../src/private-request-filter.js'));
({ default: initPrivateRequestFilter } = await import('../src/private-request-filter.js'));
({ default: http } = await import('node:http'));
({ default: https } = await import('node:https'));
originalHttpGlobalAgent = http.globalAgent;
@@ -61,15 +59,14 @@ afterAll(() => {
https.globalAgent = originalHttpsGlobalAgent;
});
function initAgent({ privateAddressWhitelist = [], allowUnresolvedHosts = false, enabled = true, requestProxyEnabled = false } = {}) {
function initAgent({ privateAddressWhitelist = [], allowUnresolvedHosts = false } = {}) {
initPrivateRequestFilter({
listen: false,
enabled,
enabled: true,
privateAddressWhitelist,
logBlocked: false,
logAllowed: false,
allowUnresolvedHosts,
requestProxyEnabled,
});
return http.globalAgent;
@@ -131,69 +128,3 @@ describe('private request filter', () => {
expect(mockNetConnect).not.toHaveBeenCalled();
});
});
describe('untrusted request agent', () => {
test('returns undefined when the private request filter is enabled', () => {
initAgent({ enabled: true });
expect(getUntrustedRequestAgent()).toBeUndefined();
});
test('returns undefined when a request proxy owns outbound routing', () => {
initAgent({ enabled: false, requestProxyEnabled: true });
expect(getUntrustedRequestAgent()).toBeUndefined();
});
test('returns the same strict agent instance when the filter is disabled', () => {
initAgent({ enabled: false });
const agent = getUntrustedRequestAgent();
expect(agent).toBeDefined();
expect(getUntrustedRequestAgent()).toBe(agent);
});
test('blocks private addresses even when the configured whitelist allows them', async () => {
initAgent({ enabled: false, privateAddressWhitelist: ['127.0.0.0/8', '::1/128'] });
const agent = getUntrustedRequestAgent();
await expect(agent.connect({}, { host: '127.0.0.1', secureEndpoint: false }))
.rejects
.toThrow('Blocked request to private IP address: 127.0.0.1');
await expect(agent.connect({}, { host: '::1', secureEndpoint: false }))
.rejects
.toThrow('Blocked request to private IP address: ::1');
expect(mockNetConnect).not.toHaveBeenCalled();
});
test('blocks hostnames that resolve to private addresses', async () => {
initAgent({ enabled: false });
mockLookup.mockResolvedValue({ address: '192.168.1.8' });
const agent = getUntrustedRequestAgent();
await expect(agent.connect({}, { host: 'internal.example.com', secureEndpoint: false }))
.rejects
.toThrow('Blocked request to private IP address: 192.168.1.8');
expect(mockNetConnect).not.toHaveBeenCalled();
});
test('blocks unresolvable hostnames', async () => {
initAgent({ enabled: false });
mockLookup.mockRejectedValue(new Error('lookup failed'));
const agent = getUntrustedRequestAgent();
await expect(agent.connect({}, { host: 'missing-host.local', secureEndpoint: false }))
.rejects
.toThrow('Unable to resolve host: missing-host.local');
expect(mockNetConnect).not.toHaveBeenCalled();
});
test('connects public hostnames to their resolved IP for both http and https', async () => {
initAgent({ enabled: false });
mockLookup.mockResolvedValue({ address: '93.184.216.34' });
const agent = getUntrustedRequestAgent();
await agent.connect({}, { host: 'example.com', secureEndpoint: false });
expect(mockNetConnect).toHaveBeenCalledWith(expect.objectContaining({ host: '93.184.216.34' }));
await agent.connect({}, { host: 'example.com', secureEndpoint: true });
expect(mockTlsConnect).toHaveBeenCalledWith(expect.objectContaining({ host: '93.184.216.34' }));
});
});
-13
View File
@@ -166,19 +166,6 @@ describe('calculateGoogleBudgetTokens', () => {
test('max returns high', () => expect(mod.calculateGoogleBudgetTokens(8192, 'max', 'gemini-3.5-flash')).toBe('high'));
});
test('stable Gemini 3.1 Flash-Lite uses Gemini 3 thinking levels', () => {
expect(mod.calculateGoogleBudgetTokens(8192, 'min', 'gemini-3.1-flash-lite')).toBe('minimal');
expect(mod.calculateGoogleBudgetTokens(8192, 'medium', 'gemini-3.1-flash-lite')).toBe('medium');
expect(mod.calculateGoogleBudgetTokens(8192, 'max', 'gemini-3.1-flash-lite')).toBe('high');
});
test('stable Gemini 3 image models use Gemini 3 thinking levels', () => {
expect(mod.calculateGoogleBudgetTokens(8192, 'min', 'gemini-3.1-flash-image')).toBe('minimal');
expect(mod.calculateGoogleBudgetTokens(8192, 'max', 'gemini-3.1-flash-image')).toBe('high');
expect(mod.calculateGoogleBudgetTokens(8192, 'min', 'gemini-3-pro-image')).toBe('low');
expect(mod.calculateGoogleBudgetTokens(8192, 'max', 'gemini-3-pro-image')).toBe('high');
});
describe('gemini-3 pro', () => {
test('auto returns null', () => expect(mod.calculateGoogleBudgetTokens(8192, 'auto', 'gemini-3.0-pro')).toBeNull());
test('min returns low', () => expect(mod.calculateGoogleBudgetTokens(8192, 'min', 'gemini-3.0-pro')).toBe('low'));
-97
View File
@@ -1,97 +0,0 @@
import { describe, test, expect, jest, beforeAll, afterAll, beforeEach } from '@jest/globals';
// secrets.js reads this config value at module load. The env var override takes
// precedence over config.yaml, so the search router imports without a config file.
process.env.SILLYTAVERN_ALLOWKEYSEXPOSURE = 'false';
const fetchMock = jest.fn();
jest.unstable_mockModule('node-fetch', () => ({
default: fetchMock,
}));
/** @type {import('express').Router} */
let router;
/** @type {import('../src/private-request-filter.js').getUntrustedRequestAgent} */
let getUntrustedRequestAgent;
/** @type {import('node:http').Server} */
let server;
let baseUrl;
beforeAll(async () => {
({ router } = await import('../src/endpoints/search.js'));
({ getUntrustedRequestAgent } = await import('../src/private-request-filter.js'));
const express = (await import('express')).default;
const app = express();
app.use(express.json());
app.use('/api/search', router);
server = app.listen(0, '127.0.0.1');
await new Promise(resolve => server.once('listening', resolve));
baseUrl = `http://127.0.0.1:${server.address().port}`;
});
afterAll(() => new Promise(resolve => server.close(resolve)));
beforeEach(() => {
fetchMock.mockReset();
fetchMock.mockResolvedValue({
ok: true,
headers: { get: () => 'text/html' },
text: async () => '<html>ok</html>',
});
});
function visit(url) {
return fetch(`${baseUrl}/api/search/visit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
});
}
describe('POST /api/search/visit URL validation', () => {
const rejectedUrls = [
['missing url', undefined],
['empty url', ''],
['relative url', '/etc/passwd'],
['ftp protocol', 'ftp://example.com/'],
['file protocol', 'file:///etc/passwd'],
['non-standard port', 'http://example.com:8080/'],
['literal IPv4 loopback', 'http://127.0.0.1/'],
['literal IPv4 private', 'http://10.0.0.1/'],
['literal IPv4 metadata service', 'http://169.254.169.254/'],
['hex IPv4 form', 'http://0x7f000001/'],
['octal IPv4 form', 'http://0177.0.0.1/'],
['decimal IPv4 form', 'http://2130706433/'],
['bracketed IPv6 loopback', 'http://[::1]/'],
['bracketed IPv6 link-local', 'http://[fe80::1]/'],
['localhost', 'http://localhost/'],
['localhost subdomain', 'http://sub.localhost/'],
['https localhost', 'https://localhost/'],
];
for (const [label, url] of rejectedUrls) {
test(`rejects ${label} with 400 before any request is made`, async () => {
const response = await visit(url);
expect(response.status).toBe(400);
expect(fetchMock).not.toHaveBeenCalled();
});
}
const allowedUrls = [
['public http url', 'http://example.com/'],
['public https url', 'https://example.com/some/page?query=1'],
];
for (const [label, url] of allowedUrls) {
test(`passes ${label} to fetch through the untrusted request agent`, async () => {
const response = await visit(url);
expect(response.status).toBe(200);
expect(await response.text()).toBe('<html>ok</html>');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(url, expect.objectContaining({
agent: getUntrustedRequestAgent(),
}));
expect(getUntrustedRequestAgent()).toBeDefined();
});
}
});
+179
View File
@@ -0,0 +1,179 @@
import { describe, test, expect } from '@jest/globals';
import { encryptObjectAes256, decryptObjectAes256, isEncryptedData } from '../src/util-crypto.js';
describe('encryptObjectAes256', () => {
test('returns an object with salt, iv, encrypted, and authTag properties', () => {
const result = encryptObjectAes256({ hello: 'world' }, 'secret');
expect(result).toBeInstanceOf(Object);
expect(typeof result.salt).toBe('string');
expect(typeof result.iv).toBe('string');
expect(typeof result.encrypted).toBe('string');
expect(typeof result.authTag).toBe('string');
});
test('all properties are valid hex strings', () => {
const result = encryptObjectAes256({ hello: 'world' }, 'secret');
expect(result.salt).toMatch(/^[0-9a-f]+$/i);
expect(result.iv).toMatch(/^[0-9a-f]+$/i);
expect(result.encrypted).toMatch(/^[0-9a-f]+$/i);
expect(result.authTag).toMatch(/^[0-9a-f]+$/i);
});
test('produces different salt and IV each call', () => {
const a = encryptObjectAes256({ value: 42 }, 'key');
const b = encryptObjectAes256({ value: 42 }, 'key');
expect(a.salt).not.toBe(b.salt);
expect(a.iv).not.toBe(b.iv);
});
test('salt is 32 bytes (64 hex characters)', () => {
const result = encryptObjectAes256({}, 'anykey');
expect(result.salt).toHaveLength(64);
});
test('IV is 12 bytes (24 hex characters)', () => {
const result = encryptObjectAes256({}, 'anykey');
expect(result.iv).toHaveLength(24);
});
test('authTag is 16 bytes (32 hex characters)', () => {
const result = encryptObjectAes256({}, 'anykey');
expect(result.authTag).toHaveLength(32);
});
});
describe('decryptObjectAes256', () => {
test('round-trips a plain object', () => {
const original = { foo: 'bar', num: 123 };
const encrypted = encryptObjectAes256(original, 'mypassword');
const decrypted = decryptObjectAes256(encrypted, 'mypassword');
expect(decrypted).toEqual(original);
});
test('round-trips a nested object', () => {
const original = { a: { b: { c: [1, 2, 3] } } };
const encrypted = encryptObjectAes256(original, 'nestedkey');
const decrypted = decryptObjectAes256(encrypted, 'nestedkey');
expect(decrypted).toEqual(original);
});
test('round-trips a string value', () => {
const original = 'hello world';
const encrypted = encryptObjectAes256(original, 'strkey');
const decrypted = decryptObjectAes256(encrypted, 'strkey');
expect(decrypted).toBe(original);
});
test('round-trips a number value', () => {
const original = 9007199254740991;
const encrypted = encryptObjectAes256(original, 'numkey');
const decrypted = decryptObjectAes256(encrypted, 'numkey');
expect(decrypted).toBe(original);
});
test('round-trips an array', () => {
const original = [1, 'two', { three: 3 }];
const encrypted = encryptObjectAes256(original, 'arrkey');
const decrypted = decryptObjectAes256(encrypted, 'arrkey');
expect(decrypted).toEqual(original);
});
test('round-trips null', () => {
const encrypted = encryptObjectAes256(null, 'nullkey');
const decrypted = decryptObjectAes256(encrypted, 'nullkey');
expect(decrypted).toBeNull();
});
test('round-trips boolean false', () => {
const encrypted = encryptObjectAes256(false, 'boolkey');
const decrypted = decryptObjectAes256(encrypted, 'boolkey');
expect(decrypted).toBe(false);
});
test('throws with wrong key (auth tag mismatch)', () => {
const encrypted = encryptObjectAes256({ secret: 'data' }, 'correctkey');
expect(() => decryptObjectAes256(encrypted, 'wrongkey')).toThrow();
});
test('throws when authTag is tampered', () => {
const encrypted = encryptObjectAes256({ v: 1 }, 'k');
const tamperedTag = encrypted.authTag.slice(0, -2) + (encrypted.authTag.slice(-2) === 'ff' ? '00' : 'ff');
const tampered = { ...encrypted, authTag: tamperedTag };
expect(() => decryptObjectAes256(tampered, 'k')).toThrow();
});
test('throws when ciphertext is tampered', () => {
const encrypted = encryptObjectAes256({ v: 'hello' }, 'k');
const tamperedCipher = encrypted.encrypted.slice(0, -2) + (encrypted.encrypted.slice(-2) === 'ff' ? '00' : 'ff');
const tampered = { ...encrypted, encrypted: tamperedCipher };
expect(() => decryptObjectAes256(tampered, 'k')).toThrow();
});
});
describe('isEncryptedData', () => {
test('returns true for a valid encrypted object', () => {
const encrypted = encryptObjectAes256({ a: 1 }, 'key');
expect(isEncryptedData(encrypted)).toBe(true);
});
test('returns false for a plain string', () => {
expect(isEncryptedData('hello world')).toBe(false);
});
test('returns false for null', () => {
expect(isEncryptedData(null)).toBe(false);
});
test('returns false for an array', () => {
expect(isEncryptedData(['ab', 'cd', 'ef', '12'])).toBe(false);
});
test('returns false for a number', () => {
expect(isEncryptedData(42)).toBe(false);
});
test('returns false when a required property is missing', () => {
const encrypted = encryptObjectAes256({ a: 1 }, 'key');
const { salt: _salt, ...withoutSalt } = encrypted;
expect(_salt).toBeDefined();
expect(isEncryptedData(withoutSalt)).toBe(false);
const { iv: _iv, ...withoutIv } = encrypted;
expect(_iv).toBeDefined();
expect(isEncryptedData(withoutIv)).toBe(false);
const { encrypted: _enc, ...withoutEncrypted } = encrypted;
expect(_enc).toBeDefined();
expect(isEncryptedData(withoutEncrypted)).toBe(false);
const { authTag: _tag, ...withoutAuthTag } = encrypted;
expect(_tag).toBeDefined();
expect(isEncryptedData(withoutAuthTag)).toBe(false);
});
test('returns false when a property contains non-hex characters', () => {
const base = encryptObjectAes256({ a: 1 }, 'key');
expect(isEncryptedData({ ...base, salt: 'zzzz' })).toBe(false);
expect(isEncryptedData({ ...base, iv: 'zzzz' })).toBe(false);
expect(isEncryptedData({ ...base, encrypted: 'zzzz' })).toBe(false);
expect(isEncryptedData({ ...base, authTag: 'zzzz' })).toBe(false);
});
test('returns false when a property is an empty string', () => {
const base = encryptObjectAes256({ a: 1 }, 'key');
expect(isEncryptedData({ ...base, salt: '' })).toBe(false);
expect(isEncryptedData({ ...base, iv: '' })).toBe(false);
expect(isEncryptedData({ ...base, authTag: '' })).toBe(false);
});
test('returns true for valid hex values with uppercase characters', () => {
const base = encryptObjectAes256({ a: 1 }, 'key');
const upper = {
salt: base.salt.toUpperCase(),
iv: base.iv.toUpperCase(),
encrypted: base.encrypted.toUpperCase(),
authTag: base.authTag.toUpperCase(),
};
expect(isEncryptedData(upper)).toBe(true);
});
});
-136
View File
@@ -1,136 +0,0 @@
import { afterEach, beforeEach, describe, test, expect, jest } from '@jest/globals';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { getImages } from '../src/util';
import { MEDIA_REQUEST_TYPE } from '../src/constants';
describe('getImages', () => {
let tmpDir;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'st-getimages-'));
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
function writeFile(name, mtimeMs = null) {
const filePath = path.join(tmpDir, name);
fs.writeFileSync(filePath, '');
if (mtimeMs !== null) {
const secs = mtimeMs / 1000;
fs.utimesSync(filePath, secs, secs);
}
}
test('sorts by name with natural collation', () => {
writeFile('b.png');
writeFile('a.png');
writeFile('c.png');
expect(getImages(tmpDir, 'name')).toEqual(['a.png', 'b.png', 'c.png']);
});
test('sorts by date oldest-first using file mtime', () => {
writeFile('newest.png', 3_000_000);
writeFile('oldest.png', 1_000_000);
writeFile('middle.png', 2_000_000);
expect(getImages(tmpDir, 'date')).toEqual(['oldest.png', 'middle.png', 'newest.png']);
});
test('reads each file mtime only once when sorting by date', () => {
for (let i = 0; i < 8; i++) {
writeFile(`img${i}.png`, (8 - i) * 1_000_000);
}
const spy = jest.spyOn(fs, 'statSync');
try {
const result = getImages(tmpDir, 'date');
expect(result).toEqual(['img7.png', 'img6.png', 'img5.png', 'img4.png', 'img3.png', 'img2.png', 'img1.png', 'img0.png']);
expect(spy).toHaveBeenCalledTimes(8);
} finally {
spy.mockRestore();
}
});
test('falls back to mtime 0 if a file disappears between readdir and stat', () => {
writeFile('survivor.png', 2_000_000);
writeFile('ghost.png', 1_000_000);
const realStat = fs.statSync;
const spy = jest.spyOn(fs, 'statSync').mockImplementation((p, ...rest) => {
if (typeof p === 'string' && p.endsWith('ghost.png')) {
const err = new Error('ENOENT');
err.code = 'ENOENT';
throw err;
}
return realStat(p, ...rest);
});
try {
expect(getImages(tmpDir, 'date')).toEqual(['ghost.png', 'survivor.png']);
} finally {
spy.mockRestore();
}
});
test('propagates non-ENOENT stat errors (e.g. EACCES) instead of masking them', () => {
writeFile('readable.png', 1_000_000);
writeFile('forbidden.png', 2_000_000);
const realStat = fs.statSync;
const spy = jest.spyOn(fs, 'statSync').mockImplementation((p, ...rest) => {
if (typeof p === 'string' && p.endsWith('forbidden.png')) {
const err = new Error('EACCES');
err.code = 'EACCES';
throw err;
}
return realStat(p, ...rest);
});
try {
expect(() => getImages(tmpDir, 'date')).toThrow(/EACCES/);
} finally {
spy.mockRestore();
}
});
test('filters to image types by default', () => {
writeFile('keep.png');
writeFile('keep.jpg');
writeFile('drop.mp4');
writeFile('drop.mp3');
writeFile('drop.txt');
writeFile('no-extension');
expect(getImages(tmpDir, 'name')).toEqual(['keep.jpg', 'keep.png']);
});
test('filters to video types when requested', () => {
writeFile('drop.png');
writeFile('keep.mp4');
writeFile('keep.webm');
expect(getImages(tmpDir, 'name', MEDIA_REQUEST_TYPE.VIDEO)).toEqual(['keep.mp4', 'keep.webm']);
});
test('filters to audio types when requested', () => {
writeFile('drop.png');
writeFile('keep.mp3');
writeFile('keep.wav');
expect(getImages(tmpDir, 'name', MEDIA_REQUEST_TYPE.AUDIO)).toEqual(['keep.mp3', 'keep.wav']);
});
test('accepts combined media-type bitmask', () => {
writeFile('img.png');
writeFile('clip.mp4');
writeFile('song.mp3');
const result = getImages(tmpDir, 'name', MEDIA_REQUEST_TYPE.IMAGE | MEDIA_REQUEST_TYPE.AUDIO);
expect(result).toEqual(['img.png', 'song.mp3']);
});
test('skips subdirectories', () => {
writeFile('real.png');
fs.mkdirSync(path.join(tmpDir, 'sub.png'));
expect(getImages(tmpDir, 'name')).toEqual(['real.png']);
});
test('returns empty array for an empty directory', () => {
expect(getImages(tmpDir, 'name')).toEqual([]);
expect(getImages(tmpDir, 'date')).toEqual([]);
});
});