release
100
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
06bde939fb |
Fix npm release publishing workflow (#6037)
Allow npm releases to be retried from an existing release tag through the trusted publishing workflow, and scope the `allow-directory` workaround to the publish command. |
||
|
|
7e8663cd9c |
Merge pull request #6036 from SillyTavern/staging
1.19.0 |
||
|
|
61139aa9b6 | Update release version number (#6035) | ||
|
|
5e8d463ed4 | feat: add Claude Fable 5.1 and GPT-6 Astra (#6015) | ||
|
|
4ad7af3c06 |
fix: use provider error fields instead of statusText for HTTP 200 errors (#5945)
Providers can return an HTTP 200 response whose body carries an error object without a message field, or the error as a plain string. The error message fell back to response.statusText, which is 'OK' for any 200 response, producing the opaque 'Error: OK'. Error messages now fall back to the error's code or type field, then the string form, and only use statusText for non-2xx responses where it carries meaning. Applies to the non-streaming request path and both streaming error toasts. Fixes #5647 Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
bcc42de2e9 |
Give non-ASCII chat names distinct backup keys and throttles (#5944)
* fix: give non-ASCII chat names distinct backup keys and throttles Backup filenames replace all non-alphanumeric characters with underscores, so names such as equal-length CJK ones collapsed to the same key and shared a single backup quota: busy chats evicted the backups of unrelated quiet ones. The backup key now appends a short hash of the raw name whenever the name contains non-ASCII characters, keeping keys distinct and stable while ASCII names keep their exact current keys and retention. The backup throttle was also keyed per user only, so rapid saves in one chat deferred or swallowed the backup of another chat saved in the same window. It is now keyed per user and chat. Fixes #5780 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: replace stray NUL byte in backup throttle key separator A literal 0x00 byte slipped into the template string separator, which made Git treat the whole file as binary. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore: reunite backupChat docblock with its function Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
b4e162324b |
fix: mint a fresh integrity slug for new branches and checkpoints (#5943)
Branches and checkpoints inherited the parent chat's integrity UUID through the chat_metadata spread in saveChat and saveGroupBookmarkChat, so every member of a branch family shared one slug and the integrity guard could not tell them apart. A save aimed at the wrong file within the family would pass validation. New branches and checkpoints now get their own slug at creation. Existing files are unaffected. Fixes #5942 Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
12b4fc50aa |
tests: set extensions enabled override for discover suite
PR #5571 added an extensionsEnabledFeatureGuard middleware that reads extensions.enabled via getConfigValue. The test environment has no config.yaml, so getConfig() exits the process and kills the Jest worker, failing the extensions-discover suite. Set the env var override so the guard resolves without touching the config file. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
800caeb9e0 |
fix: skip extension folders without a manifest during discovery (#5934)
A manually deleted extension often leaves a folder husk on disk, for example when Windows fails to remove locked .git files. The discover endpoint listed any directory, so the husk kept reporting as an installed extension: /extension-exists and /extension-state returned true after a fresh load and the manifest fetch produced a 404 in the console on every load. Discovery now skips folders without a manifest.json and logs a warning naming the exact path, and the client drops any discovered name whose manifest could not be loaded so state queries cannot report ghost extensions. Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
4f6977b779 |
feat: verify GPT-5.6 support and refresh OpenAI model list (#5932)
Verifies Sol, Terra, and Luna live against the API: generation, vision, effort values (none/low/xhigh), the unlisted gpt-5.6 alias, and the sampler contract (temperature and top_p are rejected even with reasoning off, so the strict stripping stays). Removes models OpenAI has shut down from the model dropdowns, labels announced deprecations without touching option values, orders groups newest first, and moves the new-install and captioning defaults off gpt-4-turbo, which shuts down on October 23, 2026. Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
cd2c65c9d4 |
fix: await chat completion preset application when switching presets (#5930)
Applying a CC preset deferred the actual settings update behind an unawaitable event continuation, so /preset resolved before the preset was applied. A connection profile switch runs /api, /preset, /api in sequence, and the preset's stored chat_completion_source would land after the final /api check, reverting the source to the previous provider. Requests then silently went to the wrong endpoint. The preset application chain is now captured in a promise that selectPreset awaits, so /preset resolves only when the preset is fully applied and follow-up commands sequence correctly. The UI dropdown path is unchanged, and callers that do not await selectPreset keep the exact previous behavior. Fixes #5926 Fixes #5147 Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
32e1966757 |
fix: require confirmation before overwriting chats with unparseable headers (#5928)
An existing non-empty chat file whose first line could not be parsed as a JSON object passed the integrity check as if it were a legacy chat, so a save silently replaced the file and only the replacement got backed up. The check now fails closed for unparseable, truncated, or non-object headers, routing the client into the existing overwrite confirmation dialog. A UTF-8 BOM in front of an otherwise valid header is stripped before parsing. Empty files, valid legacy headers, and force saves behave as before. Fixes #5454 Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
2463e83966 |
Fix: remove trailing whitespace from variable macros (#5848)
- Restore root lint compliance for the variable macro registry. |
||
|
|
0a1a746bfd |
Fix: ignore local third-party extensions during linting (#5847)
- Keep root lint focused on core sources. - Ignore local .windsurf IDE settings. |
||
|
|
bba96c6fbe |
Update TTS model from Gemini 2.5 to 3.1 in TTS Extension (#5778) (#5824)
* Update TTS model from Gemini 2.5 to 3.1 in TTS Extension Added New versions and new Default model * Add glm-5.2 option to model selection dropdown Co-authored-by: Samueras <Samueras@jackoedv.de> |
||
|
|
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.
|
||
|
|
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
|
||
|
|
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 |
||
|
|
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
|
||
|
|
29a18ce0c6 |
Refactor getUniqueName utility for allowBaseName option (#5602)
* feat: add allowBaseName option to getUniqueName utility function * feat: simplify getUniqueName by removing allowBaseName option and changing default startIndex to 0 |
||
|
|
1bb2a5ea19 |
Fix missing filename sanitization on V2 JSON character import + harden getPngName as safety nee (#5538)
* fix: sanitize character filenames on V2 JSON import and harden getPngName - Add missing sanitize() call in importFromJson V2 spec branch to match all other import paths - Sanitize data.name before readFromV2() so the name field sync happens automatically - Add sanitize() as defense-in-depth inside getPngName() to catch future oversights - Refactor getPngName() to use getUniqueName() utility for consistent name generation * fix: sanitize data.name before readFromV2 in importFromPng and importFromCharX Same bug as importFromJson: readFromV2() overwrites the top-level name with the unsanitized data.name, undoing any prior sanitize() call. Fix by sanitizing data.name before readFromV2 so the sync preserves it. * fix: sanitize top-level name field in JSON and CharX import paths * fix: incorrect path rejection in isPathUnderParent * fix: increase maxTries in getPngName --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
4df18ccb0b |
Add Slug Parameter to Action Loader for Programmatic Identification (#5490)
* feat: add slug parameter to action-loader for programmatic identification
Add optional `slug` parameter to ActionLoaderHandle for easier identification via code or CSS. Update all loader.show() calls across the codebase to include descriptive slugs ('app-init', 'chat-rename', 'chat-delete', 'bulk-delete', 'chat-load', 'image-generation', 'legacy-loader'). Add data attributes (data-slug, data-loader-id, data-blocking) to toast content div. Expose slug via getter and make id private with getter.
* Apply suggestions from code review
Fix slug jsdoc wording
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* fix: Add identifier to second loader in img gen
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
8aeda4a101 |
Add Persona CRUD Slash Commands with Shared Avatar Utilities (#5466)
* Add persona CRUD slash commands with enhanced utilities - Add `/persona-create`, `/persona-update`, `/persona-delete`, `/persona-duplicate`, and `/persona-get` slash commands for programmatic persona management - Move `persona_description_positions` enum from power-user.js to personas.js for better encapsulation - Add position and role parsing utilities (`parsePersonaPosition`, `parsePersonaRole`) with name-to-value mapping - Extend `initPersona()` to accept optional position, depth, role, and lorebook parameters - Refactor `deleteUserAvatar()` to delegate to new `deletePersona * Add NaN validation for descriptionDepth parameter in createPersonaCallback - Add isNaN() check for depth parameter after Number() conversion - Display warning toast when invalid depth value is provided - Fall back to DEFAULT_DEPTH when depth is NaN - Change depth from const to let to allow reassignment after validation * Refactor persona lookup to support avatar key targeting and fix enum provider currying - Refactor `autoSelectPersona()` to accept optional `personaKey` parameter for targeting specific persona when multiple share the same name - Replace manual persona lookup loops with `findPersona()` helper calls in `autoSelectPersona()` and `setNameCallback()` - Update `setNameCallback()` to pass both persona name and avatar key to `autoSelectPersona()` for precise targeting - Refactor `commonEnumProviders.personas()` |
||
|
|
15a3e3f072 |
feat: add click-to-edit support for reasoning blocks and auto-focus reasoning textarea (#5487)
Extend click-to-edit functionality to reasoning blocks in addition to message text. When clicking on a reasoning block, automatically focus the reasoning textarea after entering edit mode. |
||
|
|
53f251c52a |
Fix: Prevent "Show More Messages" Button from Triggering Message Edit Mode (#5486)
* fix: prevent event bubbling on show more messages button Replace mouseup/touchend with click event and add stopPropagation/preventDefault to prevent unintended event bubbling when loading more messages. * Add hover style to "show more messages" * add button role to show_more_messages --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
d8b3d36a84 |
Refactor: Replace SD image generation indicator with ActionLoader system (#5472)
* refactor: replace custom generation indicator with action-loader
Remove custom generation tracking (activeGenerations counter, generationToast) and replace with action-loader's non-blocking stoppable toast. Import loader from action-loader.js and use loader.show() with onStop callback in generatePicture() and generateMediaSwipe(). Remove updateGenerationIndicator(), startGenerationTracking(), and endGenerationTracking() functions. Remove manual stop button show/hide logic and generation counter updates
* Remove legacy stop button, add sentinel handler value
* fix: reassign loaderHandle in generateMediaSwipe
* feat: add data attributes to action-loader toast for easier selection
Add loaderId, title, and blocking data attributes to toast content div to enable programmatic identification and filtering of active loader toasts
* Revert "feat: add data attributes to action-loader toast for easier selection"
This reverts commit
|
||
|
|
d720605be8 |
Bulk extension field updates via merge-attributes with UNSET_VALUE sentinel (#5471)
* feat: add bulk extension field updates with UNSET_VALUE sentinel for key deletion - Add `UNSET_VALUE` sentinel constant to signal complete field removal from character cards - Add `writeExtensionFieldBulk()` function to update extension fields across multiple characters in a single API call - Add `deleteValueByPath()` utility function to remove nested object keys by dot-path - Update `writeExtensionField()` to support `UNSET_VALUE` for deleting extension keys - Extend `/api/characters/merge-attributes * Revert package-lock.json changes * Allow null values in merge-attributes filter path validation Change filter.path existence check to only skip on undefined, not null. This allows merging attributes when the existing value is explicitly null, treating null as a valid value rather than absence of a value. * fix: share forbiddenRegExp between modules * feat: add writeExtensionFieldBulk and UNSET_VALUE constant to getContext * Update src/endpoints/characters.js Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * fix: validate for .png extension * Update public/scripts/extensions.js Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * refactor: extract shouldSkip logic as a function param to avoid double parsing --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> |
||
|
|
552936a0d8 |
fix: exclude other group members' reasoning from prompt context in group chats (#5473)
In group chats, only include reasoning from the currently generating character instead of all group members. This prevents reasoning from other characters being injected into the prompt context when generating responses. - Filter reasoning in coreChat loop based on message author matching name2 - Filter reasoning in setOpenAIMessages based on message author matching name2 - Add isOtherGroupMember check before adding reasoning to messages |
||
|
|
4003251c2f |
Increase Top K max value from 200 to 500 for text generation WebUI (#5474)
Raises the maximum allowed Top K sampling parameter from 200 to 500 in both the range slider and number input controls to support higher token selection limits. |
||
|
|
0ac31c8fcd |
Enhanced /persona-sync Command with Range, Name Filter, and Quiet Mode (#5460)
* Add range and silent parameters to /persona-sync command with optional confirmation suppression - Add optional start/end range parameters to syncUserNameToPersona() function - Add silent parameter to suppress confirmation popup when needed - Update /persona-sync slash command to accept range argument (index or range string) and named silent argument - Parse range using stringToRange() utility, default to full chat if not provided - Update confirmation message to reflect whether syncing all messages or specified * Add `from` named argument to /persona-sync command for filtering by persona name - Add `from` named argument to filter messages by persona name (case-insensitive) - Rename `silent` argument to `quiet` with inverted default (true) for consistency - Add userMessageNamesEnumProvider() to provide autocomplete for existing user message names in chat - Update syncUserNameToPersona() to accept nameFilter parameter and filter messages accordingly - Update confirmation message to reflect name filtering when * Add async/await wrapper to sync_name_button click handler for proper promise handling Function now has arguments, so using just the function as the event is shown as wrong usage * Post-merge imports fix * Use canonical command name in examples --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
64c96e895c |
Add Streaming Display Utility and New Generation Slash Commands (/genstream, /reasoning-format) (#5438)
* Add StreamingDisplay class for live LLM generation output with floating toast panel - Add StreamingDisplay class to show streaming reasoning and content in a floating toast panel - Extract createModelIcon() helper from insertSVGIcon() for reusable API/model icon creation - StreamingDisplay automatically appends inside topmost open dialog (same pattern as fixToastrForDialogs) - Add CSS with fade-in animation, pulsating activity indicator, and separate reasoning/content sections - Support optional model icon in header * Add ConnectionManagerRequestService.getProfileIcon() method for retrieving profile API icons - Add static getProfileIcon() method to ConnectionManagerRequestService - Returns HTMLImageElement created via createModelIcon() for a given profile's API/model - Accepts optional profileId parameter, defaults to currently selected profile - Returns null if Connection Manager is disabled, profile not found, or profile has no API - Import createModelIcon from script.js * Use animation_duration directly in hide() and CSS transition instead of constant - Remove ANIMATION_DURATION_MS constant and use animation_duration directly in hide() method - Replace hardcoded 0.3s CSS transitions with CSS variable var(--animation-duration, 125ms) - Read animation_duration value inline in hide() for accurate timing * Add /genstream slash command with live streaming display and reasoning support - Add /genstream slash command that generates text via Connection Manager with live streaming UI - Add formatReasoning() helper function (inverse of parseReasoningFromString) to format reasoning/content into template-wrapped strings - Add connectionProfiles enum provider for profile selection in slash commands - StreamingDisplay: add delay parameter to hide() method (default 1000ms) to show final result before dismiss * Add /reasoning-format slash command to format reasoning and content into template-wrapped strings - Add /reasoning-format (alias: /format-reasoning) slash command that wraps reasoning/content using Reasoning Formatting settings - Accept required 'reasoning' named argument and optional unnamed 'content' argument - Validate that prefix/suffix are configured before formatting - Return formatted string via formatReasoning() helper for use with /reasoning-parse - Show warning toasts if prefix/suffix missing * Rename /genstream command to /profile-genstream and move to appropriate module * Apply messageFormatting to StreamingDisplay reasoning and content text for proper rendering - Import messageFormatting from script.js - Replace textContent with innerHTML using messageFormatting() in updateReasoning() and updateText() - Pass isSystem=true for reasoning, isSystem=false for content to match formatting expectations - Update css to utilize pre-formatted paragraphs correctly * Strip auto-added quotes from <q> tags in StreamingDisplay and add 'mes_text' class for consistent chat message formatting - Add CSS rules to remove browser-default quotes from <q> tags in reasoning and content sections - Add 'mes_text' class to textContent div to match chat message formatting behavior - Prevents double quotes when messageFormatting already adds them via <q> tags * Add minimize/close buttons and complete state to StreamingDisplay with configurable auto-hide - Add minimize button to collapse/restore content sections while keeping header visible - Add close button to manually dismiss display (generation continues in background) - Replace CSS pseudo-element with explicit LED indicator element for better state control - Add complete() method to mark generation done: changes LED from pulsing orange to solid green - Add configurable auto-hide delay after completion * Add stop button to StreamingDisplay with abort support and onStop/onComplete closures for /profile-genstream - Add stop button to StreamingDisplay when onStop handler is provided - Add markStopped() method with solid red LED state indicator - Add AbortController integration to /profile-genstream for request cancellation - Add onStop and onComplete closure arguments to /profile-genstream command - Update complete() method signature to use options object with label and delay - Disable stop button immediately * Position StreamingDisplay above bottom form block using CSS variable with fallback - Change bottom positioning from fixed 20px to dynamic calculation - Use max() to position above --bottomFormBlockSize + 5px or minimum 20px - Ensures StreamingDisplay doesn't overlap with bottom UI elements * Rename /profile-genstream arguments for clarity: label→generating, completedLabel→completed, hideDelay→delay - Rename `label` argument to `generating` to better reflect its purpose as the in-progress state label - Rename `completedLabel` to `completed` for consistency and brevity - Rename `hideDelay` to `delay` for simpler naming - Update all internal references and variable names to match new argument names - Update argument descriptions and default values accordingly * Remove variable resolution from /profile-genstream arguments: system, length, and delay - Remove ARGUMENT_TYPE.VARIABLE_NAME from typeList for system, length, and delay arguments - Replace resolveVariable() calls with direct argument access for system, length, and delay - Simplify type checking to use typeof directly on args properties - Maintain existing default values and validation logic * Add warning toast and early return when connection profile not found in /profile-genstream - Display toastr warning when fuzzy search fails to find matching profile - Return empty string to prevent execution with invalid profile - Improves user feedback for incorrect profile names or IDs * Extract buildResultText() helper in /profile-genstream to return partial results when stopped - Add buildResultText() helper function to centralize result formatting logic - Return partial generated text when user stops generation instead of empty string - Reuse buildResultText() for both stopped and completed states - Maintains consistent reasoning formatting in both cases * fix lint * Update documentation to reflect argument name change from hideDelay to delay --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
d72f4b6fcb |
Emit PERSONA_CREATED event on persona duplication (#5448)
* feat: emit PERSONA_CREATED event when duplicating a persona Adds PERSONA_CREATED event emission in duplicatePersona() to notify listeners when a persona is duplicated. Includes the new avatarId, name, and duplicatedFromAvatarId in the event payload. * fix: event data and execution order --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
737cb95adb |
Add clean extension lifecycle hook for optional data cleanup (#5449)
* Add 'clean' extension hook support with optional cleanup on delete - Add hasExtensionHook() helper to check if an extension defines a specific manifest hook - Add 'clean' hook type to callExtensionHook() JSDoc - Add clean button to extension UI when 'clean' hook is present - Add onCleanClick() handler to run clean hook with confirmation - Add cleanExtension() function to execute clean hook and reload page - Modify deleteExtension() to optionally run clean hook before deletion - Show cleanup checkbox on extension delete popup * fix lint Remove unused `callGenericPopup` import from extensions.js * Force save settings before page reload in extension clean and delete operations Add explicit saveSettings() calls in cleanExtension() and deleteExtension() to prevent race conditions where clean/delete hooks might update settings that get lost during the subsequent page reload. * Remove admin permission check from extension clean operation The clean hook is extension-defined and may not require admin privileges. Permission checks should be handled by the extension's clean hook implementation if needed, rather than enforcing a blanket restriction at the UI level. * fix: show clean button for built-ins * Update hasExtensionHook to support built-in extensions * Revert "Update hasExtensionHook to support built-in extensions" This reverts commit |
||
|
|
f4f390f325 |
Fix: Missing signature and toolSignatures fields in ChatCompletionService streaming state (#5439)
* Fix: Add signature and toolSignatures fields to ChatCompletionService streaming state object * fix: pass images array to getStreamingReply --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
6a325d2b22 |
Add disabled property support to all popup input types (#5441)
Adds optional `disabled` boolean property to PopupInputConfiguration JSDoc and implements it across all input types (checkbox, text, textarea, number). When set to true, the input element will be rendered in a disabled state. |
||
|
|
a7f144f28b |
feat: add getExtensionManifest() to extensions.js and expose via getContext() (#5442)
Returns a structuredClone of the loaded manifest for the given extension name. Accepts either the short name or full internal key (third-party/...). Returns null if the extension is not registered. |
||
|
|
7d3d1231a9 |
Chore: Add persona lifecycle events (PERSONA_CREATED, PERSONA_UPDATED, PERSONA_RENAMED, PERSONA_DELETED) (#5443)
* Add persona lifecycle events (created, updated, renamed, deleted) and emit them throughout persona management functions * fix: await event emissions * fix: await event in convertCharacterToPersona * fix: await PERSONA_UPDATED in callbacks * fix: delete multiple personas without reloading the chat * fix: add CHAT_RENAMED event and adjust welcome screen pin update logic --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
f3521e7007 |
Migrate built-in extensions to use manifest-based activate hooks (#5435)
* Convert jQuery/IIFE wrappers to exported init() functions and register activate hooks in 8 extension manifests * Convert remaining extensions to exported init() with activate hooks and await initExtensions() - Convert jQuery/IIFE wrappers to exported init() functions in expressions, memory, quick-reply, regex, stable-diffusion, translate, tts, and vectors extensions - Register init functions as activate hooks in extension manifests - Properly await async initExtensions() in firstLoadInit() * Fix eslint --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
fb915b4321 |
Add /regex-state slash command to check regex script status (#5428)
* feat: add /regex-state command to check script enabled status
Adds a new slash command that returns 'on' or 'off' to indicate whether a regex script is currently enabled or disabled.
* refactor: change /regex-state return values from 'on'/'off' to 'true'/'false'
Updates the /regex-state slash command to return boolean string values ('true'/'false') instead of ('on'/'off') for better consistency with standard boolean conventions.
|
||
|
|
ff4c6fa1bb |
chore: add arguments logging to deprecated MacrosParser method warnings (#5429)
Extends the #logDeprecated helper to accept and log the arguments passed to deprecated methods, providing better debugging context for migration. Updates all deprecated method calls (get, has, registerMacro, unregisterMacro) to forward their arguments to the deprecation logger. |
||
|
|
81c85f8049 |
fix: skip pseudo-elements when generating focus-visible styles (#5430)
Prevents invalid CSS by skipping rules containing `::` (pseudo-elements like `::before`, `::after`, `::-webkit-scrollbar`) when converting `:hover` to `:focus-visible`, as pseudo-elements cannot receive focus. |
||
|
|
67eba1b472 |
fix: treat all English locale variants as supported fallback language (#5431)
Previously only exact 'en' was accepted as fallback when a language wasn't found. Now accepts any English variant (en-US, en-AU, etc.) to prevent spurious warnings for valid English locales. |
||
|
|
df27574247 | Fix: Remove unused ComfyUI RunPod API key input mapping (#5432) | ||
|
|
5e68410d4e |
Add Entry Preview to World Info Deletion Confirmation Dialog (#5423)
* feat: add entry preview to world info deletion confirmation dialog Displays entry comment or first two lines of content in the deletion confirmation popup to help users verify they're deleting the correct entry. * fix: sanitize world info entry preview text in deletion confirmation dialog Adds DOMPurify sanitization to the entry preview text displayed in the deletion confirmation popup to prevent potential XSS vulnerabilities from unsanitized user content. * DOMPurify -> escapeHtml --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
e52c035fcd |
Add allowEscapeClose option to popup class for Escape key behavior override (#5340)
* feat(popup): add allowEscapeClose option to override default escape key behavior Add `allowEscapeClose` parameter to PopupOptions to explicitly control whether Escape key closes the popup, overriding the default logic that checks for visible cancel/close buttons. When null (default), uses existing behavior; when true, allows escape even without buttons; when false, prevents escape even with buttons present. * feat(popup): enable Escape key closing for informational popups Add `allowEscapeClose: true` option to TEXT-type popups in export preset, persona lore, sampler select, stats, and world info assignment dialogs to allow users to dismiss these informational popups with the Escape key. * Improve Escape key interaction in popups * Adjust jsdoc for allowEscapeClose * Always return CANCELLED on Escape * fix(popup): correct jsdoc for allowEscapeClose property description --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
45009cd0e4 |
Deprecate legacy loader and migrate all callsites to action-loader system with informative toasts (#5326)
* Refactor loader.js to use action-loader system and move overlay management into action-loader module - Deprecate showLoader() and hideLoader() in favor of action-loader API - Implement legacy functions as thin wrappers around ActionLoaderHandle - Move overlay management (showOverlay, hideOverlay, isOverlayDisplayed) into action-loader.js - Move Popup-based loader implementation and preloader cleanup to action-loader - Add loader.isBlocking() method to check for active blocking overlays * Migrate from legacy loader functions to action-loader API throughout codebase - Replace showLoader()/hideLoader() imports with loader from action-loader.js - Update firstLoadInit() to use loader.show() with title, message, and ToastMode.STATIC - Pass initLoaderHandle to getSettings() for early hide during onboarding flow - Refactor renameGroupOrCharacterChat() to use loader.show() instead of boolean flag - Wrap handleDeleteChat() with loader.show() and proper error handling - Update BulkEditOver... * Update loader titles and remove redundant reload notification - Change bookmark loader title from "Bookmark" to "Chat History" for clarity - Remove loader notification before extensions reload (redundant with browser reload) * lint fix * Add splash screen support to action loader with custom overlay content - Add `overlayContent` option to ActionLoaderOptions for custom HTML in overlay - Implement splash screen styles with centered logo, spinner, and message - Update firstLoadInit() to use custom splash screen instead of static toast - Pass custom content through showOverlay() to replace default spinner - Adjust non-blocking loader warning to account for custom overlay content * Refactor loader overlay to use DOM elements instead of HTML strings - Add createDefaultLoaderOverlay() function to generate fresh loader overlay elements - Export createOverlay() method on loader utility API for external use - Change overlayContent parameter type from string-only to string|HTMLElement|null - Add getOverlayContent() helper to normalize custom content for Popup - Update firstLoadInit() to build splash screen using DOM manipulation instead of template literals - Add splash-logo class and * Use a true ellipsis * Adjust sizing for desktop * Even truer ellipsis * Add transition to splash screen and fix blur animation on hideOverlay (#5338) * Initial plan * Blur entire splash screen on hideOverlay, not just spinner Co-authored-by: Cohee1207 <18619528+Cohee1207@users.noreply.github.com> Agent-Logs-Url: https://github.com/SillyTavern/SillyTavern/sessions/eee6c06d-7c9d-4363-bc8f-2647ed390368 * Add transition to splash-screen and fix transition detection Co-authored-by: Cohee1207 <18619528+Cohee1207@users.noreply.github.com> Agent-Logs-Url: https://github.com/SillyTavern/SillyTavern/sessions/9368bc36-31a0-4a58-aebd-7b569696ff2e --------- Co-authored-by: anthropic-code-agent[bot] <242468646+Claude@users.noreply.github.com> Co-authored-by: Cohee1207 <18619528+Cohee1207@users.noreply.github.com> * Add translations to supported locales * Localize logo alt on welcome screen --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> Co-authored-by: Claude <242468646+Claude@users.noreply.github.com> |
||
|
|
7766d41c42 |
Fix: Prevent Escape Key from Closing Non-Dismissable Popups (#5327)
* fix(popup): prevent Escape key from closing popups when both cancel and close buttons are hidden Add validation in cancel listener to check visibility of cancel and close buttons before allowing Escape key to close popup. Set isClosingPrevented flag to block subsequent close events when neither button is visible. * feat(popup): add double-escape force-close mechanism for blocking popups Add double-escape detection (within 500ms) to allow force-closing blocking popups that have both cancel and close buttons hidden. Show confirmation dialog warning about potential inconsistent state before allowing force-close. Track last escape press timestamp and confirmation popup state to prevent duplicate dialogs. Gracefully cancel force-close confirmation if main popup closes naturally. |
||
|
|
240e9ca907 |
Extend Popup System with Placeholder, Tooltip, and Icon Support (+ those in slash commands) (#5322)
* feat: add placeholder and tooltip support to popup system with icon buttons
Add `placeholder` and `tooltip` options to main popup configuration. For INPUT type popups, placeholder applies to input field; for other types, tooltip applies to content area. Enhance custom buttons with optional `icon` parameter for Font Awesome icons and `tooltip` for hover text. Add tooltip support to custom inputs (placeholder for text/textarea, tooltip icon for checkboxes).
* fix: preserve default toastClass when applying custom cssClass in /echo command
Modify cssClass argument handling in echoCallback to append custom class to existing toastClass instead of replacing it. Use filter(Boolean).join(' ') to combine default and custom classes while handling undefined values.
* feat: add placeholder, tooltip, and icon support to popup system slash commands
Add `placeholder` and `tooltip` named arguments to /input command for input field customization. Add `tooltip` argument to /popup command for content area hover text. Enhance /buttons command to support button objects with `text`, `tooltip`, and `icon` (Font Awesome) properties alongside simple string labels. Update help text and examples for all three commands. Normalize button labels to ButtonLabel format internally
* Fix jsdoc wording
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* fix: add validation for button labels in /buttons command
Add validation check to ensure each button entry is either a string or an object with a non-empty string `text` property. Return empty string and log warning if validation fails. Fix capitalization of 'Popup' in /popup command return value description.
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
|
||
|
|
a6486d7f08 |
Add Action Loader Module with Stacking Support and STscript Commands (#5311)
* Add action loader utility with stoppable toast notifications * Add slash commands for action loader control (/loader-wrap, /loader-show, /loader-hide, /loader-stop) * Refactor action loader to support stacking multiple loaders with individual toast management - Convert action loader from singleton to class-based handle system (ActionLoaderHandle) - Support multiple concurrent loaders with single overlay and stacked toasts - Add unique ID generation and tracking for each loader instance - Implement onHide callback alongside existing onStop callback - Add getActiveLoaderHandles() and getLoaderHandleById() utility functions - Refactor hideActionLoader() to accept... * Improve action loader overlay and toast handling with better state checks and cleanup timing - Check isLoaderDisplayed() before showing overlay to prevent conflicts with existing loaders - Use toastr.options.hideDuration for toast removal timing instead of hardcoded 250ms - Simplify hideActionLoader() by using getActiveLoaderHandles() helper - Remove redundant empty check in hideActionLoader() - Add clarifying comment for intentional error throw in createClosureHandler() - Remove redundant 'onStop' default * fix stop button toast removal issue by using toastr.clear force option instead of manual removal with timeout * Fix isLoaderDisplayed() by using double negation operator instead of null comparison * Add non-blocking loader support with `blocking` parameter for toast-only action loaders - Add `blocking` option to ActionLoaderHandle (default: true) - Implement hasBlockingLoaders() helper to check for active blocking loaders - Show/hide overlay only when blocking loaders are active - Add `blocking` named argument to /loader-wrap and /loader-show commands - Update help strings with non-blocking usage examples - Import commonEnumProviders for boolean enum and isFalseBoolean utility * Add optional title parameter to action loader toast notifications and reorder constructor parameters for consistency - Add `title` parameter to ActionLoaderOptions and ActionLoaderHandle constructor - Pass title to toastr.info() for toast notifications - Reorder parameters: blocking, toastMode, message, title, stopTooltip (grouped by importance) - Add warning when creating non-blocking loader without toast (invisible to user) - Update /loader-wrap and /loader-show commands with title argument * Add loader utility API to action-loader and expose it in ST context for convenient programmatic access - Create `loader` object with show/hide/active/get methods and ToastMode/Handle exports - Add JSDoc examples for basic usage, non-blocking tasks, and hiding all loaders - Import and expose `loader` in ST context alongside existing loader functions * Split slash command and functional modules * Create abort controller on app init * Remove HTML tags from "returns" declaration --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
2a00253937 |
Fix description and firstMessage in /char-create command being optional
Make description and firstMessage optional parameters in createCharacterCallback, allowing character creation with only a name. Remove validation checks that previously required these fields to be non-empty strings. |
||
|
|
276a0c2125 |
Remove long deprecated STscript commands and parameters (#5312)
* Remove deprecated 'format' argument from /listinjects and /listvars commands * Remove deprecated /lock command and add as alias to /persona-lock * Add 'bind' as an alias for /persona-lock command (#5321) * Initial plan * Add 'bind' as an alias for /persona-lock command Co-authored-by: Cohee1207 <18619528+Cohee1207@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Cohee1207 <18619528+Cohee1207@users.noreply.github.com> --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: Cohee1207 <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
f9c42a32dd |
Character CRUD Slash Commands (#5306)
* feat: add character CRUD slash commands (char-create, char-update, char-get, char-delete)
Implement comprehensive character management commands allowing programmatic creation, modification, retrieval, and deletion of characters without UI interaction. All commands support named arguments with proper validation and error handling.
* feat: enhance char CRUD commands with favorite, avatar, and improved defaults
Add `favorite` and `avatar` named arguments to char-create and char-update commands. Make `char` argument optional in char-delete (defaults to current character). Improve documentation with clarifications on card tags vs ST tags, avatar URL sources, and usage examples. Add `fav` field to char-get output.
* feat: add /tag-import slash command for programmatic character tag import
Implement /tag-import command with `name` (defaults to {{char}}) and `mode` arguments (all/existing/none/ask). Command imports character card tags as ST tags for filtering/organizing. Returns 'true' if tags were imported, 'false' otherwise. Mode argument maps to existing tag_import_setting enum values.
* feat: enhance char-create and char-update with avatar upload and tag parsing
Add avatar resolution and upload support for char-create and char-update commands. Implement resolveAvatarData() to handle URLs, base64 data URLs, and local paths. Add uploadCharacterAvatar() to upload resolved images via /api/characters/edit-avatar. Parse tags argument as comma-separated array. Refresh side panel after char-update when modifying current character. Add char-get2 alias for testing.
* feat: enhance avatar argument in char CRUD commands with file picker and local path support
Add `prompt` value to avatar argument to open file picker dialog. Implement promptForAvatarFile() to handle image selection with validation. Add folderEnumMatchProvider() for autocomplete matching of folder paths. Update avatar enumList with common ST paths (characters/, backgrounds/, User Avatars/, assets/, user/images/). Remove external URL support from resolveAvatarData() - now only accepts "prompt", base
* feat: add /char-duplicate slash command with avatar resize support and enhanced avatar upload handling
Implement /char-duplicate command with `char` and `select` named arguments. Add `avatarPromptResize` argument to char-create and char-update for optional resize/crop dialog. Refactor duplicateCharacter() to accept avatar and silent parameters, returning the new avatar key. Enhance uploadCharacterAvatar() to handle resize prompts and return success status. Add cache busting and DOM refresh for avatar thumbnails
* refactor: optimize avatar refresh after upload by using cache busting and DOM query
Replace message-specific avatar refresh logic with generic image refresh targeting all thumbnails using the updated avatar URL. Remove unnecessary delay and character name matching. Add cache busting for both thumbnail and full character image. Use querySelectorAll to find and refresh all affected img elements in one pass.
* refactor: rename char-get alias from char-get2 to char-data
* refactor: move /dupe command to alias of /char-duplicate and fix characterIndex type
Move standalone /dupe command to alias of /char-duplicate for consistency with character CRUD commands. Cast characterIndex to String in char-update to match expected type.
* docs: clarify /imagine command integration with avatar argument in char CRUD commands
Update avatar argument descriptions and examples to explicitly mention /imagine command return value support. Reorder piped /imagine example to show correct command flow (generate image first, then update character).
* feat: add i18n support to char-create and char-update command error messages
Wrap validation error toastr messages in t`` template literals for translation support in /char-create and /char-update commands.
* feat: add group chat validation to /tag-import command
Add early validation check to prevent tag import in group chats. Display warning toastr message and return 'false' when selected_group is not null.
* Fix char update world property
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* Fix help text documentation to match arg name
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* fix: return empty string instead of throwing errors in char-create and char-update commands
Replace `throw error` with `return ''` in error handlers for /char-create and /char-update commands to prevent unhandled promise rejections while still displaying error toastr messages.
* refactor: make deleteCharacter return boolean success status and update char-delete command to use it
Change deleteCharacter to return boolean indicating success/failure instead of void. Return false on user cancellation or failed chat close, true when character is successfully deleted. Update /char-delete command to use returned success value instead of always returning 'true'.
* refactor: make description and firstMessage optional in /char-create command
Remove description and firstMessage from required fields array, allowing character creation with only a name. Update help text to reflect that only name is required.
* refactor: extract external URL check to utility function and add same-origin URL support for avatar resolution
Extract external URL check into `isExternalUrl` utility function in utils.js. Update `resolveAvatarData` to use new utility and add support for same-origin URLs by converting them to pathname before fetching.
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
|
||
|
|
f5b1f913f9 | Enable experimental macro engine by default (#5234) | ||
|
|
87a0ac7cd1 |
Add textarea support to popup custom inputs (#5167)
- Add 'textarea' as a valid input type alongside 'checkbox' and 'text' - Add optional `rows` property to control textarea height (default: 1) - Implement textarea rendering with proper label, placeholder, and styling - Update result collection logic to handle textarea values like text inputs - Update warning message to include textarea in supported types |
||
|
|
953d9f34cb |
Macros 2.0 - list-supported Macros Autocomplete Improvements (#5135)
* fix(macros): prevent list-arg macros from accepting scoped content List-arg macros now correctly reject scoped content since they only accept arbitrary inline arguments. Updated validation logic in autocomplete, scope detection, and CST walker to check for `list === null` before allowing scopes. Also improved list item hint display to show total count when typing additional items. * feat(macros): display min/max constraints for list arguments in autocomplete hints Add visual indication of list argument constraints by showing min/max values in autocomplete hints. List items now display "(list, min: X, max: Y)" or "(variable-length list)" when no constraints exist. Includes new CSS styling for smaller, dimmed hint text. * feat(macros): validate list argument min/max constraints and improve warning display Add validation for list argument constraints (min/max) with specific error messages when too few or too many list items are provided. Continue highlighting current argument position even when warnings are present (except where semantically invalid), allowing users to navigate back to valid arguments while seeing "too many arguments" warnings. |
||
|
|
9f4449973b |
Macros 2.0 - Optional scoped content + improved closing-tag autocomplete (#5117)
* feat(macros): Add optional scope detection and improved closing tag autocomplete
- Implement `isScopeOptional()` to detect when scoped content is optional based on macro argument requirements
- Filter optional scopes from autocomplete hints unless force-triggered (Ctrl+Space)
- Add "OPTIONAL" badge styling for optional scoped content in autocomplete UI
- Show multiple closing tag suggestions (innermost to outermost) with priority ordering
- Display nesting level information for nested optional scopes
* fix(autocomplete): show original macro details when typing closing tags
Add nameOffset=2 to MacroClosingTagAutoCompleteOption to skip {{ prefix for fuzzy highlighting. When typing closing tags ({{/macroName}}), detect and show the original macro's details instead of "no match" error by looking up the macro definition and creating a non-selectable context option with no argument highlighting.
|
||
|
|
34688f8493 | chore(wi): Add logSlashCommandWarn utility and integrate into world-info slash commands (#5096) | ||
|
|
06b77ec94c |
Macros 2.0 - Improve Autocomplete edge cases on completing macros (#5093)
* fix(autocomplete): handle nested macros in :: separator parsing
Track nesting depth when parsing macro parts to avoid treating :: inside nested macros as separators. Increment depth on {{ and decrement on }}, only recognizing :: as a separator when nestedDepth is 0.
* chore(autocomplete): add missing properties for non-variable macros
Add `variableNameEnd` and `variableOperatorEnd` fields to track end positions of variable components in macro parsing context.
* fix(autocomplete): stop macro parsing at newlines before first :: separator
Prevent newlines before the first :: separator from being included in macro identifier/space-arg parsing. Track separator state and break early when encountering newlines at depth 0 before any :: is seen. Only include the last part if cursor is within its bounds to avoid extending macro context across line breaks.
* fix(autocomplete): handle cursor position after closing braces in macro detection
Skip closing }} when searching backwards if cursor is immediately after them, treating them as the target macro's closing braces rather than nested braces. Skip forward search entirely when cursor is after }}, using cursor position as closePos directly.
* fix(autocomplete): show macro details when typing closing brace and add no-match indicator
Track `isTypingClosingBrace` state when cursor is after a single `}` on standalone macros (no separators/args). Strip trailing `}` from identifier in this case. Show matching macro details when typing closing brace, same as when typing args. Add "no match" error option when typing args/closing brace but identifier doesn't match any macro. Extract `AnyMacroAutoCompleteOption` typedef for cleaner type annotations
* fix(autocomplete): show variable context when typing closing brace on shorthand macros
Detect `isTypingClosingBrace` state for variable shorthands (e.g., `{{.Lila}`, `{{.Lila+=4}`). Parse value before brace detection to check for trailing `}`. Show non-selectable context options (variable name, operator, value) when typing closing brace instead of operator/value suggestions. Strip trailing `}` from value when detected. Set `resultStart` to cursor position when typing closing brace to avoid replacement
* fix(autocomplete): stop flag parsing at newlines and show context when typing closing brace on variable shorthands
Skip newlines (not just all whitespace) between flags to prevent extending macro context across line breaks. Show variable context (name, operator, value) when typing closing brace on shorthand macros by excluding `isTypingClosingBrace` from the value-typing check.
* Fix highlight of value autocomplete option
* Rename permanentMatch to forceFullNameMatch
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
9ff9d59672 |
Macros 2.0 (v0.7.1) - Macro Autocomplete everywhere (#5019)
* Add macro autocomplete for free text inputs
Implements macro autocomplete (`{{`) for textareas and input fields marked with `data-macros` attribute. Extracts shared autocomplete logic into MacroAutoCompleteHelper.js for consistency between slash command and free text contexts. Includes MutationObserver for dynamic element initialization and supports variable shorthands, operators, flags, and scoped macro closing tags.
* fix annoying circular dependency again
* Add `data-macros` attribute to enable macro autocomplete on text inputs
Enables macro autocomplete (`{{`) for various textareas and input fields throughout the UI by adding the `data-macros` attribute. Includes context template fields, instruct mode sequences, character/persona descriptions, world info content, and other prompt-related inputs. Also ensures the attribute is preserved when expanding editors and creating world info entries.
* Allow macro autocomplete in editing messages
Enables macro autocomplete (`{{`) when editing messages by adding the `data-macros` attribute to the dynamically created edit textarea element.
* Add autocomplete visibility setting support for macro autocomplete
Respects the global STScript autocomplete visibility setting (`power_user.stscript.autocomplete.state`) for macro autocomplete in free text inputs. When set to "Input length > 1", macro autocomplete only activates after typing `{{` plus at least 2 characters. Also adds a tooltip to the visibility setting explaining it applies to both slash commands and macros.
* Fix unclosed div tag in STScript autocomplete visibility setting
Closes the `<div>` tag that was incorrectly left open in the autocomplete visibility setting markup.
* Add setting to control macro autocomplete visibility in non-expanded fields
Introduces a new `showInAllMacroFields` setting that controls whether macro autocomplete appears in all macro-enabled fields or only in expanded editors and when pressing Ctrl+Space. Also adds `data-macros-autocomplete` attribute support with `always` and `hide` modes for per-field override. When the setting is off, autocomplete only shows in expanded editors (which now get `data-macros-autocomplete="always"`) and the completion
* Add `data-macros-autocomplete-style` attribute to control macro autocomplete popup size
Introduces a new `data-macros-autocomplete-style` attribute with `small` (33vw, max 700px) and `expanded` (default chat width) modes to control macro autocomplete popup dimensions. The `small` style is now the default for inline fields, while `expanded` is used for expanded editors and prompt manager. Also refactors `getAutocompleteMode` to return `DEFAULT` instead of `null` and adds corresponding `getAutocompleteStyle` helper
* Fix autocomplete details panel alignment when list is constrained by viewport edge
Adjusts the details panel position to align with the actual autocomplete list position when the list is constrained by the right edge of the viewport. Previously, the panel would position based on cursor location even when the list was pushed left, causing misalignment. Now checks if the list's actual position differs from the calculated position (with 5px tolerance) and uses the list's position instead.
* Guard autocomplete details panel alignment check with `isReplaceable` condition
Prevents attempting to read the autocomplete list's bounding rect when the list is not visible. The alignment adjustment for viewport-constrained lists now only runs when `isReplaceable` is true, avoiding potential errors when the list DOM is not rendered.
* Fix macro autocomplete cursor detection to handle nested macros correctly
Updates `findMacroAtCursor` to track nesting depth when searching for opening `{{` and closing `}}` braces. Previously would incorrectly stop at the first brace pair encountered in either direction, breaking autocomplete when cursor was inside nested macros like `{{getvar::{{getvar::name}}}}`. Now properly skips over nested macro boundaries by incrementing/decrementing depth counters until finding the matching braces at depth
* gief me my comments back (and fixes, that were missed)
- Added detailed JSDoc comments to all exported functions explaining parameters, return types, and behavior
- Added inline comments throughout functions explaining logic flow, edge cases, and implementation details
- Documented parser-based vs regex-based unclosed scope detection approaches
- Clarified variable shorthand autocomplete logic including operator filtering, context display, and priority
* refactor(macros): freeze MACRO_AUTOCOMPLETE_MODE and MACRO_AUTOCOMPLETE_STYLE enums
* feat(macros): explicitly set `makeSelectable` flag for non-insertable autocomplete options
- Set `makeSelectable = true` for variable shorthand options in {{if}} conditions (already insertable)
- Set `makeSelectable = false` for already-typed operators in variable shorthand autocomplete
- Set `makeSelectable = false` for already-typed flags in macro autocomplete
- Set `makeSelectable = false` for non-selectable closing block flags when no unclosed scopes exist
- Set `makeSelectable = false` for sc
* refactor(macros): consolidate typedef imports in MacroAutoCompleteHelper
- Fixed typo in MacroDefinition typedef import (removed extra `/` from JSDoc comment)
- Replaced long-form typedef imports with short-form aliases for MacroAutoCompleteContext and MacroDefinition
- Improved code consistency by using imported typedefs throughout function signatures
* refactor(autocomplete): select first selectable item as default instead of always first item
- Extracted default item selection logic into `selectDefaultItem()` method
- Changed default selection to prioritize first selectable item over first item in list
- Falls back to last item when no selectable items exist (preserves context for info-only options)
- Added JSDoc documentation explaining selection behavior
* feat(macros): make already-typed variable names non-selectable in autocomplete
- Set `makeSelectable = false` for variable name options that match the currently typed name
- Set empty `valueProvider` for matched variables to prevent re-insertion
- Prevents redundant selection of variables that are already fully typed in the input
* feat(macros): add value context autocomplete option for variable shorthand operators
- Created `VariableValueContextAutoCompleteOption` class to display context about expected values
- Shows operator name, symbol, and description when typing variable shorthand values
- Displays currently typed value and completion hint
- Non-selectable option (context only) with priority 4
- Added to variable shorthand autocomplete when operator is typed and value is being entered
* fix lint
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
ca60ba148c |
chore(macros): Allow registration of aliases for existing macros (#5053)
- Added `registerMacroAlias()` public method to register aliases for existing macros - Extracted shared registration logic into private `#registerMacroEntry()` helper - Refactored `registerMacro()` to use `#registerMacroEntry()` for both primary macros and aliases - Alias registration validates name format, prevents self-aliasing, and resolves alias chains to primary definition - Aliases inherit handler and metadata from target but has source of the registration caller |
||
|
|
42155ecebf |
Macros 2.0 (v0.7.3) - Variable Shorthand: Comparison Operators & Autocomplete Improvements (#5050)
* feat: Add numeric comparison operators (>, >=, <, <=) to variable shorthand syntax - Added four new comparison operators for local and global variables - Implemented greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual operations in MacroCstWalker - Updated lexer to recognize >=, >, <=, < operators (longer patterns before shorter to avoid conflicts) - Simplified parser by consolidating operator alternatives into single OR block - Enhanced autocomplete with operator definitions, examples, and usage * Improve autocomplete for variable shorthand operators with cursor-aware filtering - Track `variableNameEnd` and `variableOperatorEnd` positions in parsed macro context for accurate cursor position checks - Add `isShortOperatorPrefix()` helper to detect operators that could be prefixes of longer ones (e.g., `>` → `>=`) - Fix operator autocomplete to show longer variants when typing short operators (typing `>` now shows both `>` and `>=`) - Show operator suggestions immediately when variable |
||
|
|
6f5032f20e |
Allow reasoning edit to substitute macros on saving the reasoning (#5052)
* Apply macro substitution when editing reasoning content - Added `substituteParams()` call to process macros in edited reasoning text - Changed `newReasoning` from const to let to allow reassignment * chore: Remove unnecessary double macro substitution from message edit - Removed `substituteParams()` call for first message (index 0) in `messageEditDone()` - Macro substitution is now handled consistently by `updateMessage()` for all messages |
||
|
|
26d495f457 |
Add /reroll-pick command to reset {{pick}} macro (#5049)
* feat(macros): Add `/reroll-pick` command to reset `{{pick}}` macro choices
- Added `/reroll-pick` slash command to change the seed for all `{{pick}}` macros in current chat
- Command accepts optional numeric seed value, otherwise increments current seed by 1
- Updated `{{pick}}` macro to use `pick_reroll_seed` from chat metadata in seed calculation
- Updated `{{pick}}` macro description to mention reroll capability
- Added comprehensive help text with examples for `/reroll-pick` command
- Updated tests
* lint fix
* fix(macros): exclude null reroll seed from {{pick}} hash calculation
- Changed reroll seed default from 0 to null when not set
- Filter out null values from combined seed string to avoid including "-0" suffix
- Updated both core macro implementation and tests to match new behavior
* Use strict null comparison
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
f3c886fd12 |
Add APP_INITIALIZED event before hideLoader in initialization sequence, before APP_READY fires (#5051)
* Add APP_INIT event before hideLoader in initialization sequence * refactor(events): rename APP_INIT to APP_INITIALIZED --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
9b0f0dcc9a |
Fix legacy name prefix removal using wrong variable in bookmarks
Fixes leftover bug from #4993. In both `getBookmarkName` and `createBranch`, the second regex replacement was incorrectly using the original `name` variable instead of the already-cleaned `cleanName` variable, causing the legacy prefix removal to fail. |
||
|
|
0b529290aa | Macros 2.0 expose runtime warn log function | ||
|
|
f8c373f55a |
Macros 2.0 (v0.7.0) -Variable Shorthand: New Operators & Lazy Evaluation (#4997)
* Add new variable shorthand operators and new variable macros
- Add `{{hasvar}}` and `{{deletevar}}` macros for local variables
- Add `{{hasglobalvar}}` and `{{deleteglobalvar}}` macros for global variables
- Implement new variable shorthand operators: `-=`, `||`, `??`, `||=`, `??=`, `==`
- Refactor variable expression evaluation to use direct variable API calls instead of routing through macro registry
- Add comprehensive operator support in lexer with proper token ordering for multi-character operators
* Implement lazy evaluation for variable shorthand value expressions
- Replace eager value evaluation with lazy evaluation pattern for variable operators
- Add `#createLazyValue()` method that caches value expression result on first call
- Change `#executeVariableOperation()` to accept `lazyValue` function instead of pre-evaluated value
- Only evaluate value expressions when actually needed (e.g., when variable is falsy for `||`, when variable doesn't exist for `??`)
- Add comprehensive e2e tests
* Update variable shorthand autocomplete with new operators and add edge case tests
- Add new operators to autocomplete definitions: `-=`, `||`, `??`, `||=`, `??=`, `==`
- Update example lists in `VariableShorthandAutoCompleteOption` and `VariableNameAutoCompleteOption`
- Add operator definitions with descriptions and `needsValue` flags to `VariableOperatorDefinitions`
- Update `parseMacroContext()` to recognize new operators with proper ordering (longer operators checked first)
* Add not equals (!=) operator to variable shorthand expressions
- Add `!=` operator to variable shorthand definitions for local and global variables
- Implement `notEquals` operation in `MacroCstWalker` that returns inverted equality comparison
- Add `NotEquals` token to lexer with pattern `/!=`
- Update parser to handle `!=` operator with value expression
- Add `!=` operator to autocomplete examples and operator definitions
- Update `parseMacroContext()` to recognize `!=` operator and...
* Tiny code review fixes
- Fix typo: "insie" → "inside" in variable shorthand operators comment
- Remove extra space in `{{getglobalvar}}` example usage
* Fix missing closing braces in hasglobalvar macro example usage
* Fix isFalsy to normalize value before checking boolean state in variable shorthand operators
- Apply `normalize()` to value before passing to `isFalseBoolean()` in `isFalsy` helper
- Ensures consistent falsy evaluation for variable shorthand operators like `||`, `??`, `||=`, `??=`
* Fix pipe character inside macro braces being treated as command separator
- Add `isInsideMacroBraces()` method to track unclosed `{{}}` macro braces
- Modify `testCommandEnd()` to only treat `|` as command end when not inside macro braces
- Scan text behind current position to calculate macro brace depth
- Skip second character when detecting `{{` or `}}` pairs
- Ensure `depth` never goes below 0 using `Math.max(0, depth - 1)`
* Add aliases for variable existence and deletion macros
- Add `varexists` alias for `hasvar` macro
- Add `flushvar` alias for `deletevar` macro
- Add `globalvarexists` alias for `hasglobalvar` macro
- Add `flushglobalvar` alias for `deleteglobalvar` macro
* Update variable shorthand operator descriptions to clarify return behavior
- Add "returns nothing" clarification to `=`, `+=`, `-=` operators in examples and definitions
- Add "returns the new value" clarification to `++`, `--` operators in examples and definitions
- Update `VariableOperatorDefinitions` descriptions to match example text
- Ensures users understand which operators return values vs perform silent mutations
|
||
|
|
491f2a3afd |
Feature: Enhanced Branch and Checkpoint Naming (#4993)
* Add customizable name builder and max tries to getUniqueName utility
- Add optional `nameBuilder` parameter to allow custom name formatting
- Add `maxTries` parameter to client-side version to prevent infinite loops
- Update JSDoc with new optional parameters
- Use nullish coalescing to set default name builder function
- Default name builder maintains existing "${baseName} (${i})" format
* Add startIndex option to getUniqueName utility for flexible name generation
* Enhance branch creation to use current chat name and ensure unique names
- Import `getCurrentChatDetails` from script.js
- Replace hardcoded branch name format with current chat name as base
- Add custom `buildBranchName` function to format branch names with suffix
- Strip existing " - Branch #N" suffixes before generating new branch name
- Use `getUniqueName` utility with `nameBuilder` to ensure unique branch names
- Remove unused `mainChat` variable and replace with `mainChatName`
* Enhance checkpoint creation to use current chat name and suggest unique names
- Import `getCurrentChatDetails` from script.js to get current chat name
- Add custom `buildCheckpointName` function to format checkpoint names with suffix
- Strip existing " - Checkpoint #N" suffixes before generating new checkpoint name
- Use `getUniqueName` utility with `nameBuilder` to ensure unique checkpoint names
- Pass `suggestedName` to template and popup input for better UX
- Replace manual loop with `getUniqueName`
* Remove automatic timestamp suffix from bookmark names
* Fix getUniqueName utility to correctly handle maxTries and return null on failure
* shut up copilot
* Strip legacy bookmark and branch name prefixes when generating unique names
- Add removal of old "Checkpoint #N - " prefix format in `buildCheckpointName`
- Add removal of old "Branch #N - " prefix format in `buildBranchName`
- Change `cleanName` from const to let to allow multiple replacements
- Ensures clean base names regardless of legacy or current naming format
|
||
|
|
858b9e684e |
Enhance world duplication to use current world name as base (#4990)
- Update `getFreeWorldName()` to accept optional `worldName` parameter and `stripIndex` option - Add JSDoc documentation for `getFreeWorldName()` parameters and return value - Modify world duplicate handler to pass current world name to `getFreeWorldName()` - Strip existing numbered suffix from base name before generating new numbered name - Default to "New World" when no world name is provided - Make "New World" translatable |
||
|
|
5c2a02a128 |
Fix {{pick}} macro seeding inside delayed-resolution macros like {{if}} (#4986)
- Thread `contextOffset` through `MacroEngine.evaluate()` to preserve global document position
- Update `resolve()` in execution context to pass caller's `globalOffset` as `contextOffset`
- Add `offsetDelta` option to `resolve()` for additional offset customization
- Add regression tests for `{{pick}}` inside `{{if}}` blocks with `delayArgResolution`
- Ensure identical picks at different positions produce different results
|
||
|
|
3047045d37 |
Macros 2.0 [Fix] - Fix macro evaluation to allow nested scoped macros in arguments (#4977)
* Fix scoped macro evaluation to allow nested scoped macros in arguments
- Refactor `#evaluateArgumentNode` to re-parse argument content for scoped macro pairs
- Create shared `#evaluateRawContent` helper method for consistent text evaluation
- Update `#evaluateScopedContent` to use the shared helper, reducing duplication
- Add 8 comprehensive test cases for nested scoped macros in arguments
- Enhance JSDoc documentation for EvaluationContext text parameter
* Fix `{{pick}}` macro to use global document offset for deterministic seeding
- Replace `range.startOffset` with `globalOffset` in pick macro handler for consistent position-based seeding
- Add `contextOffset` to EvaluationContext to track base offset from original document (starts at 0 for top-level)
- Calculate `globalOffset` as `contextOffset + range.startOffset` when building MacroCall objects
- Thread `contextOffset` through evaluation pipeline: MacroEngine → MacroCstWalker → all evaluation
* Fix typo in MacroCstWalker JSDoc comment and thread contextOffset through evaluateDocument
- Correct JSDoc typo: "rull macro text" → "full macro text"
- Destructure `contextOffset` from options in `evaluateDocument` method
- Pass `contextOffset` to EvaluationContext instead of hardcoded 0
|
||
|
|
e40b31b06d |
Macros 2.0 (v0.5.2) - Onboarding for new Macro Engine (#4955)
* Macros 2.0 [Feature] - Add onboarding popup for experimental macro engine features
- Add `onbordingExperimentalMacroEngine()` function in MacroDiagnostics.js to detect and prompt users about experimental features
- Detect experimental macro features in `substituteParamsLegacy()`: {{if}}, scoped macros, macro flags, variable shorthands, nested macros
- Add feature detection in autocomplete parser for macro flags, variable shorthands, and leading whitespace
* Fix typo: rename `onbording` to `onboarding` throughout macro diagnostics system
* Add `void` operator to async onboarding calls and fix typo in comment
- Add `void` operator to all `onboardingExperimentalMacroEngine()` calls to explicitly discard Promise return values
- Fix typo in MacroDiagnostics.js comment: "hat" → "that"
* Fix typo in experimental macro engine onboarding popup: "anytime time" → "any time"
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
b453fdc5d8 |
Macros 2.0 [Fix] - Macro display override uses alias name if relevant + preserve whitespaces for autocomplete closing tag (#4953)
* Refactor: Move MacroBrowser.js to macros/engine directory and update import paths
* Replace macro name with alias in displayOverride for macro browser
- Import escapeRegex utility for safe regex pattern creation
- Check if macro has aliasOf property when displayOverride is present
- Replace all occurrences of the original macro name with the alias name in displayOverride text
- Use word boundary regex pattern to match macro names in {{macro}}, {{macro::}}, and {{macro }} contexts
* Add whitespace padding preservation for macro closing tag autocomplete
- Extract paddingBefore and paddingAfter from opening macro tags in MacroCstWalker
- Pass padding info through unclosed scope detection in findUnclosedScopes() and findUnclosedScopesRegex()
- Update MacroClosingTagAutoCompleteOption constructor to accept padding options
- Apply same whitespace padding to closing tags as their corresponding opening tags
- Update regex fallback to capture and preserve whitespace from opening tags
* Add replacementStartOffset to AutoCompleteOption for whitespace normalization in closing tags
- Add replacementStartOffset property to AutoCompleteOption class with JSDoc documentation
- Update AutoComplete.select() to apply per-option replacement offset when calculating effectiveStart
- Calculate replacementStartOffset in MacroClosingTagAutoCompleteOption based on currentPadding length
- Pass currentPadding from context.paddingBefore to MacroClosingTagAutoCompleteOption in SlashCommandParser
* Fix closing tag detection regex to correctly autocomplete // macro
* Add flags and fullText to EnhancedMacroAutoCompleteOption context and fix {{//}} autocomplete offset
- Add flags, currentFlag, and fullText properties to EnhancedMacroAutoCompleteOptions JSDoc
- Store options object as #options field in EnhancedMacroAutoCompleteOption for later access
- Pass flags, currentFlag, and fullText from context to macroContext in SlashCommandParser
- Fix {{//}} macro autocomplete to adjust replacementStartOffset when typed after single slash to avoid treating it as flag
* Add unnamedArgs definition to {{//}} comment macro for better documentation
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
cd0627bfec |
Macros 2.0 [➕Macros] - Add {{hasExtension}} macro, and refactor extension lookup logic (#4948)
* Add {{hasExtension}} macro and refactor extension lookup logic
- Move findExtension() from extensions-slashcommands.js to extensions.js and export it
- Update findExtension() to return object with name and enabled properties instead of just name string
- Add {{hasExtension}} macro to check if an extension is enabled
- Update /extension-state and /extension-exists commands to use refactored findExtension()
- Remove duplicate findExtension() implementation from extensions-slashcommands.js
* Refactor extension action callbacks to use extension object instead of separate name and enabled properties
* fix eslint
|
||
|
|
81414724b0 |
Macros 2.0 (v0.5.1) - Delayed Macro Argument Resolution for {{if}} Macro (#4934)
* Add variable shorthand syntax support for local and global variables
- Add VariableShorthandType enum and VariableShorthandDefinitions for `.` (local) and `$` (global) prefixes
- Add VariableShorthandAutoCompleteOption class for autocomplete of variable shorthand syntax
- Implement variable expression parsing in MacroCstWalker to handle `{{.varName}}` and `{{$varName}}` syntax
- Add support for variable operations: get, set (=), increment (++), decrement (--), and add (+=)
- Route variable expressions to appropriate macro via handler
* Add variable shorthand autocomplete support for variable names and operators
- Add `isValidVariableShorthandName()` helper to validate variable names against shorthand pattern
- Add `VariableNameAutoCompleteOption` class for suggesting existing and new variable names
- Add `VariableOperatorAutoCompleteOption` class for suggesting operators (=, ++, --, +=)
- Add `VariableOperatorDefinitions` map with operator metadata (symbol, name, description, needsValue)
* Add variable shorthand support to {{if}} macro condition autocomplete
- Add variable shorthand (.var, $var) support to {{if}} condition evaluation in core-macros.js
- Detect and resolve variable shorthands using getvar/getglobalvar macros before condition check
- Update {{if}} description and examples to document variable shorthand syntax
- Add variable shorthand autocomplete options when typing {{if}} condition
- Show variable prefix options (. and $) when no condition is typed yet
- Reuse #buildVariableShorthandOptions
* refactor: Add Object.freeze to lexer constants and improve JSDoc documentation
- Freeze `modes` and `Tokens` objects to prevent accidental mutations
- Convert inline comments to proper JSDoc format for better documentation
- Add JSDoc block for `Def` lexer definition object
- Improve comment clarity and formatting consistency throughout MacroLexer.js
- Remove redundant section separator comments in variable shorthand modes
* Add inversion prefix (!) autocomplete support to {{if}} macro condition
- Add SimpleAutoCompleteOption class for basic autocomplete items with name, symbol, and description
- Add ! inversion prefix as autocomplete option in {{if}} condition with 🔁 icon
- Show ! as selectable option when nothing typed, non-selectable when already present
- Fix condition parsing to handle ! prefix with whitespace (e.g., "! $myvar")
- Update identifier extraction to strip ! and whitespace before detecting variable
* fix lint
* Fix variable shorthand regex in {{if}} macro to properly capture prefix and variable name
* Expand comprehensive e2e tests for variable shorthand syntax in lexer and macro engine
- Add MacroLexer tests for variable shorthand edge cases (whitespace, numbers, underscores, operators)
- Add MacroEngine tests for variable shorthand operations (hyphens, underscores, non-existent vars, chaining)
- Add MacroEngine tests for variable shorthand in {{if}} conditions (truthy/falsy, inversion, else branches)
- Test variable names with hyphens, underscores, and numbers in both get/set and conditional contexts
* Fix macro flags not being allowed inside variable shorthand macros
- Move MANY(flags) block from macroBody to macro rule to parse flags before branching
- Fix MacroCstWalker to extract flags from children.flags instead of bodyChildren.flags
- Ensures flags are available for both variable expressions and regular macros
- Fixes flag extraction in visitMacro and visitBlockMacroClose methods
* Implement delayed argument resolution for {{if}} macro to prevent side effects in non-chosen branches
- Add `delayArgResolution` flag to MacroDefinition to control when nested macros are evaluated
- Modify MacroCstWalker to skip nested macro evaluation when delayArgResolution is true
- Update {{if}} macro to use delayArgResolution and manually resolve only the chosen branch
- Replace ELSE_MARKER splitting with `splitOnTopLevelElse()` that parses CST to find correct {{else}} at depth 0
* Fix delayed resolve on if/else macros being off when a non-scoped if macro was being used inside
- Track argument count in MacroCstWalker.extractMacroInfo() to distinguish inline vs scoped macros
- Update splitOnTopLevelElse() to only track scoped {{if}} blocks (1 arg) when finding {{else}} at depth 0
- Update findClosingMacro() to only increment depth for macros that can accept scoped content
- Add e2e tests for inline {{if::condition::content}} inside scoped {{if}}/{{else}} blocks
* Remove eslint exclusion
* Remove duplicate tests
* Regenerate package-lock.json in /tests
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
dbc4fe611c |
Macros 2.0 [Fix] - Make macro name matching case-insensitive throughout the macro system (#4942)
* Make macro name matching case-insensitive throughout the macro system - Normalize macro names and aliases to lowercase in MacroRegistry storage and lookup - Update MacroCstWalker to use case-insensitive matching for block macro pairing - Normalize dynamic macro keys to lowercase in MacroEnvBuilder - Update MacroEngine to use lowercase keys when checking dynamic macros - Preserve original casing in macro definitions for display purposes - Add comments explaining case-insensitive matching behavior * Make alias validation case-insensitive in MacroRegistry to prevent duplicate names - Prevents registering aliases that differ only in casing from the macro name |
||
|
|
0dcd9906bf |
Macros 2.0 (v0.5) - Add variable shorthand macros and variable support to {{if}} macro (#4933)
* Add variable shorthand syntax support for local and global variables
- Add VariableShorthandType enum and VariableShorthandDefinitions for `.` (local) and `$` (global) prefixes
- Add VariableShorthandAutoCompleteOption class for autocomplete of variable shorthand syntax
- Implement variable expression parsing in MacroCstWalker to handle `{{.varName}}` and `{{$varName}}` syntax
- Add support for variable operations: get, set (=), increment (++), decrement (--), and add (+=)
- Route variable expressions to appropriate macro via handler
* Add variable shorthand autocomplete support for variable names and operators
- Add `isValidVariableShorthandName()` helper to validate variable names against shorthand pattern
- Add `VariableNameAutoCompleteOption` class for suggesting existing and new variable names
- Add `VariableOperatorAutoCompleteOption` class for suggesting operators (=, ++, --, +=)
- Add `VariableOperatorDefinitions` map with operator metadata (symbol, name, description, needsValue)
* Add variable shorthand support to {{if}} macro condition autocomplete
- Add variable shorthand (.var, $var) support to {{if}} condition evaluation in core-macros.js
- Detect and resolve variable shorthands using getvar/getglobalvar macros before condition check
- Update {{if}} description and examples to document variable shorthand syntax
- Add variable shorthand autocomplete options when typing {{if}} condition
- Show variable prefix options (. and $) when no condition is typed yet
- Reuse #buildVariableShorthandOptions
* refactor: Add Object.freeze to lexer constants and improve JSDoc documentation
- Freeze `modes` and `Tokens` objects to prevent accidental mutations
- Convert inline comments to proper JSDoc format for better documentation
- Add JSDoc block for `Def` lexer definition object
- Improve comment clarity and formatting consistency throughout MacroLexer.js
- Remove redundant section separator comments in variable shorthand modes
* Add inversion prefix (!) autocomplete support to {{if}} macro condition
- Add SimpleAutoCompleteOption class for basic autocomplete items with name, symbol, and description
- Add ! inversion prefix as autocomplete option in {{if}} condition with 🔁 icon
- Show ! as selectable option when nothing typed, non-selectable when already present
- Fix condition parsing to handle ! prefix with whitespace (e.g., "! $myvar")
- Update identifier extraction to strip ! and whitespace before detecting variable
* fix lint
* Fix variable shorthand regex in {{if}} macro to properly capture prefix and variable name
* Expand comprehensive e2e tests for variable shorthand syntax in lexer and macro engine
- Add MacroLexer tests for variable shorthand edge cases (whitespace, numbers, underscores, operators)
- Add MacroEngine tests for variable shorthand operations (hyphens, underscores, non-existent vars, chaining)
- Add MacroEngine tests for variable shorthand in {{if}} conditions (truthy/falsy, inversion, else branches)
- Test variable names with hyphens, underscores, and numbers in both get/set and conditional contexts
* Fix macro flags not being allowed inside variable shorthand macros
- Move MANY(flags) block from macroBody to macro rule to parse flags before branching
- Fix MacroCstWalker to extract flags from children.flags instead of bodyChildren.flags
- Ensures flags are available for both variable expressions and regular macros
- Fixes flag extraction in visitMacro and visitBlockMacroClose methods
* Add SillyTavern global to tests eslintrc
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
e9bedadc0b |
Macros 2.0 (v0.4) - Add scoped macros (last arg can be scoped), {{if}} macro and macro flags (baseline implementation) (#4913)
* Macros: make category optional, default to UNCATEGORIZED
* Tests: Update macro tests to match new error handling behavior
- Change MacroRegistry tests from expecting thrown errors to capturing console.error logs
- Update MacroLexer tests to expect plaintext fallback instead of lexer errors for invalid tokens
- Fix MacroEngine test to use `char` macro instead of `newline` for arity validation
- Update MacroParser test with corrected expected error message for invalid identifiers
- Remove "[Error]" prefixes from test descriptions where lexer no longer errors
* Macros: Implement macro execution flags system
- Add MacroFlags module with flag parsing and validation (!, ?, ~, /, >, ., $, #)
- Update lexer to tokenize flags as separate tokens before macro identifier
- Modify parser to capture flags in CST under 'flags' label
- Update CST walker to parse flag tokens into MacroFlags object
- Pass parsed flags to macro handlers via MacroCall and MacroContext
- Update autocomplete parser to handle flags before identifier
- Add comprehensive tests for flag parsing,
* Macros: Fix autocomplete positioning for macros with flags and whitespace
- Add identifierStart to parseMacroContext to track where identifier begins in macro text
- Update autocomplete to use identifierStart for correct range calculation
- Simplify indexMacros regex to use global flag instead of manual loop
- Use parseMacroContext in indexMacros to extract identifier (handles flags/whitespace)
- Fix autocomplete range starting at wrong position when flags or whitespace present
* Macros: Add autocomplete support for macro execution flags
- Add MacroFlagAutoCompleteOption class for rendering flag options in autocomplete
- Extend parseMacroContext to track currentFlag (flag cursor is on) and isInFlagsArea
- Track flagEndPositions to determine which flag cursor is currently typing
- Update #buildEnhancedMacroOptions to show flag options when cursor is in flags area
- Show current flag first if cursor just typed it, then show remaining available flags
- Add renderItem and renderDetails methods to MacroFlag
* Macros: Implement scoped macro syntax with opening and closing tags
- Add scoped macro processing to MacroCstWalker to find and merge opening/closing pairs
- Parse closing block flag (/) to identify closing macros and match with opening tags
- Extract content between opening and closing tags as the last unnamed argument
- Add `isScoped` property to MacroCall and MacroContext to track scoped invocations
- Implement `#processScopedMacros` to find outermost matching pairs and handle nesting
* Macros: Add autocomplete warnings, scoped content info, and closing tag suggestions
- Add arity warning banners in autocomplete details for invalid argument counts
- Show warning when using space-separated args on multi-arg or no-arg macros
- Add scoped content info banner when cursor is inside unclosed scoped macro
- Implement MacroClosingTagAutoCompleteOption to suggest closing tags for scoped macros
- Add sortPriority property to AutoCompleteOption for controlling sort order
* SlashCommands: Disable unimplemented flags and closing flag when no unclosed scopes in autocomplete
- Set closing block flag as non-selectable when no unclosed scopes exist
- Set unimplemented flags as non-selectable with empty valueProvider
- Lower sort priority (12) for non-selectable flags vs selectable flags (10)
* Autocomplete: Show scoped content info and auto-close no-arg macros
- Show scoped content info when cursor is at closing }} of unclosed scoped macro
- Auto-complete no-arg macros with closing }} using valueProvider
- Trigger autocomplete on select (isSelect) to refresh after choosing an option
- Simplify MacroFlagAutoCompleteOption to use base makeItem for consistent styling
- Change closing tag icon from '{/}' to '{/' for better visual consistency
* Macros: Add scoped trim macro to trim content inside opening/closing tags
- Add scoped usage for {{trim}}content{{/trim}} to trim whitespace from content
- Keep non-scoped {{trim}} behavior (post-processing marker) for backward compatibility
- Add optional unnamed 'content' argument for scoped usage
- Update description to explain both scoped and non-scoped behavior
- Handler checks isScoped flag to determine which behavior to use
* Autocomplete: Fix closing tag parsing to prevent `/` being treated as flag
- Add special case in parseMacroContext to detect closing tags (`/` + identifier char)
- Stop flag parsing when `/` is followed by identifier character (closing tag syntax)
- Simplify MacroClosingTagAutoCompleteOption valueProvider to return full closing tag
- Remove input-based logic since autocomplete replaces entire identifier
* Macros: Add {{if}} conditional macro with auto-resolution of macro names
- Add {{if condition}}content{{/if}} macro to conditionally show content
- Auto-resolve condition if it matches a registered macro name (0 required args)
- Support both scoped content ({{if x}}...{{/if}}) and explicit args ({{if::x::content}})
- Treat empty string, "false", "off", "0" as falsy conditions
- Inherit environment context when resolving macro names
- Update autocomplete warning to allow space-separated syntax
* Macros: Add centralized identifier validation with pattern enforcement
- Export MACRO_IDENTIFIER_PATTERN from MacroLexer for reuse across modules
- Add isIdentifierValid() helper function to validate macro names and aliases
- Enforce identifier pattern: must start with letter, followed by word chars or hyphens
- Update macro registration to validate both primary names and alias identifiers
- Improve error messages to explain identifier requirements
- Add comprehensive e2e tests for valid/invalid identifier patterns
* Macros: Add tests for scoped {{trim}} macro functionality
* SlashCommands: Fix macro indexing to properly handle nested macros with brace depth tracking
- Replace regex-based macro detection with manual brace depth tracking
- Track opening/closing brace pairs to correctly identify macro boundaries
- Ensure nested macros like {{reverse::Hey {{user}}}} are properly indexed
- Index both outer and inner macros by scanning content recursively
- Handle unclosed macros by defaulting to end of text
* Macros: Add {{else}} branch support to {{if}} conditional macro
- Add {{else}} macro as marker to split then/else branches in {{if}} blocks
- Use control character sequence (\u0000\u001FELSE\u001F\u0000) as internal marker
- Split scoped content on else marker and trim both branches independently
- Return then-branch if condition is truthy, else-branch if falsy
- Auto-suggest {{else}} in autocomplete when inside scoped {{if}} block
- Make {{else}} non-selectable in autocomplete when outside {{if}} scope
* Macros: Add negation support to {{if}} conditional macro with ! prefix
- Add ! prefix support to invert condition evaluation in {{if}} macro
- Parse original macro text to detect ! prefix before macro resolution
- Strip ! from condition after detecting inversion to avoid double-negation
- Invert isFalsy result when ! prefix is detected in original condition
- Prevent ! in resolved values from triggering inversion (only original syntax)
* Autocomplete: Add {{if}} condition autocomplete with zero-arg macro suggestions
- Add EnhancedMacroAutoCompleteOptions typedef for noBraces/paddingAfter/closeWithBraces options
- Support options object in EnhancedMacroAutoCompleteOption constructor alongside context
- Add noBraces mode to display macro names without {{ }} braces (for use as values)
- Add paddingAfter option to match opening whitespace style before closing }}
* Autocomplete: Match opening whitespace padding when auto-closing macros
* Fix `{{if}}` example usages
* Macros: Hide `comment` alias from autocomplete suggestions for `//` macro
* Macros: Simplify {{trim}} handler with destructured parameters and clearer content check
* Macros: Use MacroEngine.evaluate for zero-arg macro resolution in {{if}} condition handler
* Macros: Add auto-trim for scoped content with # flag to preserve whitespace
- Auto-trim scoped content by default in MacroCstWalker before passing to handlers
- Add preserveWhitespace flag (# symbol) to prevent auto-trimming when needed
- Rename legacyHash flag to preserveWhitespace across engine and definitions
- Update {{trim}} handler to rely on engine auto-trim for scoped content
- Update {{if}} handler to respect # flag when trimming branches around {{else}} marker
* Macros: Clarify macro name validation error message to use "alphanumeric characters" instead of "word chars"
* Add 'setspriteoverride' optional 'name' argument
* Refactor ElevenLabs TTS API key handling (#4906)
* Refactor ElevenLabs TTS API key handling #4483
* Remove unused connection button and related event handler from ElevenLabs TTS provider
* Add ElevenLabs STT endpoint
* Add caching system prompt feature for OpenRouter Gemini (#4903)
* feat: add caching system prompt for OpenRouter Gemini
* fix: resolve reviews
* Update GitHub links to llama.cpp
* Add model selection support for llama.cpp router mode (#4910)
* Add model selection support for llama.cpp router mode
- Add llamacpp_model setting to textgen-settings.js
- Implement loadLlamaCppModels() function to fetch and populate models
- Add onLlamaCppModelSelect() handler for model selection
- Update status check to load llama.cpp models when connecting
- Update getTextGenModel() to return selected llama.cpp model
- Add model dropdown to HTML UI in llama.cpp section
- Initialize event handlers and Select2 for better UX
- Add llamacpp_model to preset manager for save/load support
- Add llamacpp_model to slash commands support
This implements model selection for llama.cpp router mode, allowing
users to select from multiple models without restarting the server.
Follows the same pattern as Ollama, Tabby, and vLLM implementations.
* Correct spelling
* Fix clear selection position
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Add glm-4.7 model option and context mapping for Z.AI
* Add select2 style for NanoGPT list
Closes #4911
* Disable macro engine init traces
* Update type annotations for instruct presets and context presets
* Fix test for new error text
* Add MacroStoryString tests
* Add trimContent utility for consistent indentation dedenting in scoped macros
- Add trimScopedContent method to MacroEngine that trims and dedents scoped content based on first non-empty line indentation
- Pass trimContent utility through evaluation context to all macro handlers
- Update {{if}} macro to use trimContent instead of direct trim() call
- Update auto-trim logic in MacroCstWalker to use trimContent for consistent dedenting
- Add trimContent to MacroExecutionContext type definitions
* Add ELSE_MARKER export and cleanup leftover markers in macro processing
* Update trimContent parameter to use options object pattern in JSDoc
* Add processor registration system to MacroEngine with priority-based execution
- Add MacroProcessor callback and RegisteredProcessor typedef for pre/post processors
- Add addPreProcessor/removePreProcessor and addPostProcessor/removePostProcessor methods with priority-based sorting
- Refactor core legacy syntax handling into registered processors with reserved priorities (0-50)
- Move legacy time syntax, marker replacements, brace unescaping, trim macro, and ELSE_MARKER cleanup to registered processors
* Split core processor registration into separate pre and post processor methods
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
|
||
|
|
000fbccda9 |
Optimize {{pick}} macro by caching content hash in MacroEnv
|
||
|
|
6f8b6b098e |
Macros 2.0 (v0.3) - Replacing the existing Macro System with a new Macro Engine (#4820)
* Chevrotain lib and env setup
* First draft of the macro lexer
* fix ESLint types loading for chevrotain
* Cleaner lexer modes
* Readme link to Chevrotain & license
* Add jsconfig to tests folder
- Add jsconfig.json to tests folder, to prevent IDE errors on dynamic imports inside the page.evaluate execution.
* Slight improvements on lexer & first tests
* Add more lexer tests
* More edge cases tests
* Reorder tests
* Add macro execution modifiers + more tests
- Added macro flags (execution modifiers) to lexer
- Fixed some lexing issues
- Expanded lexer tests
- Treat lexer errors as failed test
* enable eslint for tests and run it
* Fix lexing unknown flags - treat as error
* Rewrote lexer modes/tokes to capture errors better
* Add lexing for output modifiers
* Clearer names for lexer tokens
* Increase tests default timeout
* Restructure lexer error testcases
* Allow legacy underscores in macro identifiers
* Test case for legacy single-colon syntax
* Improve lexer, removing warnings
* Basic setup for MacroParser + initial tests
* Make parser errors testable
* Add macros stuff to SillyTavern.getContext
* macros test case naming + lint
* Parser consumes basic macros
- Fix lexer mode names
- Add basic macro parsing (identifier, and arguments)
- Tests: basic macro parsing tests
- Tests: simplifyCstNode supports ignoring nodes, or flattening nodes to just plaintext
* Improve macro argument parsing to allow colons in values
Enhances separator handling by fixing separator type detection and enabling colon characters within argument values
Updates validation to require at least one argument component and adds error cases for empty arguments
Includes expanded test coverage for mixed separator scenarios and edge cases
* More nested macro tests
Add error case tests to enforce macro start position requirements
Include nested macro parsing scenarios and invalid syntax checks
Ensures parser correctly handles edge cases with embedded macros
* Unvendor chevrotain
* Add document rule
* Implement visitor, switch built-ins to new type
* Puppeteer -> playwright
* Revert "Implement visitor, switch built-ins to new type"
This reverts commit
|
||
|
|
a11abc4273 |
Add new WORLDINFO_SCAN_DONE event with mutable state for extensions (#4797)
* chore: Add WORLDINFO_SCAN_DONE event with mutable state for extensions * Fix incorrect scan state reference in world info recursion logic * Fix typo in world info scan state property name: 'sucessful' → 'successful' (am i stupid) |
||
|
|
19ae4e7cc1 |
feat: add max-height and scrolling to world entry key input fields (#4769)
- Added 160px max-height to select2 multiple selection, primary key, and secondary key text areas in world entries - Enabled vertical scrolling with hidden horizontal overflow for better UX with long content |
||
|
|
81367629fe |
Feat: Improve multiline input handling in popups (#4756)
* feat: improve multiline input handling in popups - Added Ctrl+Enter requirement for submission in multiline input popups to prevent accidental sends - Exported PopupUtils class for external use * refactor: remove redundant higher/different rows from input popups - Removed rows: 2 from callGenericPopup calls where default behavior is sufficient - Increased rows from 2 to 4 in caption extension for better multiline input experience |
||
|
|
bc06f3e3e0 |
Refactor: make whitelist validation a bit more robust (#4757)
* refactor: extract IP whitelist validation into helper function - Added isIPInWhitelist helper with error handling for individual whitelist entry checks - Replaced inline whitelist matching logic with reusable function calls - Added JSDoc type annotations and error logging for failed IP matching attempts * refactor: simplify whitelist validation with upfront filtering - Moved IP validation to startup time instead of per-request checking - Extracted validateWhitelist function to filter invalid entries once at initialization - Simplified isIPInWhitelist by removing redundant error handling after validation * fix: correct IP whitelist matching to use parsed CIDR notation |
||
|
|
6963f5cdd7 | chore: add test-results directory to gitignore | ||
|
|
b0dd267b9e | feat: enhance HTML escaping to include single quotes (#4755) | ||
|
|
5fd64bef2e | fix: improve bot detection and event filtering in GitHub workflow conditions | ||
|
|
59d4c7f5d7 | fix: restrict app token generation to internal PRs and add fallback auth token (on PR comments) | ||
|
|
01e3880587 | refactor: add has() and get() to MacrosParser (#4626) | ||
|
|
806726d737 |
Workflows Switch all to use app token/app for any PR/issue labeling/commenting action (#4624)
* ci: switch workflows to use app token/app id authentication * That wasn't supposed to go in this PR * chore: refactor to local token minting step [Test] * chore: expose token output from setup-app-token action and add PR checkout step * ci: replace checkout and custom app token with create-github-app-token action in PR merge conflict workflow * ci: add test label action to PR conflict check workflow * another test... * I am losing my sanity * can this work now? please? This action adds my debug level? * it needs to run always * let's do it via curl...? * why did it (totally not me) remove the always() again * Sorry I screamed at you, Qwen. Does this work? * refactor: consolidate GitHub App token creation into individual jobs * chore: remove debug label functionality from merge conflict workflow * chore: let's figure out why labeler is not behaving * chore: remove temporary GitHub API token validation check from PR workflow * ci: ensure workflow jobs run regardless of previous job failures by adding if: always() |
||
|
|
f88ba369dd |
Workflows: Replace ISSUES_BOT_TOKEN with GitHub App for labeling + 'against release' auto comment (#4621)
* ci: replace ISSUES_BOT_TOKEN with GitHub App authentication for PR auto-labeling workflow * Update PR auto comments for target branch guidance Added note about changing target branch for PRs. --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
74ff23ec0c | fix: remove focus call before keyup event dispatch that traps cursor (#4607) | ||
|
|
9463d1a152 |
Reprint non-tainted group chat on switching personas (#4603)
* fix: reprint non-tainted group chat on switching personas * feat: mark chat as tainted when sending user message * feat: mark chat as tainted when adding custom messages or captions * feat: export createOrEditCharacter function and integrate it into retriggerFirstMessageOnEmptyChat * fix: optimize loadPersonaForCurrentChat by storing current chat ID in a variable * Improve conditions of first message retrigger --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
c4cb0b783a | security: update GitHub workflows to use ISSUES_BOT_TOKEN instead of GITHUB_TOKEN (#4606) | ||
|
|
39fd16fe86 |
Fix not jumping twice to group chat when creating a new group chat with deleting the old one (#4602)
* fix: do not jumo to chat twice on new group chat with delete * fix: prevent metadata reset when deleting non-active group chat * Bring back group chat splice call * Always delete past group metadata on chat delete --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
a65f708fd8 |
Allow create new world books via /getpersonabook and /getcharbook (#4597)
* feat: allow create new world books via /getpersonabook and /getcharbook Refactor character world info management into dedicated functions Extract character world assignment logic from UI handlers into reusable functions Add support for automatic lorebook creation in slash commands Improve code maintainability by centralizing world info operations * refactor: update boolean enum provider from onOffToggle to trueFalse in world info commands * fix: improve world info name uniqueness check using getUniqueName utility * Unset current persona WI on file deletion --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com> |
||
|
|
23b1360204 | fix: add optional chaining to prevent undefined error when accessing first_mes (#4601) | ||
|
|
d56c649d86 | style: hide self-responses label when activation strategy is not natural (#4593) | ||
|
|
08f48a9867 | fix: enable character source (open link) when group is selected (#4592) | ||
|
|
06f5cea402 |
Fix group chat on new chat not respecting saved persona connections (#4594)
* fix: (new) group chat doesn't respect persona connections Fixes #3876 * refactor: simplify persona connection filtering with destructuring and type comparison * fix: remove redundant type check in persona connection filtering logic (char avatar and group key *should* always be unique and different anyway, no need to check on type. Makes this more flexible) |