Compare commits

...
Author SHA1 Message Date
Wolfsblvt 28669f4985 fix: reduce redundant filter item opacity, fix JSDoc param name
- Lower opacity from 0.45 to 0.33 for better visual distinction of redundant character filter items
- Fix JSDoc parameter name: choiceDisplay → element in getFilterItemForChoice()
2026-05-19 01:04:53 +02:00
Wolfsblvt bf2a0143c3 fix: close dropdown on toggle, warn singleton conflicts in slash commands
- Pass closeDrawer: true to select2ChoiceClickSubscribe so the dropdown
  doesn't open when clicking chips to cycle filter state
- Extract warnCharacterFilterSingletonConflicts() helper
- Call it in setEntryFieldCallback when characterFilter is set via slash
  commands, so users get the same impossible-filter warning as in the UI
2026-05-19 01:03:30 +02:00
Wolfsblvt 08d91b58b5 fix: click handler + UX for singleton type required state
- Fix click-to-toggle: navigate up to .select2-selection__choice__display
  when event.target is a child element (icon, text node)
- Add singleton-type awareness: character and persona can only be one active
  at a time, so when one is REQUIRED, others of same type are redundant
- Visual: redundant items get dimmed (opacity 0.45)
- Toast warning: setting to required when another of same type is already
  required (impossible filter)
- Toast info: setting to required when others of same type exist (redundant)
2026-05-19 00:49:23 +02:00
Wolfsblvt 600aaf5416 fix: character filter render bug, migration AND logic, slash command JSON
- Fix initial render: fill options BEFORE initializing select2 so templates apply on load
- Fix P1 migration: when old format has both names AND tags (include mode), migrate
  names as ONE_OF and tags as REQUIRED to preserve the AND relationship between groups
- Fix P2 slash command: /getentryfield field=characterFilter now returns proper JSON
  instead of going through substituteParams which coerced objects to [object Object]
2026-05-19 00:42:43 +02:00
Wolfsblvt 45c5160215 refactor: character filter UI — optgroups, FA icons, dropdown state indicators
- Group options into Characters/Tags/Personas optgroups in dropdown
- Replace [Character]/[Tag]/[Persona] text prefixes with FA icons
  (fa-address-card, fa-tags, fa-face-smile)
- Show state indicator (○/✓/✗) in dropdown for already-selected items
- Use data attributes on rendered chips for robust matching (no text-based matching)
- Refactor getFilterItemForDisplayText → getFilterItemForChoice
- Safe DOM construction in templateResult/templateSelection (no HTML injection)
2026-05-19 00:35:19 +02:00
Wolfsblvt aa441f3c77 feat: enhanced WI character filter with three-state logic and persona support
- New data model: characterFilter is an array of {type, name, state} items
- Types: character, tag, persona (CHARACTER_FILTER_TYPES enum)
- Three states: oneOf (OR, default), required (AND), excluded (NOT)
- Click select2 choices to cycle states with visual indicators
- [Character] prefix on character names for consistent display
- Migration from legacy object format and intermediate exclude boolean format
- Slash commands: backwards compat with deprecation warnings for old fields
- Deprecated fields hidden from slash command autocomplete
- Removed global Exclude checkbox from UI
2026-05-18 23:46:58 +02:00
Blueberry 93bd9e217e Macros: Access array and object elements (#4383) (#5649)
* Macros: Access array items by index (#4383)

* Macros: Access array and object elements (#4383)

* fix spacing

* setvarkey setvarindex

* setglobalvarindex getglobalvarindex
2026-05-19 00:13:47 +03:00
Cohee fd582be5ca Add rate limit to account reset (#5603) 2026-05-18 23:25:50 +03:00
Cohee 3a453d4cfa Enforce stricter npm source restrictions in .npmrc (#5663) 2026-05-18 22:51:39 +03:00
40ca51f4f1 Pollinations: Add API endpoint selection (#5625)
* Split Pollinations into two separate API providers: (Key) and (No Key)

- Replaces the single "Pollinations" source with two distinct entries:
  - "Pollinations (Key)": uses gen.pollinations.ai/v1 with Bearer token auth,
    supports BYOP OAuth flow with app key pk_Gu8Ta8q6QhS67hSg and manual key entry
  - "Pollinations (No Key)": uses text.pollinations.ai/v1, no authentication required
- Renames CHAT_COMPLETION_SOURCES.POLLINATIONS to POLLINATIONS_KEY/POLLINATIONS_NOKEY
  throughout the codebase (constants, endpoints, frontend scripts)
- Adds BYOP authorize button and OAuth callback handler for key-based source
- Updates all data-source attributes, secret key mappings, model selectors,
  tool-calling, reasoning, slash-commands, caption, and SD extension references

https://claude.ai/code/session_01T57Cm84cv2GiSL4DPCccBj

* Fix POLLINATIONS_NOKEY: exempt from API key check, fix placeholder text

- Add POLLINATIONS_NOKEY to the keyless providers exemption in the
  /generate endpoint's API key guard (was hitting the 400 check)
- Remove 'pk_...' from the key input placeholder since pk_ is the
  app key used in the BYOP auth link, not the user's secret key

https://claude.ai/code/session_01T57Cm84cv2GiSL4DPCccBj

* Add Pollinations anonymous/authenticated endpoint selector

Implements reviewer feedback to use a single Pollinations provider with
an endpoint dropdown (similar to Z.AI) rather than two separate sources.

- Add POLLINATIONS_ENDPOINT enum (anonymous / authenticated)
- Anonymous uses text.pollinations.ai/v1, no API key required
- Authenticated uses gen.pollinations.ai/v1, requires sk_... key with BYOP OAuth support
- Key input and BYOP button are hidden when anonymous endpoint is selected
- Backend skips key guard for anonymous requests
- Reasoning effort and JSON schema only sent for authenticated mode
- Connection status check passes for anonymous without a saved key

https://claude.ai/code/session_01T57Cm84cv2GiSL4DPCccBj

* Fix broken Pollinations references after resolving merge conflicts

- Replace POLLINATIONS_KEY/NOKEY in CHAT_COMPLETION_SOURCES with POLLINATIONS
- Fix SECRET_KEYS.POLLINATIONS → SECRET_KEYS.POLLINATIONS_KEY in backend
- Update all chat_completion_sources references in openai.js to use unified POLLINATIONS
- Consolidate duplicate model select/change handlers into single pollinations_model
- Keep backward compat in caption-image handler for pollinations_key/nokey multimodal API
- Fix openai.js inline handler to route pollinations to correct endpoint based on endpoint field

https://claude.ai/code/session_01T57Cm84cv2GiSL4DPCccBj

* Complete Pollinations unification: remove all pollinations_key/nokey splits

- Fix committed merge conflict in openai.js (Wolfsblvt review)
- Replace POLLINATIONS_KEY/NOKEY in chat_completion_source dropdown with single POLLINATIONS option
- Replace pollinations_key,pollinations_nokey in all data-source attributes with pollinations
- Merge duplicate /pollinations_key and /pollinations_nokey multimodal routes into single /pollinations
- Update caption extension: single "Pollinations" option using pollinations_endpoint from oai_settings
- Update slash-commands.js model selector to single pollinations entry
- Clean up caption-image handler (openai.js) to use only 'pollinations' api type
- Pass pollinations_endpoint in caption request body (shared.js)
- Add settings migration: pollinations_key → pollinations, pollinations_nokey → pollinations (anonymous)

https://claude.ai/code/session_01T57Cm84cv2GiSL4DPCccBj

* Address Cohee review: named constants, mock key, revert POLLINATIONS_KEY rename, default to authenticated

- Use POLLINATIONS_ENDPOINT named constants throughout (no magic 'anonymous' strings)
- Use mock key pattern (set key to POLLINATIONS_ENDPOINT.ANONYMOUS value) so no guard exception needed
- Revert POLLINATIONS_KEY rename back to POLLINATIONS in secrets.js files
- Default pollinations_endpoint to AUTHENTICATED so saved keys aren't bypassed
- Remove redundant isPollinationsAnon check from getReasoningEffort() (backend handles it)
- Unify tool-calling.js, caption, shared, stable-diffusion to single POLLINATIONS source

https://claude.ai/code/session_01T57Cm84cv2GiSL4DPCccBj

* Fix ESLint padded-blocks error in BYOP OAuth callback

https://claude.ai/code/session_01T57Cm84cv2GiSL4DPCccBj

* fix: regression in caption API validation

* fix: remove unneeded migration

* fix: remove duplicate keyless check in apiSourceConfig

* fix: regression in extractReasoningFromData

* refactor: simplify UI unhide logic

* fix: remove BYOP flow due to security concerns

* fix: use a string instead of a constant reference for placeholder key

* fix: reconnect when switching endpoints

* feat: support pollinations in /api-url command

* fix: remove endpoint check from image generation (it always uses authenticated)

* fix: default to authenticated

* fix: use a named constant in auto-connect logic

* fix: filter by modality in anon models list

* fix: remove bespoke model loading logic for anon endpoint

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-05-18 22:45:53 +03:00
Wolfsblvt 060f224f28 Add MessageFormatter: a structured hook system for extensions to transform message content pre-DOM (#5652)
* feat(core): add MessageFormatter pipeline for extension message hooks

Introduces a new MessageFormatter singleton class (public/scripts/message-formatter.js)
that allows extensions to transform message text at well-defined stages of the
messageFormatting() pipeline, before the result reaches the DOM.

The pipeline exposes three hook stages (all before DOMPurify sanitization):
- BEFORE_REGEX  -- raw Markdown, before custom regex rules
- AFTER_REGEX   -- plain Markdown, after regex, before showdown conversion
- AFTER_MARKDOWN -- rendered HTML, after showdown, before sanitization (default)

There is intentionally no post-sanitize stage to prevent XSS vectors.

Extensions register hooks via getContext().messageFormatter.addHook(fn, { stage, order }).
Stage and order enums (formatting_stage, hook_order) are re-exported on the
singleton instance itself so extensions need no additional imports beyond getContext().

The formatter also exposes a .format() shim over messageFormatting() for
convenience. messageFormatting() itself gains full JSDoc documentation.

* feat(core): add pipeline documentation to MessageFormatter.format()

Adds detailed JSDoc documentation to the MessageFormatter.format() method
describing the complete 11-step message formatting pipeline, from prompt-bias
stripping through DOMPurify sanitization. Clarifies that all extension hooks
(beforeRegex, afterRegex, afterMarkdown) run before sanitization to ensure
their output is always sanitised.

* feat(core): add async detection and non-string return guards to MessageFormatter

Adds runtime and registration-time safety checks to the MessageFormatter hook system:
- Throws TypeError at registration if an async function is passed to addHook()
- Emits console warning and ignores return value if a hook returns non-string at runtime
- Detects Promise returns and includes helpful hint that hook may be async
- Updates JSDoc to clarify synchronous string return requirement and error conditions

* test(frontend): add comprehensive e2e tests for MessageFormatter

Adds full test coverage for the MessageFormatter singleton class including:
- Module exports validation (formatting_stage, hook_order enums)
- Singleton instance constant re-exports
- Registration validation (rejects non-functions, async functions, unknown stages)
- Hook execution pipeline (stage isolation, order sorting, context freezing)
- Error handling (continues on throw, warns on non-string/Promise returns)
- Stage injection

* refactor(core): rename ch_name parameter to characterName in MessageFormatter

Renames the `ch_name` parameter to `characterName` throughout MessageFormatter for improved code clarity and consistency with modern naming conventions. Updates JSDoc typedef and method signatures.
2026-05-18 21:51:16 +03:00
Wolfsblvt aec9754b31 Fix: Scoped comment macro {{//}}...{{///}} not removing its content (#5643)
* fix: handle scoped comment macro closing tag tokenization edge case

The lexer greedily tokenizes '//' before '/', causing {{///}} to parse as {{// /}} instead of {{/ //}}. Added special case detection in MacroCstWalker to check if the comment macro's first argument starts with '/' and treat it as a closing block. Removed list/strictArgs flags from comment macro definition and added comprehensive e2e tests for scoped comment blocks.

* refactor: DRY, remove unneccessarily duplicated private extractMacroInfo
2026-05-18 21:48:49 +03:00
Wolfsblvt 9f8c3e156a Lorebook "Apply Current Sorting" — Order control, ascending mode, step size, and live validation feedback (#5653)
* feat: enhance world info sorting with ascending/descending modes and animation

- Add autoFocus property to popup inputs with autofocus attribute and tabIndex
- Add slide animation to setInfoBlock/clearInfoBlock with configurable animate option
- Replace simple input prompt with detailed popup for applying current sorting
- Add ascending/descending order toggle for world info entry sorting
- Add configurable step value between order assignments
- Add real-time warning when starting value is below

* fix: improve world info sorting warning to account for step value

- Update warning calculation to consider step size when detecting order collisions
- Add step input parameter to updateWarning function
- Attach input listener to step field for real-time warning updates
- Display more detailed warning message showing the calculated final order value
2026-05-18 20:14:45 +03:00
Wolfsblvt 355598bb30 fix: disable pipe/filter feature to prevent breaking macros with pipe characters in arguments (#5644)
Temporarily commented out Filter.Pipe and Filter.EscapedPipe token handling in MacroLexer to fix issue where pipe characters in argument values (e.g., {{setvar::foo::|bar}}) were incorrectly parsed as filter operators. Added regression tests for pipe handling in argument values and skipped existing output modifier tests until filter flag (>) logic is properly implemented.

Resolves: #5618
2026-05-18 19:56:38 +03:00
mekineerandCohee 45d166ff6a fix(autocomplete): guard MutationObserver against detached textarea (#5660)
When a textarea is removed from the DOM before the autocomplete
clone-positioning logic runs, parentElement is null and
MutationObserver.observe throws. This can happen when extensions
abort generation early (via generate_interceptor) and the textarea
is torn down before autocomplete finishes setup.

Add a null check so the observer is only attached when the parent
still exists.

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2026-05-18 19:35:36 +03:00
realyxl 69cf5571ba Update outdated readme-zh_cn.md and readme-ja_jp.md (#5659) 2026-05-18 19:33:36 +03:00
加乘 81be2c51a2 Update outdated readme-zh_tw.md (#5639) 2026-05-18 19:32:19 +03:00
DeathStalker471 a900958bef chore: Sync NanoGPT providers: Tensorix, and Xiaomi (#5646)
* Sync NanoGPT providers, Tensorix, and Xiaomi

* fix lint
2026-05-18 19:31:18 +03:00
underscore_x 56061f793c fix mislabelled popup for "Replace existing Quick Reply set" (#5662)
* fix mislabelled popup for "Replace existing Quick Reply Set"

it currently provides a popup asking for confirmation "Replace existing World Info" when user tries to create a new QR Set with an existing name.

Checked that it does not conflict/reuse anything from the actual world info screen.

* capitalisation
2026-05-18 19:30:26 +03:00
34 changed files with 1727 additions and 269 deletions
+2 -1
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は現在200人以上の貢献者と2年間の独立した開発を経て、知識豊富なAI愛好家のための主要なソフトウェアとして機能し続けています。
2023年2月にTavernAI 1.2.8のフォークとして始まり、SillyTavernは現在300人以上の貢献者と3年間の独立した開発を経て、知識豊富なAI愛好家のための主要なソフトウェアとして機能し続けています。
## 私たちのビジョン
@@ -79,6 +79,7 @@ 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ガイド
+2 -1
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 的一个分支开始,如今已拥有超过 200 名贡献者和 2 年的独立开发经验,并继续作为资深 AI 爱好者领先的软件。
SillyTavern 于 2023 年 2 月作为 TavernAI 1.2.8 的一个分支开始,如今已拥有超过 300 名贡献者和 3 年的独立开发经验,并继续作为资深 AI 爱好者领先的软件。
## 我们的愿景
@@ -79,6 +79,7 @@ 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) 提供
+3 -2
View File
@@ -26,7 +26,7 @@ SillyTavern 提供一個統一的前端介面,整合多種大型語言模型
SillyTavern(簡稱 ST)是一款本地安裝的使用者介面,讓您能與大型語言模型(LLM)、影像生成引擎以及語音合成模型互動的前端。
SillyTavern 起源於 2023 年 2 月,作為 TavernAI 1.2.8 的分支版本發展至今。目前已有超過 200 位貢獻者,並擁有超過兩年的獨立開發歷史。如今,它已成為 AI 愛好者中備受推崇的軟體之一。
SillyTavern 起源於 2023 年 2 月,作為 TavernAI 1.2.8 的分支版本發展至今。目前已有超過 300 位貢獻者,並擁有超過三年的獨立開發歷史。如今,它已成為 AI 愛好者中備受推崇的軟體之一。
## 我們的願景
@@ -42,7 +42,7 @@ SillyTavern 的硬體需求相當低。任何能夠運行 NodeJS 20 或更高版
### 歡迎加入我們的 Discord 伺服器
| [![][discord-shield-badge]][discord-link] | [加入我們的 Disocrd 伺服器](https://discord.gg/sillytavern) 以獲得技術支援、分享您喜愛的角色與提示詞。 |
| [![][discord-shield-badge]][discord-link] | [加入我們的 Discord 伺服器](https://discord.gg/sillytavern) 以獲得技術支援、分享您喜愛的角色與提示詞。 |
| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
或直接聯繫開發者:
@@ -79,6 +79,7 @@ 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) 編寫
+4
View File
@@ -1,2 +1,6 @@
ignore-scripts=true
min-release-age=7
allow-directory=none
allow-file=none
allow-git=none
allow-remote=none
+2
View File
@@ -198,6 +198,8 @@ 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:
+59
View File
@@ -240,3 +240,62 @@ span.select2.select2-container .select2-selection__choice__remove:hover {
.select2_choice_clickable_buttonstyle+span.select2-container .select2-selection__choice__display:hover {
background-color: var(--white30a);
}
/* Character filter — selected chip base styling */
.select2-selection__choice.character_filter_oneOf .select2-selection__choice__display,
.select2-selection__choice.character_filter_required .select2-selection__choice__display,
.select2-selection__choice.character_filter_excluded .select2-selection__choice__display {
cursor: pointer;
}
/* required (AND) — green border */
.select2-container .select2-selection--multiple .select2-selection__choice.character_filter_required {
border-color: var(--active);
}
/* excluded (NOT) — red border, strikethrough, reduced opacity */
.select2-container .select2-selection--multiple .select2-selection__choice.character_filter_excluded {
border-color: var(--SmartThemeQuoteColor, #e74c3c) !important;
opacity: 0.85;
}
.select2-selection__choice.character_filter_excluded .select2-selection__choice__display {
text-decoration: line-through;
text-decoration-color: var(--SmartThemeQuoteColor, #e74c3c);
}
/* Character filter — dropdown state indicators */
.cf_option {
display: flex;
align-items: center;
gap: 0.4em;
}
.cf_option i {
width: 1.2em;
text-align: center;
opacity: 0.7;
}
.cf_state_indicator {
margin-left: auto;
font-weight: bold;
font-size: 0.9em;
}
.cf_state_indicator.cf_state_oneOf {
opacity: 0.5;
}
.cf_state_indicator.cf_state_required {
color: var(--active);
}
.cf_state_indicator.cf_state_excluded {
color: var(--SmartThemeQuoteColor, #e74c3c);
}
/* Character filter — redundant items (singleton type has a required item) */
.select2-container .select2-selection--multiple .select2-selection__choice.character_filter_redundant {
opacity: 0.33;
}
+21 -22
View File
@@ -3874,17 +3874,24 @@
</select>
</div>
<div id="pollinations_form" data-source="pollinations">
<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'.
<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>
</div>
<h4 data-i18n="Pollinations Model">Pollinations Model</h4>
<select id="model_pollinations_select">
@@ -7028,18 +7035,10 @@
<div class="flex-container wide100p flexGap10">
<div class="flex4 flex-container flexFlowColumn flexNoGap">
<div class="flex-container justifySpaceBetween">
<small for="characterFilter" data-i18n="Filter to Characters or Tags">
Filter to Characters or Tags
<small for="characterFilter">
<span data-i18n="Filter to Characters, Tags, or Personas">Filter to Characters, Tags, or Personas</span>
<div class="fa-solid fa-circle-info opacity50p" title="Click a selected item to cycle its filter mode: ○ One of (OR) → ✓ Required (AND) → ✗ Excluded (NOT)" data-i18n="[title]Click a selected item to cycle its filter mode: ○ One of (OR) → ✓ Required (AND) → ✗ Excluded (NOT)"></div>
</small>
<label class="checkbox_label flexNoGap margin-r5" for="character_exclusion">
<input type="checkbox" name="character_exclusion" />
<span>
<small title="Switch the Character/Tags filter around to exclude the listed characters and tags from matching for this entry" data-i18n="[title]Switch the Character/Tags filter around to exclude the listed characters and tags from matching for this entry">
<span data-i18n="Exclude">Exclude</span>
<div class="fa-solid fa-circle-info opacity50p"></div>
</small>
</span>
</label>
</div>
<div class="range-block-range">
<select name="characterFilter" multiple>
+42 -9
View File
@@ -282,6 +282,7 @@ 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';
@@ -1740,15 +1741,35 @@ export async function sendTextareaMessage() {
}
/**
* 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
* 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`.
*/
export function messageFormatting(mes, ch_name, isSystem, isUser, messageId, sanitizerOverrides = {}, isReasoning = false) {
if (!mes) {
@@ -1805,12 +1826,20 @@ 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) {
@@ -1889,6 +1918,10 @@ 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 } from './openai.js';
import { chat_completion_sources, oai_settings, POLLINATIONS_ENDPOINT } 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.chat_completion_source === chat_completion_sources.POLLINATIONS)
|| ((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.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)
+3 -1
View File
@@ -674,7 +674,9 @@ export class AutoComplete {
this.clone.remove();
}
});
mo.observe(this.textarea.parentElement, { childList: true });
if (this.textarea.parentElement) {
mo.observe(this.textarea.parentElement, { childList: true });
}
}
this.clone.style.height = `${inputRect.height}px`;
this.clone.style.left = `${inputRect.left}px`;
+1 -1
View File
@@ -592,7 +592,7 @@ export class ChatCompletionService {
}
// Ensure api-url is properly applied for all sources that accept it
['custom_url', 'vertexai_region', 'zai_endpoint', 'siliconflow_endpoint', 'minimax_endpoint'].forEach(field => {
['custom_url', 'vertexai_region', 'zai_endpoint', 'siliconflow_endpoint', 'minimax_endpoint', 'pollinations_endpoint'].forEach(field => {
// The order is: connection profile => CC preset => CC settings
overridePayload[field] = overridePayload[field] || settings[field] || oai_settings[field];
});
+3 -3
View File
@@ -3,7 +3,7 @@ import { getContext, getApiUrl, doExtrasFetch, extension_settings, modules, rend
import { appendMediaToMessage, chat_metadata, eventSource, event_types, getRequestHeaders, saveChatConditional, saveSettingsDebounced, substituteParams } from '../../../script.js';
import { getMessageTimeStamp } from '../../RossAscends-mods.js';
import { SECRET_KEYS, secret_state } from '../../secrets.js';
import { oai_settings } from '../../openai.js';
import { oai_settings, POLLINATIONS_ENDPOINT } from '../../openai.js';
import { getMultimodalCaption } from '../shared.js';
import { textgen_types, textgenerationwebui_settings } from '../../textgen-settings.js';
import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
@@ -530,8 +530,8 @@ export async function init() {
return true;
}
// Custom API doesn't need additional checks
if (api === 'custom') {
// Custom API and anonymous Pollinations don't need additional checks
if (api === 'custom' || (api === 'pollinations' && oai_settings.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS)) {
return true;
}
}
@@ -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 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.`);
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.`);
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 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.`);
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.`);
if (replace) {
const idx = QuickReplySet.list.indexOf(oldQrs);
await this.doDeleteQrSet(oldQrs);
+7 -2
View File
@@ -1,7 +1,7 @@
import { CONNECT_API_MAP, createModelIcon, getRequestHeaders, substituteParams } from '../../script.js';
import { extension_settings, openThirdPartyExtensionMenu } from '../extensions.js';
import { t } from '../i18n.js';
import { oai_settings, proxies, ZAI_ENDPOINT } from '../openai.js';
import { oai_settings, proxies, ZAI_ENDPOINT, POLLINATIONS_ENDPOINT } from '../openai.js';
import { SECRET_KEYS, secret_state } from '../secrets.js';
import { textgen_types, textgenerationwebui_settings } from '../textgen-settings.js';
import { getTokenCountAsync } from '../tokenizers.js';
@@ -126,6 +126,10 @@ export async function getMultimodalCaption(base64Img, prompt) {
requestBody.zai_endpoint = oai_settings.zai_endpoint || ZAI_ENDPOINT.COMMON;
}
if (extension_settings.caption.multimodal_api === 'pollinations') {
requestBody.pollinations_endpoint = oai_settings.pollinations_endpoint || POLLINATIONS_ENDPOINT.AUTHENTICATED;
}
if (extension_settings.caption.multimodal_api === 'workers_ai') {
requestBody.workers_ai_account_id = oai_settings.workers_ai_account_id;
}
@@ -284,7 +288,7 @@ function throwIfInvalidModel(useReverseProxy) {
throw new Error('Z.AI API key is not set.');
}
if (multimodalApi === 'pollinations' && !secret_state[SECRET_KEYS.POLLINATIONS]) {
if (multimodalApi === 'pollinations' && oai_settings.pollinations_endpoint !== POLLINATIONS_ENDPOINT.ANONYMOUS && !secret_state[SECRET_KEYS.POLLINATIONS]) {
throw new Error('Pollinations API key is not set.');
}
@@ -449,6 +453,7 @@ 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'],
@@ -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,6 +155,62 @@ 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,
@@ -302,4 +358,60 @@ 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);
},
});
}
+45 -33
View File
@@ -189,7 +189,21 @@ class MacroCstWalker {
// Check for closing block flag
const flagTokens = /** @type {IToken[]} */ (children.flags || []);
const isClosing = flagTokens.some(token => token.image === MacroFlagType.CLOSING_BLOCK);
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;
}
}
}
return {
name,
@@ -227,7 +241,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) {
@@ -1098,6 +1112,34 @@ 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.
@@ -1146,7 +1188,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({
@@ -1254,36 +1296,6 @@ 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.
+7 -2
View File
@@ -214,11 +214,16 @@ const Def = {
// Macro args allow nested macros
enter(Tokens.Macro.Start, modes.macro_def),
// PIPE/FILTER FEATURE DISABLED: Lines below commented out until pipe/filter feature is fully implemented.
// Currently, having these active breaks macros that use | as a regular character in argument values (e.g., {{setvar::foo::|bar}})
// See: https://github.com/SillyTavern/SillyTavern/issues/5618
// TODO: Re-enable when filter flag (>) logic is properly implemented to conditionally enable pipe parsing
// We allow escaped pipes to not start output modifiers. We need to capture this first, before the pipe
using(Tokens.Filter.EscapedPipe),
// using(Tokens.Filter.EscapedPipe),
// If at any place during args writing there is a pipe, we lex it as an output identifier, and then continue with lex its args
enter(Tokens.Filter.Pipe, modes.macro_filter_modifer),
// enter(Tokens.Filter.Pipe, modes.macro_filter_modifer),
using(Tokens.Args.DoubleColon),
using(Tokens.Args.Colon),
+259
View File
@@ -0,0 +1,259 @@
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;
+23 -1
View File
@@ -267,6 +267,11 @@ export const ZAI_ENDPOINT = {
CODING: 'coding',
};
export const POLLINATIONS_ENDPOINT = {
AUTHENTICATED: 'authenticated',
ANONYMOUS: 'anonymous',
};
export const SILICONFLOW_ENDPOINT = {
GLOBAL: 'global',
CN: 'cn',
@@ -335,6 +340,7 @@ 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],
@@ -451,6 +457,7 @@ 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',
@@ -2933,6 +2940,10 @@ 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;
}
@@ -4428,6 +4439,10 @@ 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`);
@@ -5934,7 +5949,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 },
[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.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 },
};
@@ -6017,6 +6032,7 @@ 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');
@@ -7193,6 +7209,12 @@ 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,6 +85,7 @@ 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
*/
/**
@@ -336,6 +337,7 @@ 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;
@@ -362,6 +364,7 @@ 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');
@@ -384,6 +387,7 @@ 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');
@@ -409,6 +413,7 @@ 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', () => {
+29 -2
View File
@@ -70,7 +70,7 @@ import { hideChatMessageRange } from './chats.js';
import { getContext, saveMetadataDebounced } from './extensions.js';
import { getRegexedString, regex_placement } from './extensions/regex/engine.js';
import { findGroupMemberId, groups, is_group_generating, openGroupById, regenerateGroup, resetSelectedGroup, saveGroupChat, selected_group, getGroupMembers } from './group-chats.js';
import { chat_completion_sources, MINIMAX_ENDPOINT, oai_settings, promptManager, SILICONFLOW_ENDPOINT, ZAI_ENDPOINT } from './openai.js';
import { chat_completion_sources, MINIMAX_ENDPOINT, oai_settings, POLLINATIONS_ENDPOINT, promptManager, SILICONFLOW_ENDPOINT, ZAI_ENDPOINT } from './openai.js';
import { user_avatar } from './personas.js';
import { addEphemeralStoppingString, chat_styles, context_presets, flushEphemeralStoppingStrings, playMessageSound, power_user } from './power-user.js';
import { SERVER_INPUTS, textgen_types, textgenerationwebui_settings } from './textgen-settings.js';
@@ -3135,6 +3135,7 @@ 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')),
],
@@ -3168,7 +3169,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, 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, 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.`}
</div>
`,
}));
@@ -6686,6 +6687,32 @@ 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,6 +110,7 @@ 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 {
@@ -242,6 +243,7 @@ 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="XXXX">
<input type="text" name="code" class="text_pole" placeholder="XXXXXX">
</div>
</form>
+8
View File
@@ -258,6 +258,10 @@ const NANOGPT_PROVIDERS = [
'id': 'neuralwatt',
'label': 'Neuralwatt',
},
{
'id': 'tensorix',
'label': 'Tensorix',
},
{
'id': 'nextbit',
'label': 'NextBit',
@@ -310,6 +314,10 @@ const NANOGPT_PROVIDERS = [
'id': 'wandb',
'label': 'Weights & Biases',
},
{
'id': 'xiaomi',
'label': 'Xiaomi',
},
{
'id': 'zai',
'label': 'Z.AI',
+34 -12
View File
@@ -7,7 +7,7 @@ import {
} from '../lib.js';
import { getContext } from './extensions.js';
import { characters, getRequestHeaders, processDroppedFiles, this_chid, user_avatar } from '../script.js';
import { animation_duration, characters, getRequestHeaders, processDroppedFiles, this_chid, user_avatar } from '../script.js';
import { isMobile } from './RossAscends-mods.js';
import { collapseNewlines, power_user } from './power-user.js';
import { debounce_timeout } from './constants.js';
@@ -2786,32 +2786,54 @@ 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') {
export function setInfoBlock(target, content, type = 'info', { animate = true } = {}) {
if (!content) {
clearInfoBlock(target);
return;
}
const infoBlock = typeof target === 'string' ? document.querySelector(target) : target;
if (infoBlock) {
infoBlock.className = `info-block ${type}`;
if (typeof content === 'string') {
infoBlock.innerHTML = content;
} else {
infoBlock.innerHTML = '';
infoBlock.appendChild(content);
}
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);
}
}
/**
* 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) {
export function clearInfoBlock(target, { animate = true } = {}) {
const infoBlock = typeof target === 'string' ? document.querySelector(target) : target;
if (infoBlock && infoBlock.classList.contains('info-block')) {
if (!infoBlock || !infoBlock.classList.contains('info-block')) return;
if (animate) {
$(infoBlock).slideUp(animation_duration * 1.5, () => {
infoBlock.className = '';
infoBlock.innerHTML = '';
$(infoBlock).css('display', '');
});
} else {
infoBlock.className = '';
infoBlock.innerHTML = '';
}
+571 -150
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 } 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, setInfoBlock, clearInfoBlock } 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';
@@ -37,6 +37,34 @@ export const world_info_logic = {
AND_ALL: 3,
};
/**
* @enum {string} Types for character filter items
*/
export const CHARACTER_FILTER_TYPES = {
CHARACTER: 'character',
TAG: 'tag',
PERSONA: 'persona',
};
/**
* @enum {string} Filter states for individual character filter items.
* - ONE_OF: At least one item with this state must match (OR logic). This is the default.
* - REQUIRED: This specific item must match (AND logic).
* - EXCLUDED: If this item matches, the entry is filtered out (NOT logic).
*/
export const CHARACTER_FILTER_STATES = {
ONE_OF: 'oneOf',
REQUIRED: 'required',
EXCLUDED: 'excluded',
};
/** Ordered cycle for clicking through filter states */
const CHARACTER_FILTER_STATE_CYCLE = [
CHARACTER_FILTER_STATES.ONE_OF,
CHARACTER_FILTER_STATES.REQUIRED,
CHARACTER_FILTER_STATES.EXCLUDED,
];
/**
* @enum {number} Possible states of the WI evaluation
*/
@@ -1274,26 +1302,28 @@ function registerWorldInfoSlashCommands() {
}
// handle special cases, otherwise execute default logic
const filterItems = Array.isArray(entry.characterFilter) ? entry.characterFilter : [];
let fieldValue;
switch (field) {
case 'characterFilter':
// Return raw JSON — don't go through substituteParams array path
return JSON.stringify(filterItems);
case 'characterFilterNames':
if (entry.characterFilter) {
fieldValue = entry.characterFilter.names;
}
toastr.warning('[WI] characterFilterNames is deprecated. Use characterFilter instead.');
fieldValue = filterItems
.filter(f => f.type === CHARACTER_FILTER_TYPES.CHARACTER)
.map(f => f.name);
break;
case 'characterFilterTags':
if (entry.characterFilter) {
if (!entry.characterFilter.tags) {
return '';
}
//Find the tag objects corresponding to each ID in the array, then return the names
fieldValue = tags.filter((tag) => entry.characterFilter.tags.includes(tag.id)).map((tag) => tag.name);
}
toastr.warning('[WI] characterFilterTags is deprecated. Use characterFilter instead.');
fieldValue = tags
.filter(tag => filterItems.some(f => f.type === CHARACTER_FILTER_TYPES.TAG && f.name === tag.id))
.map(tag => tag.name);
break;
case 'characterFilterExclude':
if (entry.characterFilter) {
fieldValue = entry.characterFilter.isExclude;
}
toastr.warning('[WI] characterFilterExclude is deprecated. Use characterFilter instead.');
// Return true if all items are excluded (backwards compat approximation)
fieldValue = filterItems.length > 0 && filterItems.every(f => f.state === CHARACTER_FILTER_STATES.EXCLUDED);
break;
default:
fieldValue = entry[field] ?? newWorldInfoEntryDefinition[field]?.default;
@@ -1346,19 +1376,10 @@ function registerWorldInfoSlashCommands() {
const field = args.field || 'content';
const tags = getContext().tags;
// characterFilter is an object with internal fields we need to access, which may also may be null and need to be populated
const createCharacterFilterFieldObjectIfNeeded = (currentEntry) => {
if (!currentEntry.characterFilter) {
Object.assign(
currentEntry,
{
characterFilter: {
isExclude: false,
names: [],
tags: [],
},
},
);
/** Ensures entry.characterFilter is a valid array */
const ensureCharacterFilterArray = (currentEntry) => {
if (!Array.isArray(currentEntry.characterFilter)) {
currentEntry.characterFilter = [];
}
};
@@ -1404,27 +1425,69 @@ function registerWorldInfoSlashCommands() {
let tagNames;
let charNames;
switch (field) {
case 'characterFilterNames':
createCharacterFilterFieldObjectIfNeeded(entry);
case 'characterFilter': {
ensureCharacterFilterArray(entry);
try {
const parsed = JSON.parse(value);
if (!Array.isArray(parsed)) {
toastr.warning('characterFilter must be a JSON array');
return '';
}
entry.characterFilter = parsed.filter(item =>
item && typeof item === 'object' &&
Object.values(CHARACTER_FILTER_TYPES).includes(item.type) &&
typeof item.name === 'string' &&
Object.values(CHARACTER_FILTER_STATES).includes(item.state),
);
} catch {
toastr.warning('characterFilter must be valid JSON');
return '';
}
warnCharacterFilterSingletonConflicts(entry.characterFilter);
setWIOriginalDataValue(data, uid, 'character_filter', entry.characterFilter);
break;
}
case 'characterFilterNames': {
toastr.warning('[WI] characterFilterNames is deprecated. Use characterFilter instead.');
ensureCharacterFilterArray(entry);
charNames = parseStringArray(value);
entry.characterFilter.names = charNames
const resolvedNames = charNames
.map((name) => getCharaFilename(null, { manualAvatarKey: findChar({ name, allowAvatar: true, preferCurrentChar: false, quiet: true })?.avatar }))
.filter(Boolean)
.filter(onlyUnique);
// Remove existing character items, then add new ones with default oneOf state
entry.characterFilter = entry.characterFilter.filter(f => f.type !== CHARACTER_FILTER_TYPES.CHARACTER);
for (const charName of resolvedNames) {
entry.characterFilter.push({ type: CHARACTER_FILTER_TYPES.CHARACTER, name: charName, state: CHARACTER_FILTER_STATES.ONE_OF });
}
setWIOriginalDataValue(data, uid, 'character_filter', entry.characterFilter);
break;
case 'characterFilterTags':
createCharacterFilterFieldObjectIfNeeded(entry);
}
case 'characterFilterTags': {
toastr.warning('[WI] characterFilterTags is deprecated. Use characterFilter instead.');
ensureCharacterFilterArray(entry);
tagNames = parseStringArray(value);
//Find the tag objects corresponding to each name in the user array, then return an array of the corresponding IDs
entry.characterFilter.tags = tags.filter((tag) => tagNames.includes(tag.name)).map((tag) => tag.id);
const tagIds = tags.filter((tag) => tagNames.includes(tag.name)).map((tag) => tag.id);
// Remove existing tag items, then add new ones with default oneOf state
entry.characterFilter = entry.characterFilter.filter(f => f.type !== CHARACTER_FILTER_TYPES.TAG);
for (const tagId of tagIds) {
entry.characterFilter.push({ type: CHARACTER_FILTER_TYPES.TAG, name: tagId, state: CHARACTER_FILTER_STATES.ONE_OF });
}
setWIOriginalDataValue(data, uid, 'character_filter', entry.characterFilter);
break;
case 'characterFilterExclude':
createCharacterFilterFieldObjectIfNeeded(entry);
entry.characterFilter.isExclude = isTrueBoolean(value);
}
case 'characterFilterExclude': {
toastr.warning('[WI] characterFilterExclude is deprecated. Use characterFilter instead.');
ensureCharacterFilterArray(entry);
const excludeValue = isTrueBoolean(value);
// Set state on all existing filter items (backwards compat: global toggle)
const targetState = excludeValue ? CHARACTER_FILTER_STATES.EXCLUDED : CHARACTER_FILTER_STATES.ONE_OF;
for (const item of entry.characterFilter) {
item.state = targetState;
}
setWIOriginalDataValue(data, uid, 'character_filter', entry.characterFilter);
break;
}
default:
if (Array.isArray(entry[field])) {
entry[field] = parseStringArray(value).filter(arrayFilter);
@@ -1565,9 +1628,11 @@ function registerWorldInfoSlashCommands() {
/** A collection of local enum providers for this context of world info */
const localEnumProviders = {
/** All possible fields that can be set in a WI entry */
wiEntryFields: () => Object.entries(newWorldInfoEntryDefinition).map(([key, value]) =>
new SlashCommandEnumValue(key, `[${value.type}] default: ${(typeof value.default === 'string' ? `'${value.default}'` : JSON.stringify(value.default))}`,
enumTypes.enum, enumIcons.getDataTypeIcon(value.type))),
wiEntryFields: () => Object.entries(newWorldInfoEntryDefinition)
.filter(([_, value]) => !value.deprecated)
.map(([key, value]) =>
new SlashCommandEnumValue(key, `[${value.type}] default: ${(typeof value.default === 'string' ? `'${value.default}'` : JSON.stringify(value.default))}`,
enumTypes.enum, enumIcons.getDataTypeIcon(value.type))),
/** All existing UIDs based on the file argument as world name */
wiUids: (/** @type {import('./slash-commands/SlashCommandExecutor.js').SlashCommandExecutor} */ executor) => {
@@ -2051,6 +2116,7 @@ export async function loadWorldInfo(name) {
if (response.ok) {
const data = await response.json();
migrateWorldInfoData(name, data);
worldInfoCache.set(name, data);
return data;
}
@@ -2122,19 +2188,107 @@ function addMissingWorldInfoFields(data) {
entry.keysecondary = [];
}
// Ensure that the characterFilter is an object with the expected structure
if (!entry.characterFilter || typeof entry.characterFilter !== 'object' || Array.isArray(entry.characterFilter)) {
entry.characterFilter = {
isExclude: false,
names: [],
tags: [],
};
}
// Ensure that the characterFilter is a valid array (migrate old format if needed)
migrateCharacterFilter(entry);
});
return data;
}
/**
* Adds missing fields to WI entries that are present in the entry template, but not in the data.
* Additionally verify that array/object fields are of the expected type.
* @param {string} name - The name of the world to migrate
* @param {any[]} data WI entries
*/
function migrateWorldInfoData(name, data) {
let migrated = false;
// Migrate characterFilter format for all entries on load
if (data?.entries) {
for (const entry of Object.values(data.entries)) {
if (migrateCharacterFilter(entry))
migrated = true;
}
}
if (migrated) {
saveWorldInfo(name, data);
}
}
/**
* Migrates an entry's characterFilter from old formats to the current format.
* Handles: legacy object with isExclude/names/tags, and intermediate array with boolean exclude.
* Target format: array of `{ type, name, state }` items.
* @param {object} entry - The WI entry to migrate
* @returns {boolean} - Whether anything was migrated
*/
function migrateCharacterFilter(entry) {
// Legacy object format: { isExclude, names, tags }
if (entry.characterFilter && !Array.isArray(entry.characterFilter) && typeof entry.characterFilter === 'object') {
const oldFilter = entry.characterFilter;
const newFilter = [];
const hasNames = Array.isArray(oldFilter.names) && oldFilter.names.length > 0;
const hasTags = Array.isArray(oldFilter.tags) && oldFilter.tags.length > 0;
if (oldFilter.isExclude) {
// Exclude mode: all items become EXCLUDED
if (hasNames) {
for (const name of oldFilter.names) {
newFilter.push({ type: CHARACTER_FILTER_TYPES.CHARACTER, name, state: CHARACTER_FILTER_STATES.EXCLUDED });
}
}
if (hasTags) {
for (const tag of oldFilter.tags) {
newFilter.push({ type: CHARACTER_FILTER_TYPES.TAG, name: tag, state: CHARACTER_FILTER_STATES.EXCLUDED });
}
}
} else if (hasNames && hasTags) {
// Both names and tags in include mode: old logic was AND between groups.
// Names → ONE_OF (character must be one of these)
// Tags → REQUIRED (preserves AND relationship: tags must also match)
for (const name of oldFilter.names) {
newFilter.push({ type: CHARACTER_FILTER_TYPES.CHARACTER, name, state: CHARACTER_FILTER_STATES.ONE_OF });
}
for (const tag of oldFilter.tags) {
newFilter.push({ type: CHARACTER_FILTER_TYPES.TAG, name: tag, state: CHARACTER_FILTER_STATES.REQUIRED });
}
} else {
// Only names or only tags: ONE_OF preserves exact old behavior
if (hasNames) {
for (const name of oldFilter.names) {
newFilter.push({ type: CHARACTER_FILTER_TYPES.CHARACTER, name, state: CHARACTER_FILTER_STATES.ONE_OF });
}
}
if (hasTags) {
for (const tag of oldFilter.tags) {
newFilter.push({ type: CHARACTER_FILTER_TYPES.TAG, name: tag, state: CHARACTER_FILTER_STATES.ONE_OF });
}
}
}
console.debug('[WI] Migrated old characterFilter object format for entry', entry.uid);
entry.characterFilter = newFilter;
return true;
}
// Normalize non-array to empty array
if (!Array.isArray(entry.characterFilter)) {
entry.characterFilter = [];
return true;
}
// Intermediate array format: items may have boolean 'exclude' instead of 'state'
for (const item of entry.characterFilter) {
if (!item.state || !Object.values(CHARACTER_FILTER_STATES).includes(item.state)) {
item.state = item.exclude ? CHARACTER_FILTER_STATES.EXCLUDED : CHARACTER_FILTER_STATES.ONE_OF;
delete item.exclude;
}
}
return false;
}
/**
* Sorts the given data based on the selected sort option
*
@@ -2495,45 +2649,125 @@ 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;
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 contentEl = document.createElement('div');
const result = await Popup.show.input(t`Apply Current Sorting`, content, '100', { okButton: t`Apply`, cancelButton: 'Cancel' });
if (!result) return;
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 start = Number(result);
if (isNaN(start) || start < 0) {
toastr.error(t`Invalid number: ${result}`, t`Apply Current Sorting`);
toastr.error(t`Invalid starting value: ${start}`, t`Apply Current Sorting`);
return;
}
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`);
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`);
}
// 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, current = start;
for (const entry of entries) {
const newOrder = Math.max(current--, 0);
if (entry.order === newOrder) continue;
let updated = 0;
entries.forEach((entry, index) => {
const newOrder = ascending
? start + index * step
: Math.max(start - index * step, 0);
if (entry.order === newOrder) return;
entry.order = newOrder;
setWIOriginalDataValue(data, entry.order, 'order', entry.order);
setWIOriginalDataValue(data, entry.uid, 'order', entry.order);
updated++;
}
});
if (updated > 0) {
toastr.info(`Updated ${updated} Order values`, 'Apply Custom Sorting');
toastr.info(t`Updated ${updated} Order values`, t`Apply Current Sorting`);
await saveWorldInfo(name, data, true);
updateEditor(navigation_option.previous);
} else {
toastr.info('All values up to date', 'Apply Custom Sorting');
toastr.info(t`All values up to date`, t`Apply Current Sorting`);
}
});
@@ -3003,50 +3237,132 @@ function updatePosOrdDisplayHelper({ template, data, uid }) {
template.find('.world_entry_form_position_value').text(`(${posText} ${entry.order})`);
}
/** FA icon classes for each character filter type */
const CHARACTER_FILTER_TYPE_ICONS = {
[CHARACTER_FILTER_TYPES.CHARACTER]: 'fa-solid fa-address-card',
[CHARACTER_FILTER_TYPES.TAG]: 'fa-solid fa-tags',
[CHARACTER_FILTER_TYPES.PERSONA]: 'fa-solid fa-face-smile',
};
/** State indicator symbols for rendering in dropdown and chips */
const CHARACTER_FILTER_STATE_INDICATORS = {
[CHARACTER_FILTER_STATES.ONE_OF]: { icon: '○', cls: 'cf_state_oneOf' },
[CHARACTER_FILTER_STATES.REQUIRED]: { icon: '✓', cls: 'cf_state_required' },
[CHARACTER_FILTER_STATES.EXCLUDED]: { icon: '✗', cls: 'cf_state_excluded' },
};
/**
* Helper to initialize character filter select2.
* Helper to initialize character filter select2 with custom templates.
* @param {JQuery<HTMLElement>} characterFilter - The select element for character filter.
* @param {object} wiData - The world info data object (for reading current filter states).
*/
function initCharacterFilterSelect2Helper(characterFilter) {
function initCharacterFilterSelect2Helper(characterFilter, wiData) {
/** Gets the current filter state for an option element, or null if not selected */
const getItemState = (optionElement) => {
const uid = characterFilter.data('uid');
const filter = Array.isArray(wiData.entries[uid]?.characterFilter) ? wiData.entries[uid].characterFilter : [];
const type = optionElement?.getAttribute('data-type');
const value = optionElement?.value;
const item = filter.find(f => f.type === type && f.name === value);
return item?.state ?? null;
};
/** Renders an option in the dropdown list */
const templateResult = (selectData) => {
if (!selectData.element) return selectData.text;
const type = selectData.element.getAttribute('data-type');
if (!type) return selectData.text;
const iconClass = CHARACTER_FILTER_TYPE_ICONS[type] || '';
const state = getItemState(selectData.element);
const $span = $('<span class="cf_option"></span>');
$span.append($(`<i class="${iconClass}"></i>`));
$span.append(document.createTextNode(` ${selectData.text} `));
if (state) {
const indicator = CHARACTER_FILTER_STATE_INDICATORS[state];
$span.append($(`<span class="cf_state_indicator ${indicator.cls}"></span>`).text(indicator.icon));
}
return $span;
};
/** Renders a selected item (chip) */
const templateSelection = (selectData) => {
if (!selectData.element) return selectData.text;
const type = selectData.element.getAttribute('data-type');
const iconClass = CHARACTER_FILTER_TYPE_ICONS[type] || '';
const $el = $('<span></span>').attr('data-filter-type', type).attr('data-filter-value', selectData.id);
$el.append($(`<i class="${iconClass}"></i>`));
$el.append(document.createTextNode(` ${selectData.text}`));
return $el;
};
if (!isMobile()) {
$(characterFilter).select2({
width: '100%',
placeholder: t`Tie this entry to specific characters or characters with specific tags`,
placeholder: t`Filter to characters, tags, or personas`,
allowClear: true,
closeOnSelect: false,
templateResult,
templateSelection,
});
}
}
/**
* Helper to fill character and tag options for character filter.
* Helper to fill character, tag, and persona options for character filter.
* @param {object} params - Parameters for filling options.
* @param {JQuery<HTMLElement>} params.characterFilter - The select element to fill with options.
* @param {object} params.entry - The entry object containing character filter data.
*/
function fillCharacterAndTagOptionsHelper({ characterFilter, entry }) {
function fillCharacterFilterOptionsHelper({ characterFilter, entry }) {
const filterItems = Array.isArray(entry.characterFilter) ? entry.characterFilter : [];
// Characters optgroup
const charGroup = document.createElement('optgroup');
charGroup.label = t`Characters`;
const characters = getContext().characters;
characters.forEach((character) => {
const option = document.createElement('option');
const name = character.avatar.replace(/\.[^/.]+$/, '') ?? character.name;
option.innerText = name;
option.selected = entry.characterFilter?.names?.includes(name);
option.setAttribute('data-type', 'character');
characterFilter.append(option);
option.value = name;
option.selected = filterItems.some(f => f.type === CHARACTER_FILTER_TYPES.CHARACTER && f.name === name);
option.setAttribute('data-type', CHARACTER_FILTER_TYPES.CHARACTER);
charGroup.append(option);
});
characterFilter.append(charGroup);
// Tags optgroup
const tagGroup = document.createElement('optgroup');
tagGroup.label = t`Tags`;
const tags = getContext().tags;
tags.forEach((tag) => {
const option = document.createElement('option');
option.innerText = `[Tag] ${tag.name}`;
option.selected = entry.characterFilter?.tags?.includes(tag.id);
option.innerText = tag.name;
option.value = tag.id;
option.setAttribute('data-type', 'tag');
characterFilter.append(option);
option.selected = filterItems.some(f => f.type === CHARACTER_FILTER_TYPES.TAG && f.name === tag.id);
option.setAttribute('data-type', CHARACTER_FILTER_TYPES.TAG);
tagGroup.append(option);
});
characterFilter.append(tagGroup);
// Personas optgroup
const personaGroup = document.createElement('optgroup');
personaGroup.label = t`Personas`;
const personas = power_user.personas;
Object.entries(personas).forEach(([avatarId, personaName]) => {
const option = document.createElement('option');
option.innerText = personaName;
option.value = avatarId;
option.selected = filterItems.some(f => f.type === CHARACTER_FILTER_TYPES.PERSONA && f.name === avatarId);
option.setAttribute('data-type', CHARACTER_FILTER_TYPES.PERSONA);
personaGroup.append(option);
});
characterFilter.append(personaGroup);
}
/**
* Helper to handle character filter changes.
* Rebuilds the characterFilter array from the selected options, preserving existing filter states.
* @param {object} params - Parameters for handling character filter changes.
* @param {JQuery<HTMLElement>} params.characterFilter - The select element for character filter.
* @param {object} params.data - The data object containing entries.
@@ -3061,24 +3377,109 @@ function handleCharacterFilterChangeHelper({ characterFilter, data, entry, name
}
const uid = $(this).data('uid');
const selected = $(this).find(':selected');
if ((!selected || selected?.length === 0) && !data.entries[uid].characterFilter?.isExclude) {
delete data.entries[uid].characterFilter;
if (!selected || selected.length === 0) {
data.entries[uid].characterFilter = [];
} else {
const names = selected.filter('[data-type="character"]').map((_, e) => e instanceof HTMLOptionElement && e.innerText).toArray();
const tags = selected.filter('[data-type="tag"]').map((_, e) => e instanceof HTMLOptionElement && e.value).toArray();
Object.assign(
data.entries[uid],
{
characterFilter: {
isExclude: data.entries[uid].characterFilter?.isExclude ?? false,
names: names,
tags: tags,
},
},
);
const existingFilter = Array.isArray(data.entries[uid].characterFilter) ? data.entries[uid].characterFilter : [];
/** @type {Array<{type: string, name: string, state: string}>} */
const newFilter = [];
selected.each((_, el) => {
if (!(el instanceof HTMLOptionElement)) return;
const type = el.getAttribute('data-type');
const itemName = el.value;
// Preserve filter state from existing filter
const existing = existingFilter.find(f => f.type === type && f.name === itemName);
newFilter.push({
type,
name: itemName,
state: existing?.state ?? CHARACTER_FILTER_STATES.ONE_OF,
});
});
data.entries[uid].characterFilter = newFilter;
}
setWIOriginalDataValue(data, uid, 'character_filter', data.entries[uid].characterFilter);
await saveWorldInfo(name, data);
// Update visual state indicators after select2 re-renders
setTimeout(() => updateCharacterFilterStateStyles(characterFilter, data.entries[uid].characterFilter), 0);
});
}
/**
* Warns about singleton type conflicts in a character filter array.
* Character and persona can only be one active at a time, so multiple required items of those types are impossible.
* @param {Array<{type: string, name: string, state: string}>} filterItems - The character filter array.
*/
function warnCharacterFilterSingletonConflicts(filterItems) {
const SINGLETON_TYPES = [CHARACTER_FILTER_TYPES.CHARACTER, CHARACTER_FILTER_TYPES.PERSONA];
for (const type of SINGLETON_TYPES) {
const requiredCount = filterItems.filter(f => f.type === type && f.state === CHARACTER_FILTER_STATES.REQUIRED).length;
if (requiredCount > 1) {
toastr.warning(t`Only one ${type} can be active at a time. Multiple required ${type}s will make this filter impossible to match.`);
}
}
}
/**
* Finds the filter item that corresponds to a rendered select2 choice element.
* Uses data attributes embedded by templateSelection for robust matching.
* @param {Array<{type: string, name: string, state: string}>} filterItems - The character filter array.
* @param {JQuery<HTMLElement>} element - The .select2-selection__choice__display element.
* @returns {object|undefined} The matching filter item, or undefined.
*/
function getFilterItemForChoice(filterItems, element) {
const $el = $(element);
// Navigate up to .select2-selection__choice__display if target is a child element
const display = $el.hasClass('select2-selection__choice__display')
? $el
: $el.closest('.select2-selection__choice__display');
const searchRoot = display.length ? display : $el;
const templateSpan = searchRoot.find('span[data-filter-type]');
if (!templateSpan.length) return undefined;
const type = templateSpan.attr('data-filter-type');
const value = templateSpan.attr('data-filter-value');
return filterItems.find(f => f.type === type && f.name === value);
}
/**
* Updates the visual filter state styling on rendered select2 choice elements.
* @param {JQuery<HTMLElement>} characterFilterSelect - The select element.
* @param {Array<{type: string, name: string, state: string}>} entryFilter - The character filter array.
*/
function updateCharacterFilterStateStyles(characterFilterSelect, entryFilter) {
const filterItems = Array.isArray(entryFilter) ? entryFilter : [];
const container = characterFilterSelect.next('span.select2-container');
const tooltips = {
[CHARACTER_FILTER_STATES.ONE_OF]: t`One of (OR): At least one of these must match`,
[CHARACTER_FILTER_STATES.REQUIRED]: t`Required (AND): This must match`,
[CHARACTER_FILTER_STATES.EXCLUDED]: t`Excluded (NOT): Must not match`,
};
// Singleton types: only one can be active at a time, so having a required item makes others redundant
const SINGLETON_TYPES = [CHARACTER_FILTER_TYPES.CHARACTER, CHARACTER_FILTER_TYPES.PERSONA];
const hasRequiredSingleton = new Set(
SINGLETON_TYPES.filter(type => filterItems.some(f => f.type === type && f.state === CHARACTER_FILTER_STATES.REQUIRED)),
);
container.find('.select2-selection__choice').each(function () {
const display = $(this).find('.select2-selection__choice__display');
const filterItem = getFilterItemForChoice(filterItems, display);
const state = filterItem?.state ?? CHARACTER_FILTER_STATES.ONE_OF;
const type = filterItem?.type;
// Remove all state classes, then add the current one
$(this).removeClass('character_filter_oneOf character_filter_required character_filter_excluded character_filter_redundant');
$(this).addClass(`character_filter_${state}`);
// Mark non-required items of singleton types as redundant when a required item of the same type exists
const isRedundant = type && hasRequiredSingleton.has(type) && state !== CHARACTER_FILTER_STATES.REQUIRED;
if (isRedundant) {
$(this).addClass('character_filter_redundant');
$(this).attr('title', t`Redundant: another ${type} is already required (only one can be active)`);
} else {
$(this).attr('title', tooltips[state] ?? '');
}
});
}
@@ -3550,41 +3951,44 @@ export async function getWorldEntry(name, data, entry) {
selectiveInput.parent().hide();
// Character filter
const characterFilterLabel = editTemplate.find('label[for="characterFilter"] > small');
characterFilterLabel.text(entry.characterFilter?.isExclude ? 'Exclude Character(s)' : 'Filter to Character(s)');
const characterExclusionInput = editTemplate.find('input[name="character_exclusion"]');
characterExclusionInput.data('uid', entry.uid);
characterExclusionInput.on('input', async function (_, { noSave = false } = {}) {
const uid = $(this).data('uid');
const value = $(this).prop('checked');
characterFilterLabel.text(value ? 'Exclude Character(s)' : 'Filter to Character(s)');
if (data.entries[uid].characterFilter) {
if (!value && data.entries[uid].characterFilter.names.length === 0 && data.entries[uid].characterFilter.tags.length === 0) {
delete data.entries[uid].characterFilter;
} else {
data.entries[uid].characterFilter.isExclude = value;
}
} else if (value) {
Object.assign(data.entries[uid], { characterFilter: { isExclude: true, names: [], tags: [] } });
}
if (data.entries[uid]?.characterFilter?.names?.length > 0) {
for (const name of [...data.entries[uid].characterFilter.names]) {
if (!getContext().characters.find(x => x.avatar.replace(/\.[^/.]+$/, '') === name)) {
data.entries[uid].characterFilter.names = data.entries[uid].characterFilter.names.filter(x => x !== name);
}
}
}
setWIOriginalDataValue(data, uid, 'character_filter', data.entries[uid].characterFilter);
!noSave && await saveWorldInfo(name, data);
});
characterExclusionInput.prop('checked', entry.characterFilter?.isExclude ?? false).trigger('input', { noSave: true });
const characterFilter = editTemplate.find('select[name="characterFilter"]');
characterFilter.data('uid', entry.uid);
initCharacterFilterSelect2Helper(characterFilter);
fillCharacterAndTagOptionsHelper({ characterFilter, entry });
fillCharacterFilterOptionsHelper({ characterFilter, entry });
initCharacterFilterSelect2Helper(characterFilter, data);
handleCharacterFilterChangeHelper({ characterFilter, data, entry, name });
// Click-to-toggle filter state on individual character filter choices (oneOf → required → excluded → oneOf)
const SINGLETON_TYPES = [CHARACTER_FILTER_TYPES.CHARACTER, CHARACTER_FILTER_TYPES.PERSONA];
select2ChoiceClickSubscribe(characterFilter, async (target) => {
const uid = characterFilter.data('uid');
const filter = Array.isArray(data.entries[uid].characterFilter) ? data.entries[uid].characterFilter : [];
const item = getFilterItemForChoice(filter, $(target));
if (item) {
const currentIndex = CHARACTER_FILTER_STATE_CYCLE.indexOf(item.state);
const nextIndex = (currentIndex + 1) % CHARACTER_FILTER_STATE_CYCLE.length;
const newState = CHARACTER_FILTER_STATE_CYCLE[nextIndex];
// Warn about singleton type conflicts when setting to REQUIRED
if (newState === CHARACTER_FILTER_STATES.REQUIRED && SINGLETON_TYPES.includes(item.type)) {
const othersOfType = filter.filter(f => f.type === item.type && f !== item);
const otherRequired = othersOfType.find(f => f.state === CHARACTER_FILTER_STATES.REQUIRED);
if (otherRequired) {
toastr.warning(t`Only one ${item.type} can be active at a time. Multiple required ${item.type}s will make this filter impossible to match.`);
} else if (othersOfType.length > 0) {
toastr.info(t`Only one ${item.type} can be active at a time. Other ${item.type} items become redundant when one is required.`);
}
}
item.state = newState;
updateCharacterFilterStateStyles(characterFilter, data.entries[uid].characterFilter);
setWIOriginalDataValue(data, uid, 'character_filter', data.entries[uid].characterFilter);
await saveWorldInfo(name, data);
}
}, { closeDrawer: true });
// Apply initial filter state styles after select2 renders
setTimeout(() => updateCharacterFilterStateStyles(characterFilter, entry.characterFilter), 0);
// Content
const counter = editTemplate.find('.world_entry_form_token_counter');
const countTokensDebounced = debounce(async function (counter, value) {
@@ -3997,7 +4401,7 @@ export async function deleteWorldInfoEntry(data, uid, { silent = false } = {}) {
*
* Use `newEntryTemplate` if you just need the template that contains default values
*
* @type {{[key: string]: WIEntryFieldDefinition}}
* @type {{[key: string]: WIEntryFieldDefinition & { deprecated?: boolean } }}
*/
export const newWorldInfoEntryDefinition = {
key: { default: [], type: 'array' },
@@ -4038,9 +4442,11 @@ export const newWorldInfoEntryDefinition = {
sticky: { default: null, type: 'number?' },
cooldown: { default: null, type: 'number?' },
delay: { default: null, type: 'number?' },
characterFilterNames: { default: [], type: 'array', excludeFromTemplate: true },
characterFilterTags: { default: [], type: 'array', excludeFromTemplate: true },
characterFilterExclude: { default: false, type: 'boolean', excludeFromTemplate: true },
characterFilter: { default: [], type: 'array', excludeFromTemplate: true },
// Deprecated: kept for slash command backwards compatibility, hidden from enum
characterFilterNames: { default: [], type: 'array', excludeFromTemplate: true, deprecated: true },
characterFilterTags: { default: [], type: 'array', excludeFromTemplate: true, deprecated: true },
characterFilterExclude: { default: false, type: 'boolean', excludeFromTemplate: true, deprecated: true },
triggers: { default: [], type: 'array', arrayFilter: (value) => GENERATION_TYPE_TRIGGERS.includes(value) },
};
@@ -4732,33 +5138,48 @@ export async function checkWorldInfo(chat, maxContext, isDryRun, globalScanData
}
}
// Check if this entry applies to the character or if it's excluded
if (entry.characterFilter && entry.characterFilter?.names?.length > 0) {
const nameIncluded = entry.characterFilter.names.includes(getCharaFilename());
const filtered = entry.characterFilter.isExclude ? nameIncluded : !nameIncluded;
// Check if this entry applies based on character filter (characters, tags, personas)
if (Array.isArray(entry.characterFilter) && entry.characterFilter.length > 0) {
const oneOfItems = entry.characterFilter.filter(f => f.state === CHARACTER_FILTER_STATES.ONE_OF);
const requiredItems = entry.characterFilter.filter(f => f.state === CHARACTER_FILTER_STATES.REQUIRED);
const excludedItems = entry.characterFilter.filter(f => f.state === CHARACTER_FILTER_STATES.EXCLUDED);
if (filtered) {
log('filtered out by character');
/** Checks whether a single filter item matches the current context */
const matchesItem = (item) => {
switch (item.type) {
case CHARACTER_FILTER_TYPES.CHARACTER:
return item.name === getCharaFilename();
case CHARACTER_FILTER_TYPES.TAG: {
const tagKey = getTagKeyForEntity(this_chid);
if (tagKey) {
const tagMapEntry = context.tagMap[tagKey];
return Array.isArray(tagMapEntry) && tagMapEntry.includes(item.name);
}
return false;
}
case CHARACTER_FILTER_TYPES.PERSONA:
return item.name === user_avatar;
default:
return false;
}
};
// EXCLUDED: If any excluded item matches, filter out this entry
if (excludedItems.length > 0 && excludedItems.some(matchesItem)) {
log('filtered out by character filter (excluded item matched)');
continue;
}
}
if (entry.characterFilter && entry.characterFilter?.tags?.length > 0) {
const tagKey = getTagKeyForEntity(this_chid);
// REQUIRED: Every required item must match
if (requiredItems.length > 0 && !requiredItems.every(matchesItem)) {
log('filtered out by character filter (required item not matched)');
continue;
}
if (tagKey) {
const tagMapEntry = context.tagMap[tagKey];
if (Array.isArray(tagMapEntry)) {
// If tag map intersects with the tag exclusion list, skip
const includesTag = tagMapEntry.some((tag) => entry.characterFilter.tags.includes(tag));
const filtered = entry.characterFilter.isExclude ? includesTag : !includesTag;
if (filtered) {
log('filtered out by tag');
continue;
}
}
// ONE_OF: At least one must match (OR logic)
if (oneOfItems.length > 0 && !oneOfItems.some(matchesItem)) {
log('filtered out by character filter (no oneOf item matched)');
continue;
}
}
+5
View File
@@ -561,6 +561,11 @@ export const ZAI_ENDPOINT = {
CODING: 'coding',
};
export const POLLINATIONS_ENDPOINT = {
AUTHENTICATED: 'authenticated',
ANONYMOUS: 'anonymous',
};
export const SILICONFLOW_ENDPOINT = {
GLOBAL: 'global',
CN: 'cn',
+17 -11
View File
@@ -20,6 +20,7 @@ import {
SILICONFLOW_ENDPOINT,
MINIMAX_ENDPOINT,
ZAI_ENDPOINT,
POLLINATIONS_ENDPOINT,
} from '../../constants.js';
import {
forwardFetchResponse,
@@ -83,6 +84,7 @@ 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';
@@ -1789,8 +1791,9 @@ 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 = readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS, request.body.secret_id);
apiKey = isAnonymous ? 'anonymous' : 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;
@@ -2414,20 +2417,23 @@ router.post('/generate', async function (request, response) {
};
}
} else if (request.body.chat_completion_source === CHAT_COMPLETION_SOURCES.POLLINATIONS) {
apiUrl = API_POLLINATIONS;
apiKey = readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS, request.body.secret_id);
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);
headers = {};
bodyParams = {
reasoning_effort: request.body.reasoning_effort,
seed: request.body.seed ?? Math.floor(Math.random() * 99999999),
};
if (request.body.json_schema) {
bodyParams['response_format'] = {
type: 'json_schema',
json_schema: {
schema: request.body.json_schema.value,
},
};
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,
},
};
}
}
} else if (request.body.chat_completion_source === CHAT_COMPLETION_SOURCES.MOONSHOT) {
apiUrl = new URL(request.body.reverse_proxy || API_MOONSHOT).toString();
+5 -2
View File
@@ -8,6 +8,7 @@ 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();
@@ -98,7 +99,8 @@ router.post('/caption-image', async (request, response) => {
}
if (request.body.api === 'pollinations') {
key = readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS);
const isAnonymous = request.body.pollinations_endpoint === POLLINATIONS_ENDPOINT.ANONYMOUS;
key = isAnonymous ? 'anonymous' : readSecret(request.user.directories, SECRET_KEYS.POLLINATIONS);
bodyParams.seed = Math.floor(Math.random() * Math.pow(2, 32));
}
@@ -182,7 +184,8 @@ router.post('/caption-image', async (request, response) => {
}
if (request.body.api === 'pollinations') {
apiUrl = 'https://gen.pollinations.ai/v1/chat/completions';
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';
}
if (request.body.api === 'moonshot' && !request.body.reverse_proxy) {
+43 -6
View File
@@ -4,15 +4,25 @@ 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 {
@@ -223,14 +233,27 @@ router.post('/change-name', async (request, response) => {
router.post('/reset-step1', async (request, response) => {
try {
const resetCode = String(crypto.randomInt(1000, 9999));
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();
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) {
console.error('Recover step 1 failed:', 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);
return response.sendStatus(500);
}
});
@@ -238,19 +261,27 @@ router.post('/reset-step1', async (request, response) => {
router.post('/reset-step2', async (request, response) => {
try {
if (!request.body.code) {
console.warn('Recover step 2 failed: Missing required fields');
console.warn('Reset 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('Recover step 2 failed: Incorrect password');
console.warn('Reset 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) {
console.warn('Recover step 2 failed: Incorrect code');
await resetLimiter.consume(ip);
console.warn('Reset step 2 failed: Incorrect code');
return response.status(400).json({ error: 'Incorrect code' });
}
@@ -260,10 +291,16 @@ 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) {
console.error('Recover step 2 failed:', 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);
return response.sendStatus(500);
}
});
+38
View File
@@ -124,6 +124,44 @@ 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', () => {
+45 -1
View File
@@ -508,6 +508,49 @@ 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', () => {
@@ -931,7 +974,8 @@ test.describe('MacroLexer', () => {
});
});
test.describe('Macro Output Modifiers', () => {
// SKIPPED: Pipe/filter feature temporarily disabled. See https://github.com/SillyTavern/SillyTavern/issues/5618
test.describe.skip('Macro Output Modifiers', () => {
// {{macro | outputModifier}}
test('should support output modifier without arguments', async ({ page }) => {
const input = '{{macro | outputModifier}}';
+323
View File
@@ -0,0 +1,323 @@
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);
});
});
});