* Fix: HTTP Basic Auth fails when password contains colons
The credentials in HTTP Basic Auth are formatted as base64(username:password).
Per RFC 7617, the username must not contain a colon, but the password can.
The previous code used `.split(':')` which splits on all colons, truncating
passwords that contain ':' characters. Fix by splitting only on the first colon.
* Use spread syntax for credential parsing
* 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.
* feat(server): make CORS middleware configurable
Add detailed configuration options for CORS in config.yaml, including
origin, methods, headers, credentials, and max age. Update server
initialization to apply these settings dynamically instead of using
hardcoded values.
* fix(server): Fix default value and conditional logic issues in CORS configuration
- Changed the default value of `cors.maxAge` from `null` to `0`.
- Simplified the conditional check logic for `allowedHeaders`, removing duplicate checks for `corsAllowedHeaders` being `null`.
* fix(server): Fix CORS exposed headers configuration logic
- Removed redundant conditional checks. now directly validates array length when `corsExposedHeaders` has a truthy value
* Improve types + simplify checks
* fix(cors): align maxAge default with original behavior
* Adjust default array values
* Remove debug log
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* 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.
* Add background sort by date added feature
* reapply search after changing sort
* overengineer it
* use sortIgnoreCaseAndAccents
* make enum for sort options
* Centralized `await clearChat();` and `chat.length = 0;` into `wipeChat()`
* Added `clearData` argument to `clearChat`.
---------
Co-authored-by: user <user@exmaple.com>
* Startup and on-demand check
* Update comments, add color preload
* remove redundant metadata generation
* changed image-metadata/all from GET to POST
* move initializeAllUserMetadata to image-metadata.js, make blocking (?)
* Add type annotations
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Feat - Allow to bulk toggle all third-party extensions from popup manager
* Fix - Prevent reloading the page if the final state is the same
* Fix - Handle bulk toggle with no extensions installed
* Update - Delete leftover debug logs
* Fix - Simplify extension toggle logic and improve readability
* Update - State that bulk toggle only affects external extensions
* Feat - Allow to restore bulk toggled extensions
* Update - Move bulk toggle to the third-party extensions header
* Uncenter section headers
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* 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>
* git push --force
Implement background management in json
lint
upload multer weirdness, fix for timestamp
* remove duplicated logic to generate backgrounds.json
* remove duplicate logic to create backgrounds.js
* remove excessive enodent eror handling
* simplify shared extension constants
* move backgrounds.json to backgrounds/index.json
* use plimit
* move user directory iteration to syncBackgroundsMetadata insetad of server main
* create and move getBackgroundThumbnailResolution
* nitpick
* typdef
* simplify checks
* use read method
* error -> regenerate
* use fileExists
* type error fix (maybe)
* add object to jsdoc returns
* typo
* use getUniqueName from util.js
* remove duplicated multer something or other
* make skipped_extensions a set
* remove strict comparison
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* create isAnimatedWebP and use it
* use file creation date instead of server date
* actually type BackgroundImageMetadata
* use fileExists instead of try catch
* response.sendStatus(500);
* sync json to allow adding images to the folder without restart
* lint
* Generic image metadata endpoint. Remove tags and starred. No startup sync.
* lint
* Descriptive json and move to util.js
* remove folders routes
* It's a POST
* Revert file name to index.json
* Type errors fixing
* Remove p-limit
* Why?
* apply codex suggestions
* see comment
* remove unused functions
* remove path normalization for da path, not needed
* Fix dimensions shadowing issue, circular imports, and apply bg res to only bg
* move thumbnailsEnabled to the top level
* Metadata now stored at {userDataRoot}/image-metadata.json instead of per-folder index.json
Uses relative paths as keys (e.g., backgrounds/sunset.png) for easy file existence checking
Added cleanupOrphanedMetadata() function and /api/image-metadata/cleanup endpoint for data-maid integration
Simplified the API endpoint by removing folder-grouping logic
* lint
* update backgrounds.js imports
* security check, .replaceAll
* Remove useless function, pass type to cache invalidate and seperate file types
* fix: normalize file paths to use POSIX separators in metadata functions
* serve original
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Refactor /search to use per-line async parsing
Supersedes #5047
* Use named type
* Cache query fragments, add file name match
* Skip invalid chat files in search
* Remove extensions from /search results
* Use file_id when appropriate
* Revert "Use file_id when appropriate"
This reverts commit aaa0274b53.
* Clean-up file extension handling
* Move extension append down for non-group
* feat(tts): Add support for Volcengine TTS provider
* refactor: Remove the redundant comments in the Volcengine TTS-related code.
* fix(volcengine): Fix the audio data processing logic in the voice generation interface
* feat(tts): Enhance Volcengine TTS functionality and improve error handling
- Return more detailed error information when generating voice fails
- Add multiple preset voice options and support custom voice management
- Reconstruct the audio stream processing logic to enhance reliability
- Improve the UI interface, adding a voice selection dropdown menu and operation buttons
* refactor(tts): Optimize the code structure and error handling of the Volcengine TTS provider
- Remove the unused "voices" array and "model" parameter
- Improve the text processing logic, eliminating unnecessary separators
- Standardize the error handling logic, simplifying the status code checks
- Fix the DOM operation method, using "createElement" instead of string concatenation
- Ensure the existence check of the "customVoices" array
* Fix: Change the Content-Type of the audio response to audio/mpeg.
* Clean-up
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Expose character update APIs for extensions
Add getCharacterSource, importFromExternalUrl, and importTags to the
extension context (SillyTavern.getContext()). This allows extensions to:
- Get the source URL for a character (Chub, etc.)
- Import/update a character from an external URL
- Import tags from a character's embedded tag data
These functions already exist and are used internally but were not
exposed to extensions. This enables extension developers to build
features like bulk character update checking and tag synchronization.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix review comments
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* 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>
- 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
* 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
* 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
* 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>
* try to modify config.yaml at start instead of modify it
* replace error with warn when failing to write config.yaml
---------
Co-authored-by: ccss <ccss>
* feat(sd): Add generation status indicator and improve abort handling
- Add persistent toast notification showing "Generating image..." during generation
- Toast displays spinner, supports multiple concurrent generations with count
- Click toast to dismiss (generation continues in background)
- Improve abort handling: show friendly "Image generation stopped" info message
instead of error when user clicks stop button
- Handle abort in both generatePicture() and sendGenerationRequest() catch blocks
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Scope abort controllers for each individual button
* Use native element reference for caching button abort controller
* Update toast in paintbrush button handler
* refactor: Update abort message for image generation in sdMessageButton
* feat: Enhance generation indicator with active generation count in toast
* Move tracking after prompt generation, add toast for LLM prompt gen progress
* Add type annotation for generation toastr
* Simplify generation abort checks
* Remove unnecessary blank line in addSDGenButtons function
---------
Co-authored-by: mschienbein <mschienbein@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Add vector slash commands
* Updated vector-threshold command per feedback. Want to validate it is correct before fixing other commands.
* Added slash commands for several vector storage settings.
* Added slash commands for vector storage, updated w/dev feedback
* Fix min value of entries
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Add taxon controls to top of group member list
* Refactor/cleanup getGroupCharacters
* Fix favorites, refactor and cleanup code
* Fix clearing filters, only show relevant filters in groups
* Fix issues and add persistence
- Fix group member tag listing requiring character list to be init to display
- Fix character tag updates to actually show up in group member contexts
- Persist filter changes for group member tag controls
* Apply suggestions from code review
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Avoid sibling selectors
* Err on invalid tag type
* avoid hardcoded ids
* cleanup: don't use `group_member`, use `group_candidates_list`
* Support both selectors and jquery instances in getFilterHelper
* Sanitize missing tag filters before rendering
* Unscrew jsdoc formatting
* Show all tags, mark absents specially
* Improve JSDoc
* Fix tag indicator for group contexts
* Don't use deprecated fields
* Add a comment on potentially undefined group id
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
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.
* Improved printMessages performance by reducing DOM updates.
Refactored part of addOneMessage into createMessageElement.
Before: Rendered 1000 messages in 25.529199999809265 seconds.
After: Rendered 1000 messages in 5.088 seconds.
* Fixed mistakes: https://github.com/SillyTavern/SillyTavern/pull/4947#pullrequestreview-3624592007
* Formatting fix
* Fixed scroll and last_mes order..
* Refactored printMessages logic into redisplayChat.
* Passed `fade`.
* Cleanup.
* WIP.
Removed getMessageFromTemplate
Refactored addOneMessage and updateMessageElement.
* Minor changes to better match https://github.com/SillyTavern/SillyTavern/pull/4985
* If insert is false, `newMessage` may not be new, so I renamed `newMessage` to `messageElement` and `newMessageId` to `messageId`.
I also rearranged some constants to improve readability.
* Accept 0 as valid insertAfter/insertBefore targets
* Renamed forceId to messageId for clarity.
* Change forceId to undefined by default.
* Swapped `forceId` to `messageId` in addOneMessage.
* Added adjustMediaScroll to updateMessageElement.
* Revert "Change forceId to undefined by default."
This reverts commit cbda7eb3fe.
---------
Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* feat(sd): Add Z.AI GLM-Image model support
Add the new GLM-Image model to the Z.AI image generation source:
- Add 'glm-image' to the model dropdown with friendly display name
- Handle GLM-Image's requirement for dimensions in multiples of 32
(vs CogView's multiples of 16)
- Show quality dropdown for GLM-Image (supports standard/hd)
The GLM-Image model uses the same API endpoint as CogView
but has different dimension constraints.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* feat(sd): Enhance Z.AI GLM-Image support
- Use regex for GLM-Image model detection (futureproofing)
- Skip 2^21 pixel limit for GLM-Image (CogView-specific)
- Add Z.AI recommended resolutions (1280x1280, 1568x1056, etc.)
- Add "Use Coding API" toggle for GLM Coding Plan users
- Add better error logging for image fetch debugging
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* refactor(sd): Address PR review feedback for Z.AI GLM-Image
- Remove custom zai_coding_api setting, use existing oai_settings.zai_endpoint
- Always use Common API for image generation (avoids rate limits)
- Keep ZAI_ENDPOINT import for consistency with other extensions
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* fix: always use Common API for Z.AI image generation
Removes conditional endpoint selection since we decided to always use
Common API for image generation (Coding API has stricter rate limits).
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* It's not only cogview anymore
* Remove unused param from request payload
* Remove redundant debug logs
* Loosen the check on image quality data attribute
* Bring back coding API notice
---------
Co-authored-by: mschienbein <mschienbein@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* If insert is false, `newMessage` may not be new, so I renamed `newMessage` to `messageElement` and `newMessageId` to `messageId`.
I also rearranged some constants to improve readability.
* Accept 0 as valid insertAfter/insertBefore targets
* Yeah whatever
---------
Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* 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
* Extracted updateMessageItemizedPromptButton and getMessageHTML from addOneMessage to improve readability.
* Fix types and function calls
* Fixed insertBefore, insertAfter and messages without extra.
* Use strict comparison operator
* Use logical OR for display text fallback
* Fixed newMessageId again.
* Faster showMoreMessages.
* removed `insertAfter` and `insertBefore` from `mes_edit_copy`, `/message-role` and `/message-name`.
* Formatting fix
* Refactor newMessageId
---------
Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Reduced redundant swipe code by fully updating the swipe message.
* `getMessageFromTemplate` is an inconvenient function that requires more lines than it saves.
It cannot be used in any other function, therefore it should not exist.
This change also prevents an unnecessary call of `messageTemplate.clone` in addOneMessage when `type = 'swipe'`.
ESLint.
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4983#discussion_r2680379455
* Replaced ?? with &&: https://github.com/SillyTavern/SillyTavern/pull/4983#discussion_r2680366010 and removed comments.
* Fixed bias check. "0" is falsy.
* Remove scroll adjust early bail
* Call appendMediaToMessage before updating content
Because we need to preserve chatHeight and scrollPosition according to the previous swipe, not the new one
---------
Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* 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
- 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
- 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
* 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
* Bypass REPLACE_GETVAR with experimental parser enabled
* (wip) macro-2.0 replacer in STscript parser
* Add support for MacroDefinitionOptions format in dynamic macros
- Add DynamicMacroValue typedef supporting string, function, or MacroDefinitionOptions object
- Extract macro definition building logic into MacroRegistry.buildMacroDefFromOptions() method
- Update MacroEngine to detect and handle three dynamic macro formats:
1. string - direct value, no args allowed
2. function - handler function, no args allowed (legacy)
3. MacroDefinitionOptions object - full definition with handler, args, type
* Implement dynamic macro replacers
* Remove global typedef
* Use unique closure boundary
* Add e2e tests for MacroSlashCommands
* Update public/scripts/macros/engine/MacroEngine.js
Co-authored-by: Wolfsblvt <wolfsblvt@gmail.com>
* Use strict args array match
* Update public/scripts/macros/engine/MacroEngine.js
---------
Co-authored-by: Wolfsblvt <wolfsblvt@gmail.com>
* 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>
* 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>
* 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
* 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>
* 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
* Add regex filter option to TTS extension
- Added checkbox to enable/disable regex filtering of TTS text
- Added text input for custom regex patterns
- Default pattern removes emojis and non-English text while preserving letters, numbers, spaces, and punctuation
- Regex is applied after asterisk removal and other text processing
- Includes error handling for invalid regex patterns
- Automatically cleans up extra spaces after regex removal
* reverted the accidental change in tts_skip_tags description
clarified the regex description
* Add regex validation warning to TTS settings
* fixed regex field in UI
* reworked the regex warning
* changed the regex event to change (input might not have worked correctly)
* Apply review comments
* Spacing fix
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* 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>
* 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>
* create and export updateWorldInfoSettings
* Add WorldInfoSettings type and refactor updateWorldInfoSettings function
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Add an additional slash command to change a message's character and avatar.
* Refactor message character change command to update message sender's name
* Fix default value
* Allow setting unbound message names
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Add comfyrunpod generation endpoints.
Get a bunch of settings added.
Probably get runpod api secret stored properly.
sending to runpod.
Correct workflow wrapping for runpod.
* Reuse comfyui workflow setting block for runpod.
* Update API key url to point to runpod settings
* Remove debug print.
* Combine normal and runpod comfyui generation functions
* Remove unused server endpoints for runpod.
* Remove debug prints from server.
* Remove redundant switch case.
* Check for url to see if image generation is possible for comfy and comfy runpod.
* lint
* Correct/update doc comments.
* Make runpod serverless a sub-type under comfyui source in the UI.
* Set comfy_type in stable-diffusion defaultSettings
* Allow loading comfy workflows even if url isnt set yet.
* Change default runpod url to template example
* Rename runpod api key to comfy_runpod
* Handle default switches separately from standard now that default setting is ensured.
* Update runpod api key name on server.
* Move example runpod url to placeholder.
* lint
* Remove incorrect comment.
* Hide toasts remote models toasts
* React to key updates
* Add type annotation for data and improve workflow handling in generate endpoint
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Added an option to hide message avatars in `User Settings > UI Theme`.
* Deprecated the `Hide Chat Avatars` toggle.
Moved the option to hide message avatars to `User Settings > UI Theme > Avatars`.
* Revert "Deprecated the `Hide Chat Avatars` toggle."
This reverts commit 6f616767cc.
* Moved `Hide Chat Avatars` next to `Avatar Style`, added title text.
* Reverted changes.
---------
Co-authored-by: user <user@exmaple.com>
* 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>
* Implement Gemini thought signatures
* Implement streaming support for Gemini thought signatures
* Implement OR support for Gemini thought signatures
* Remove unnecessary extraction of thought sigs from response parts
* Update thought sig comments to remove explicit Gemini mention
* Fix thought_signature naming convention in message.extra
* Add thought_signatures to ReasoningMessageExtra typedef
* Prevent thought sigs being sent to incompatible endpoints
* Move signatures to populateChatHistory, update for consistent casing
* Code clean-up
* Only send thought signatures if target model and API match original
* Implement content-hash thought signature mapping
* Change the data model + split for text/functions
* Don't include signature to invocations if the model doesn't match
* Fix function description
* Remove misleading comment
* Handle OpenRouter signatures
* Improve message extra types
* Prevent modifying original invocations when removing signatures
* Fix return of openrouter non-streaming signatures
* Remove redundant array check
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* 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 706a94b4de.
* Converted puppeteeer tests
* File rename
* chore: reduce Playwright worker count to 4 for performance/stability
* test: add comprehensive legacy macro parser test suite
- Added 13 test cases covering legacy macro formats (roll, reverse, comment, datetime, time_UTC, banned, setvar)
- Documented parser limitations with TODO comments for whitespace separators, special characters, and empty arguments
- Tests validate parsing of various separator styles (space, colon, +/-) and argument formats (quoted, numeric, empty)
* fix: handle legacy macro syntax with colon or whitespace separator
- Modified arguments rule to support both double-colon (::) and single-colon (:) separators
- Made single-colon separator optional to allow whitespace-separated legacy macros
- Removed TODO comments as parser now correctly handles legacy macro formats
* feat: support space-separated quoted arguments in macro parser
- Added parsing support for equals signs and quotes as valid argument tokens
- Removed TODO comments for legacy macro parsing with quoted arguments
* fix: improves macro argument parsing with colon handling
Enhances parser to correctly handle double colons within legacy single-colon arguments
Introduces separate parsing rules for arguments with different colon constraints
Adds test coverage for arguments containing double colons in legacy format
* fix: allow empty macro arguments after double-colon separator
- Changed argument rule from AT_LEAST_ONE to MANY to permit zero-length arguments
- Updated tests to verify empty argument parsing (e.g., `{{something::}}`)
- Enhanced simplifyCstNode helper with default flatten/ignore keys and improved null handling
* refactor: improve test documentation with inline macro display
- Added inline comments showing the actual macro syntax being tested for better readability
- Removed duplicate comment in error test case
- Cleaned up extra whitespace in legacy macro tests
* feat: add legacy macro preprocessing for time offset format
- Implemented preProcessFixLegacyMacros method to convert {{time_UTC±N}} to {{time::UTC±N}} format
- Updated tests to use new preprocessing step for legacy time macro parsing
- Added runPreProcessFix option to test helper functions for controlled legacy macro handling
* feat: add support for comment macros with double-slash syntax
- Added `DoubleSlash` token to lexer to recognize `//` as a valid macro identifier
- Updated parser to accept either `//` or standard identifiers as macro names
- Enhanced test suite with comprehensive comment macro test cases including multiline support
* feat: implement macro evaluation engine with CST walking and registry integration
(I'm tired, let's just throw this in right now)
- Added CST walker and macro registry to engine initialization
- Enhanced parseDocument to handle empty input, legacy macro preprocessing, and error collection
- Implemented async evaluate method with full macro resolution pipeline
- Added resolveMacro callback to handle unknown macros and registry execution
- Integrated lexing/parsing error handling with console warnings
- Added support for preserving unknown macro
* refactor: improve type safety and code clarity in macro evaluation system
- Simplified typedef imports to use correct Chevrotain types (CstNode, IToken)
- Added TokenRange typedef for consistent offset handling
- Enhanced error messages with context-specific prefixes
- Replaced verbose type casts with inline JSDoc annotations
- Condensed singleton pattern declarations to single lines
- Improved null safety with optional chaining and nullish coalescing
- Extracted resolveMacro logic into private root function
* fix test macro whitespace arguments onls accepting one argument
* Fix OpenRouter embeddings URL
#4736
* Fix: Prevent data loss on bulk regex move to scoped scripts (#4760)
* Fix: Prevent data loss in regex bulk move
* prevents moving to scoped scripts with group selected for bulkedit
* 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
* 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
* Fix npm audit
* 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
* Bump anti-troll tags limit
Closes#4763
* OpenAI: Add Sora 2 API (#4748)
* OpenAI: Add Sora 2 API
* Add duration control
* Support client generation abort
* Reduce poll log amount
* Simplify selector
* Simplify model-specific control handling
* Gemini: Pass non-success response content to frontend
* Vertex: Add Vertex AI-specific safety setting (#4770)
Closes#4455
* Feature: allows sorting tags by most used (#4768)
* add sorting tags by most used
* Fix whitespaces
* Code review updates
* Remove commented code
* Fix capitalization in comment
* Apply review suggestion
* Simplify template init
* Reformat
* Add documentation for appendViewTagToList and printViewTagList functions
* Reprint renamed tags regardless of sorting mode
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Move img.swipe notice block up
* Preserve media playback state when running appendMediaToMessage (#4771)
* Preserve media playback state when running appendMediaToMessage
* Better selector specificity
* Fix local variable name
* Move typedef to global.d.ts
* Check for readyState on save/restore
* Only check for currentSrc on restoration callback
* gpt-5.1
* A 500 billion dollar startup can’t filter API payload fields
* Refactor macro argument validation to use requiredArgs and list pattern
- Replace minArgs/maxArgs/enforceArity with requiredArgs and list specification
- Add MacroListSpec typedef for flexible list argument constraints (min/max)
- Rename enforceArity to strictArgs with inverted default behavior
- Update validation logic to separately track required vs. list arguments
- Add requiredArgs and list arrays to MacroExecutionContext for easier access
- Improve error messages to clearly distinguish between required and list
* Refactor MacroRegistry.registerMacro to use options object pattern
- Move handler function into options object as required property
- Improve validation with detailed error messages for all option fields
- Add explicit type checking for requiredArgs, list, strictArgs, and description
- Consolidate name normalization and validation logic
- Simplify list option parsing with clearer conditional structure
- Update all builtin macro registrations to use new signature
* Add e2e tests for macro arity validation errors
- Test ping macro rejects calls with unexpected arguments
- Test upper macro rejects calls without required arguments
- Verify macros remain unresolved and log warnings on arity violations
* re-implement core macros as registered macros
- Create shallow frozen copy of env object before passing to macro handlers
- Add comprehensive MacroEnv typedef with nested types for names, character, system, and extra fields
- Update MacroDefinitionOptions typedef to clarify default values and mark handler as required
- Export variable manipulation functions for external use
- Fix whitespace in ifCallback JSDoc comment
* Defer slash command autocomplete initialization to firstLoadInit
- Move slash command autocomplete setup from module-level to initSlashCommandAutoComplete function
- Add null check for sendTextarea.value before accessing first character
- Import and call initSlashCommandAutoComplete in firstLoadInit sequence
- Export registerCoreMacros, registerInstructMacros, and registerVariableMacros using named export syntax
- Call registerCoreMacros from initMacros with
* Add variable manipulation functions to SillyTavern context API
- Import deleteGlobalVariable, deleteLocalVariable, addGlobalVariable, addLocalVariable, incrementGlobalVariable, incrementLocalVariable, decrementGlobalVariable, and decrementLocalVariable from variables.js
- Expose del, add, inc, and dec methods on both context.variables.local and context.variables.global objects
- Provide consistent API for variable deletion, addition, increment, and decrement operations
* Extract test setup utilities and fix trailing comma in core-macros.js
- Add testSetup utility object with goST and awaitST helper functions for Playwright tests
- Replace duplicated beforeEach setup code in MacroLexer, MacroParser, and MacroRegistry tests with testSetup.goST
- Add explanatory comments indicating tests currently run without ST context
- Fix missing trailing comma in input macro handler registration
* Refactor MacroEngine e2e tests to use real core macros instead of prototypes
- Replace prototype macros (ping, echo, upper, wrap, first) with actual core macros (newline, reverse, setvar, getvar, addvar, roll)
- Use testSetup.awaitST helper from utils.js for beforeEach setup
- Increase test timeout from 10s to 20s due to additional setup requirements
- Remove registerPrototypeMacros import and registration logic from evaluateWithEngine
- Add page.waitForTimeout(1000) to ensure macros are fully initialize
- Remove now obsolete MacroBuiltins.js
* Fix audit in tests
* Rename frontend test utils file to frontent-test-utils.js and update imports
- Rename tests/frontend/utils.js to tests/frontend/frontent-test-utils.js
- Update testSetup imports across MacroEngine, MacroLexer, MacroParser, and MacroRegistry e2e tests
* Refactor MacroRegistry for improved readability and consistency
- Reorder MacroDefinition typedef fields to match registration order (handler moved to end)
- Add inline JSDoc comments to MacroDefinitionOptions properties for clarity
- Simplify name validation logic in unregisterMacro, hasMacro, and getMacro methods using early returns
- Extract argument validation logic into dedicated isArgsValid helper function
- Refactor executeMacro to be async and use Promise.resolve for consistent promise handling
* Add returns field to MacroDefinitionOptions for documenting macro return values
- Add returns property to MacroDefinitionOptions typedef with string type and null default
- Include returns field in MacroDefinition typedef
- Store returns value in macro definition object for documentation purposes
* Add error handling to macro execution and refactor core macro handlers
- Add catch handler in MacroRegistry.executeMacro to log errors and return empty string on handler failures
- Update macro descriptions to use "index" instead of "ID" for message position macros
- Simplify reverse macro description and remove redundant null coalescing
- Add strictArgs: false to comment macro to ensure it's always removed
- Enhance time macro description with UTC offset examples
- Remove unnecessary null check
* Refactor instruct-macros.js for consistency and reduce code duplication
- Rename enabled helper to instEnabled and add sysEnabled helper for clarity
- Consolidate defaultSystemPrompt, instructSystem, and instructSystemPrompt into single registerSimple call
- Simplify systemPrompt handler by removing unnecessary null coalescing and intermediate variables
- Convert chatSeparator and chatStart macros to use registerSimple helper
- Fix JSDoc comment formatting for registerSimple helper function
* Add normalize helper to MacroExecutionContext and refactor variable macros for consistency
- Add normalizeMacroResult method to MacroEngine for converting macro results to strings
- Include normalize function in MacroExecutionContext for handler use
- Update normalizeMacroResult to handle arrays explicitly alongside objects
- Add returns field to variable macros that produce side-effects only
- Refactor variable macro handlers to use destructuring and normalize helper
- Remove redundant null checks an
* chore: Remove duplicate getglobalvar macro registration from variable-macros.js
- Remove redundant getglobalvar macro definition (already registered earlier in the file)
- Import MacroEngine in MacroRegistry for normalizeMacroResult access
- Add fallback binding for normalize in MacroExecutionContext when not provided by caller
- Update executeMacro to use executionContext.normalize instead of standalone normalizeMacroResult
- Remove normalizeMacroResult helper function from MacroRegistry (now handled by MacroEngine)
* Add core environment macros for names, character fields, system info, and deterministic pick
- Add lastGenerationType tracking with event listeners for GENERATION_STARTED and CHAT_CHANGED
- Add ensureLastGenerationTypeTracking helper to initialize event listeners once
- Register name macros: user, char, group, groupNotMuted, notChar, charIfNotGroup
- Register character card field macros: charPrompt, charInstruction, description, personality, scenario, persona, mesExamplesRaw, charDepthPrompt, cre
* Refactor core macros into separate modules by category (env, state, chat, time)
- Move name and character card field macros to new env-macros.js module
- Move system/device/runtime state macros to new state-macros.js module
- Move chat inspection macros (lastMessage, lastMessageId, etc.) to new chat-macros.js module
- Move time/date macros (time, date, weekday, isotime, etc.) to new time-macros.js module
- Remove lastGenerationType tracking logic and helper functions from core-macros.js (moved to state
* Reorganize macro system into engine and definitions directories
- Move macro engine components (MacroEngine, MacroRegistry, MacroLexer, MacroParser, MacroCstWalker) to macros/engine/ subdirectory
- Move macro definition modules (core-macros, env-macros, state-macros, chat-macros, time-macros, variable-macros, instruct-macros) to macros/definitions/ subdirectory
- Create macro-system.js as central entry point that exports engine singletons and initRegisterMacros function
- Refactor variable-macros.js to use S
* Export getGeneratingModel function and add MacroEnvBuilder to macro system exports
- Export getGeneratingModel function from script.js for external use
- Import MacroEnvBuilder in macro-system.js
- Add envBuilder singleton to macros export object alongside existing engine components
* Extract MacroEnv typedefs into separate MacroEnv.types.js file
- Create MacroEnv.types.js with MacroEnv, MacroEnvNames, MacroEnvCharacter, and MacroEnvSystem typedefs
- Remove MacroEnv typedef definitions from MacroRegistry.js
- Update MacroRegistry.js, MacroEngine.js, MacroEnvBuilder.js, and env-macros.js to import MacroEnv from MacroEnv.types.js
- Change MacroEngine.evaluate env parameter type from any to optional MacroEnv
* Add comprehensive e2e tests for MacroEnvBuilder
- Create MacroEnvBuilder.e2e.js with 13 test cases validating environment construction
- Test name override precedence (overrides vs global fallback)
- Test character field population based on replaceCharacterCard flag
- Test original value one-shot helper function behavior
- Test group override string propagation to group/group
* Add substituteParamsAsync function with experimental macro engine support
- Create substituteParamsAsync function in script.js as async alternative to substituteParams
- Use object destructuring pattern for function parameters following RO-RO convention
- Add experimental_macro_engine flag to power_user settings for feature gating
- Add MacroEnvFunctions typedef with original and postProcess function types to MacroEnv.types.js
- Add functions property to MacroEnv typedef for one-shot helpers an
* Add dynamic macro support to MacroEngine with environment-based override and postProcess execution
- Add defOverride parameter to MacroRegistry.executeMacro for temporary macro definitions
- Check env.dynamicMacros in MacroEngine#resolveMacro and create temporary macro definition when found
- Set strictArgs to true for dynamic macros to fail if called with arguments
- Execute env.functions.postProcess on macro results in MacroEngine#resolveMacro with error handling
- Update MacroEnv typedef to make
* Refactor macro handlers to assume non-null env and remove optional chaining
- Remove optional chaining (?.) from env property access in env-macros.js and instruct-macros.js
- Change MacroExecutionContext env property from optional to required in MacroRegistry.js
- Update executeMacro context parameter from optional to required
- Simplify original macro handler to call env.functions.original() directly without try-catch
- Update MacroHandler typedef to use arrow function syntax for consistency
- Remove redundant null checks an
* Refactor MacroRegistry.executeMacro to accept MacroCall object and make MacroExecutionContext properties non-optional
- Change executeMacro to accept MacroCall object instead of separate name and context parameters
- Move normalize function from context parameter to options object in executeMacro
- Construct MacroExecutionContext from MacroCall properties within executeMacro
- Set namedArgs to null in executionContext (currently unused)
- Update MacroEngine.resolveMacro to pass MacroCall directly
* Remove normalize parameter from MacroRegistry.executeMacro and bind normalizeMacroResult directly in execution context
- Remove normalize parameter from executeMacro options object in MacroRegistry.js
- Bind MacroEngine.normalizeMacroResult directly in executionContext instead of accepting override
- Remove normalize option from MacroEngine.resolveMacro call to executeMacro
- Add missing name fields (group, groupNotMuted, notChar) to MacroEnvBuilder default env object
* Make MacroEnvRawContext properties optional and change original function from required to optional in MacroEnvFunctions
- Change MacroEnvRawContext properties from required to optional with null defaults
- Change original function from required to optional in MacroEnvFunctions typedef
- Remove original function from default env object in MacroEnvBuilder (only include when provided)
* Refactor MacroEnvBuilder tests to use optional properties and add macro arity validation tests
- Remove explicit undefined/false assignments from MacroEnvRawContext test objects (now optional with defaults)
- Rename additionalMacro to dynamicMacros in MacroEnvBuilder tests and update property access from env.extra to env.dynamicMacros
- Move original function from env.extra to env.functions in test assertions
- Remove test for additionalMacro overriding original helper (no longer applicable with
* Improve macro error handling with dedicated diagnostics and runtime error propagation
- Import and use logMacroInternalError and logMacroRuntimeWarning from MacroDiagnostics in MacroEngine
- Wrap MacroRegistry.executeMacro call in try-catch to distinguish runtime vs internal errors
- Nest postProcess execution in inner try-catch with dedicated error logging
- Return raw macro syntax on execution failure instead of empty string
- Replace console.warn with logMacroRuntimeWarning for argument count
* Add macro argument type validation with positional argument definitions and runtime type checking
- Add MacroArgType and MacroPositionalArgDef typedefs for argument metadata
- Change requiredArgs option to accept number or MacroPositionalArgDef[] array
- Add requiredArgDefs property to MacroDefinition to store normalized argument definitions
- Validate requiredArgs array elements during macro registration (name, description, type fields)
- Generate default argument definitions when requiredArgs is a
* Add e2e tests for macro type validation and dynamic macro strict arity enforcement
- Add test verifying strict typed macros fail resolution when argument type is invalid
- Add test verifying non-strict typed macros execute with invalid types but log warnings
- Add test verifying dynamic macros reject arguments due to strictArgs enforcement
- Capture and assert runtime warning messages for type validation and arity violations
- Register test macros with integer type requirements and varying strict
* Add mesExamples macro with instruct mode formatting support
- Register mesExamples macro in env-macros.js to format dialogue examples
- Import parseMesExamples, main_api, power_user, and formatInstructModeExamples
- Check instruct mode enabled state and main_api to determine formatting path
- Parse raw examples using parseMesExamples with instruct mode flag
- Return empty string when raw examples are missing or parsed result is empty
- Format examples using formatInstructModeExamples when instruct mode is active
* Add URL navigation wait in test setup and increase Playwright worker count to 4
- Add waitForURL check after user selection in awaitST to ensure navigation completes before preloader check
- Increase Playwright workers from 1 to 4 for parallel test execution
* Add e2e tests for multi-line macro arguments and comment macro functionality
- Add test verifying reverse macro handles multi-line arguments with newline characters
- Add test verifying comment macro removes single-line comments with simple body
- Add test verifying comment macro accepts non-word characters immediately after //
- Add test verifying comment macro ignores additional // sequences inside comment body
- Add test verifying comment macro supports multi-line comment bodies
* Standardize JSDoc type annotations to use explicit null defaults and union types instead of nullable shorthand
* Remove individual test timeout configurations from frontend macro test files
* Add positional argument definitions with sample values and descriptions to core, env, and time macros
- Add sampleValue field to MacroPositionalArgDef typedef (optional string)
- Replace numeric requiredArgs with positional argument definition arrays in roll, banned, outlet, datetimeformat, and timeDiff macros
- Include name, sampleValue, description, and type fields for each positional argument
- Update timeDiff description to clarify absolute difference calculation
- Remove unnecessary blank lines in
* Remove async/await from macro engine evaluation and convert all macro handlers to synchronous execution
Makes me sad, but such is life
* Refactor substituteParams to use options object signature with backward compatibility for legacy positional arguments
- Rename original substituteParams to substituteParamsLegacy with unchanged positional argument signature
- Rename substituteParamsNew to substituteParams as the new primary function
- Add automatic detection and routing of legacy positional argument calls to substituteParamsLegacy
- Update substituteParamsExtended to use new options object signature and mark as deprecated
* forgor
* fix missing import, and package-lock, finally. Maybe.
* Add experimental macro engine toggle to UI settings
- Add experimental_macro_engine setting to default settings.json
- Move experimental_macro_engine property to correct position in power_user object (with other experimental settings)
- Add checkbox UI control in settings panel with flask icon and tooltip explaining nested macro resolution and logical replacement order
- Wire up checkbox event handler to save experimental_macro_engine setting
- Load experimental_macro_engine state on settings initialization
* Refactor macro pre/post-processing from parser to engine and improve error handling
- Move legacy macro pre-processing (time_UTC format) from MacroParser to MacroEngine #runPreProcessors
- Move trim macro post-processing to MacroEngine #runPostProcessors to handle cross-boundary behavior
- Remove MacroLexer import from MacroEngine (now handled by MacroParser.parseDocument)
- Update MacroParser.parseDocument to return separate lexingErrors and parserErrors arrays
* Add {{trim}} macro placeholder that defers to post-processing for cross-boundary whitespace handling
* Add eslint-plugin-playwright
* Add logMacroSyntaxWarning function for structured lexer/parser error reporting with compact human-readable payload
* Small code review fixes
- import event types from events.js
- Add chained fallback to {{input}}, just to be safe
- switched variables.js to export-per-method
- minor text adjustments in registered macro docs
* fix lexer not capturing linebreaks correctly & simplify plaintext token
- Replace alternation-based pattern with negated character class approach
- Use `(?:[^{]|\{(?!\{))+` to match non-brace chars or single braces not followed by another brace
- Add unicode flag for consistency
- Update comment to clarify intent: consume anything that is not the start of a macro '{{'
* Skip macro processing on char/group fields for env build (performance)
- Add returnRaw parameter to getCharacterCardFields to optionally return raw values without baseChatReplace
- Add returnRaw parameter to getGroupCharacterCards for consistent raw value handling
- Replace direct baseChatReplace calls with conditional transform function based on returnRaw flag
- Apply collapseNewlines when returnRaw is true and collapse_newlines setting is enabled
- Update MacroEnvBuilder to use the returnRaw as true
* Fix lexer failing to handle literal '{' before macro openers
- Add PlaintextOpenBrace token to lexer with pattern `/\{(?=\{\{)/` to match single '{' immediately before '{{'
- Update lexer mode definition to consume PlaintextOpenBrace before attempting macro start
- Update parser document rule to handle PlaintextOpenBrace as alternative to Plaintext
- Update MacroCstWalker to collect both Plaintext and Plaintext.OpenBrace tokens when building document items
* Add legacy non-curly marker pre-processing (<USER>, <BOT>, <CHAR>, <GROUP>, <CHARIFNOTGROUP>)
- Add pre-processing step in MacroEngine to rewrite legacy angle-bracket markers into their curly-brace macro equivalents
- Map <USER> → {{user}}, <BOT> → {{char}}, <CHAR> → {{char}}, <GROUP> → {{group}}, <CHARIFNOTGROUP> → {{charIfNotGroup}}
- Add e2e tests verifying legacy marker resolution through the engine pipeline
- Tests cover <USER>, <BOT>/<CHAR>, and <GROUP>/<CHARIFNOTGROUP> markers
* Add env.content to MacroEnv and use it for deterministic {{pick}} hashing
- Add content property to MacroEnv type definition and MacroEnvBuilder to expose the full original input string
- Update {{pick}} macro handler to use env.content hash instead of rawListString hash for seed generation
- Ensures deterministic behavior when the same prompt position contains different list items across evaluations
- Prevents {{pick}} from returning different values when nested macros resolve to different intermediate
* add e2e tests for env.content exposure and deterministic {{pick}} behavior
- Rename getChatIdHashCore → getChatIdHash in core-macros.js for consistency
- Add e2e test verifying env.content is exposed to macro handlers
- Add e2e test confirming {{pick}} returns stable results for same chat and content
- Tests verify deterministic behavior by comparing multiple evaluations with fixed chat_id_hash
* Rename chat macro helper functions to remove 'Core' suffix for consistency
* Add MacrosParser deprecation warnings and bridge to new macro engine when experimental flag enabled
- Import macroSystem and power_user for experimental macro engine integration
- Add @deprecated JSDoc tag to MacrosParser class
- Add #logDeprecated helper to warn about deprecated MacrosParser methods
- Add #registerMacroInNewEngine to bridge legacy macro registrations into new engine
- Add #unregisterMacroInNewEngine to bridge legacy macro unregistrations
- Log deprecation warnings in get, has, register
* Fix lint in tests
* Add comprehensive bracket handling tests and improve macro lexer/parser resilience to invalid syntax
- Add logMacroGeneralError function for non-macro-specific error logging
- Add CST validation check in MacroEngine to return original input if parser produces invalid CST
- Wrap MacroCstWalker.evaluateDocument in try-catch to gracefully handle evaluation failures
- Update MacroLexer Unknown token pattern to capture single closing braces not followed by another closing brace
- Add fallback mode exit
* Add error recovery for incomplete macros by flattening them to plaintext while preserving nested complete macros
- Enable Chevrotain error recovery in MacroParser constructor
- Add #isRecoveryToken helper to detect tokens inserted during error recovery
- Add #flattenIncompleteMacro to recursively convert incomplete macro nodes into plaintext items
- Update #collectDocumentItems to detect recovery-inserted Macro.End tokens and flatten incomplete macros
- Simplify plaintext token collection to use
* Add e2e test verifying nested macros resolve even when outer macro has invalid argument count
* Remove unused macro CST node caching mechanism from MacroCstWalker
* Add JSDoc type re-exports and register shorthand to macro-system.js for improved DX
- Re-export commonly used JSDoc types from MacroRegistry and MacroEnv modules for easier consumption by external code
- Add macros.register shorthand function bound to MacroRegistry.registerMacro for convenient macro registration
- Includes MacroDefinitionOptions, MacroHandler, MacroEnv, and related type definitions
* Migrate legacy macro registrations to new macro system API across multiple modules
- Replace MacrosParser.registerMacro calls with macros.register using object-based configuration
- Update imports from './macros.js' to './macros/macro-system.js'
- Extract macro registration into dedicated registerAuthorsNoteMacros function in authors-note.js
- Add descriptions to all macro registrations for better documentation
- Update MacrosParser iterator to yield from new registry when experimental engine is enabled
* Add MacroCategory to all macro registrations across codebase for improved organization and discoverability
- Import MacroCategory from macro-system.js in authors-note.js, memory/index.js, stable-diffusion/index.js, and macros.js
- Add category property to all macro registrations using appropriate MacroCategory values
- Assign 'legacy' category to MacrosParser auto-registered macros
- Categorize macros across chat, character, prompts, utility, random, state, time, and names categories
* fix lint
* Add MacroBrowser UI component and integrate macro help system into chat interface
- Add implementation of MacroBrowser
- Add macros.css stylesheet link to index.html
- Update core-macros.js ban macro to return empty string instead of 'Empty string' description
- Add sampleValue property to positional argument definitions in MacroRegistry
- Generate default sampleValue for numeric requiredArgs using 'arg{n}' pattern
- Set default description to '<no description>' and returns to '<empty string>' when empty
* Reorder JSDoc typedef declarations in MacroRegistry.js to have the most relevant first
* fix missing category in legacy initMacros
* Add displayOverride and exampleUsage properties to macro registration system
- Add displayOverride property to MacroDefinitionOptions for custom signature display
- Add exampleUsage property to MacroDefinitionOptions for documentation examples
- Update MacroRegistry.registerMacro to validate and process displayOverride and exampleUsage
- Add logMacroRegisterWarning function to MacroDiagnostics for registration-time warnings
- Auto-wrap displayOverride and exampleUsage in curly braces if missing
* Add error handling to MacroRegistry.registerMacro and logMacroRegisterError diagnostic function
- Add logMacroRegisterError function to MacroDiagnostics for registration failures
- Wrap MacroRegistry.registerMacro body in try-catch to handle registration errors gracefully
- Change registerMacro return type from MacroDefinition to MacroDefinition|null
- Log registration errors and return null instead of throwing, preventing macro registration failures from breaking the application
* Optimize character card field access with lazy evaluation to improve macro execution performance
* Add brace unescaping to MacroEngine post-processing to support literal curly braces in macro output
- Add regex replacement to unescape \{ and \} to { and } after macro execution
- Allows users to output literal braces by escaping them with backslashes
- Escaped sequences like \{\{ don't match MacroStart pattern and pass through as plain text
* Add alias system to macro registry with UI support for displaying and navigating macro aliases
- Add `aliases` property to MacroDefinitionOptions for defining alternative macro names
- Add `aliasOf` and `aliasVisible` properties to MacroDefinition to track alias relationships
- Update MacroRegistry.registerMacro to create alias entries pointing to primary definitions
- Add `getPrimaryMacro` method to retrieve primary definition from alias names
- Add filtering options to `getAllMacros` to exclude aliases
* Strip curly braces from MacroBrowser search query to match macro name format in search definitions
* Add enhanced macro autocomplete with argument hints and context-aware suggestions
- Add comprehensive CSS styling for enhanced macro autocomplete items with flex layout
- Add argument hint banner styling with gradient background and border
- Add current argument highlighting in details panel
- Export formatMacroSignature, createSourceIndicator, createAliasIndicator, and createTypeBadge from MacroBrowser for reuse
* Fix macro autocomplete not showing details/arguments because of trailing colons
* Change macro details CSS selectors from `.macroBrowser` to `.macro-details` for better reusability and update autocomplete to use macro enum icon
- Replace all `.macroBrowser` selectors with `.macro-details` in macros.css to allow macro details panel styling to work outside MacroBrowser context
- Change autocomplete option icon from hardcoded '{}' to `enumIcons.macro` for consistency
- Remove redundant `showCategory: false` option from renderMacroDetails call in autocomplete (now handled by default
* Add MacroArgType enum to replace string literal type union for macro argument types
- Add MacroArgType enum with STRING, INTEGER, NUMBER, and BOOLEAN values
- Replace MacroArgType typedef string literal union with enum reference
- Export MacroArgType from macro-system.js alongside MacroCategory
- Remove MacroArgType typedef re-export (now an enum, not a type)
* Add support for multiple argument types in macro definitions
- Update createTypeBadge to handle both single type and array of types, displaying as "type1 | type2" with tooltip
- Add JSDoc comments to MacroArgType enum values explaining each type
- Update MacroArgDefinition typedef to allow type property to be single MacroArgType or array
- Update MacroRegistry.registerMacro to validate array of types and default empty arrays to 'string'
- Update validateArgTypes to check if argument value matches
* Add returnType property to macro definitions with automatic type badge display in macro details panel
- Rename MacroArgType enum to MacroValueType to reflect dual use for arguments and return types
- Add returnType property to MacroDefinitionOptions (defaults to MacroValueType.STRING)
- Add returnType validation in MacroRegistry.registerMacro to ensure valid type values
- Update renderMacroDetails to always show Returns section with type badge
- Add macro-returns-content CSS class with flex layout for type
* Add detailed argument definitions, return types, and example usage to all variable macros
- Replace numeric requiredArgs with detailed argument definition objects including name, type, and description
- Add returnType property to all macros that return values (inc/dec/get variants)
- Add returns property descriptions to all macros
- Add exampleUsage arrays demonstrating typical usage patterns for each macro
- Apply changes consistently
* Add returns descriptions and return types to core macro definitions with improved documentation
* Add returns descriptions, display overrides, and example usage to time macros with improved documentation
* fix lint
* Add returns descriptions and return types to chat, environment, instruct, and state macros with improved documentation
* Add missing properties to dynamic macro definition override to match MacroDefinitionOptions structure
* Replace console logging with MacroDiagnostics logging in MacroEnvBuilder and MacroRegistry
* Add support for array-based argument types in macro autocomplete with union type display and tooltip
* Rename requiredArgs to unnamedArgs and add support for optional unnamed arguments with bracket notation in macro signatures and hints
* Add optional offset argument definition to time macro with type, sample value, and description
* Simplify example usage for random and pick macros by removing surrounding context text
* Add default value display for optional macro arguments in autocomplete and browser documentation
* Fix macro args defaultValue not being converted into the normalized values for register and display
* Allow STscript macro auto completion to still show up when typing closing braces
* Add space macro with optional count argument for inserting multiple spaces
* Add optional count argument to newline macro for inserting multiple newlines with default value of 1
* Remove MutationObserver and CTRL+F keyboard event handling from MacroBrowser
* fix lint
* Register `{{summary}}` macro for both old and new macro engines based on experimental flag
* Register `{{charPrefix}}` and `{{charNegativePrefix}}` macros for both old and new macro engines based on experimental flag
* Update hidden alias badge text to indicate deprecation status
* Simplify macro name validation and error handling in MacroRegistry
Remove redundant `macroName` variable by normalizing `name` parameter early and reusing it throughout the registration flow. Consolidate trim checks in validation condition.
* Remove exp macro engine flag checks from auto complete and help, and remove legacy macro template
Move macro registration to always use new engine regardless of experimental flag. Remove conditional logic for `experimental_macro_engine` in MacroBrowser, system messages, and slash command parser. Delete legacy `macros.html` template and associated static macro help generation. Always use MacroBrowser for macro documentation display.
* Rename macros to camelCase and add backward-compatible aliases
Rename `description`, `personality`, `scenario`, `creatorNotes` to `charDescription`, `charPersonality`, `charScenario`, `charCreatorNotes` respectively. Rename `idle_duration` to `idleDuration`. Add old names as aliases for backward compatibility. Add `comment` as visible alias for `//` macro. Mark `idle_duration` alias as hidden.
* fix `random` and `pick` macros by using list parameter directly instead of raw string
Remove `raw` parameter from `random` and `pick` macro handlers. Simplify legacy comma-separated list handling by using `list[0]` directly instead of `rawListString`. Rename `items` variable to `list` in `pick` macro for consistency.
* fix `random` and `pick` not handling all colon-separated lists as before
Extract `readSingleArgsRandomList` helper function to handle legacy comma-separated and double-colon list parsing. Reuse this helper in both `random` and `pick` macro handlers to eliminate duplicated list parsing logic.
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
Co-authored-by: bmen25124 <bmen25124@gmail.com>
* Separate prompt-building functionality from request-sending functionality
* removing logs and clarifying comments
* separating parameter construction functionality to allow ConnectionManagerRequestService to use all other preset parameters
* fixing chat completion issues, adding documentation to new functions.
* Improving ConnectionManagerRequestService errors. Adding parseReasoningFromString option to override reasoning template.
* Adjusting TextCompletionService prompt formatting
* linting
* Use settingsToUpdate to convert from OAI preset to OAI settings.
* lint
* throw errors when profile ID not found
* Fix missed instances of global completion settings being used (CC and TC), replaced with optional argument. Specified typing for ChatCompletionSettings and TextCompletionSettings.
* Adjusting parameters of parseReasoningFromString and adding getReasoningTemplateByName
* using messages.role as a fallback for custom requests, fixing newline removal.
* parameters => settings
I like how it sounds better
* ditto
* You know I had to do it to 'em
* Update getCustomTokenBans
* Fix calculateLogitBias
* Fix param attributes
* Fix type checks
* Less strict role type on ChatCompletionMessage
* Add missing space
* fixing getChatCompletionModel to use an arbitrary chat completion settings object
* Fixing issues with preset overriding custom data passed.
* Pass model to createGenerationParameters externally
* Unify seed param handling for CHUTES
* Fix non-existing CC source
* Use strict comparison
* Use global settings as a base for generation parameters creation
* removing unnecessary handling of preset fields
* don't pass preset prompts, use the passed payload override messages
* refactoring text generation prompt building of last line
* Pass model to getReasoningEffort
* Pass model name to canPerformToolCalls
* Pass model to createTextGenGenerationData
---------
Co-authored-by: qvink <qvink@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Feat: Add toggle to exclude think/reason blocks from smooth streaming
* Fix: Adjust new setting name to properly reflect what it does
* Sync data-i18n with text content
* Add reasoning stream flags for Mistral, Claude and Google models
* Update layout
* Fix: Enhance reasoning handling in parseStreamData function
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Added a mock OpenAI-compatible endpoint at /v1/chat/completions.
Disabled by default.
Intended for debugging and e2e tests.
* Fixed empty prompts.
* Add mock server and example test
* Improve test
* Added `eslint-plugin-playwright`
* Removed `Date.now()` for reproducible responses.
* Ignore ERR_SERVER_NOT_RUNNING on close.
* Use MockServer in mock-openai.js
* Fixed error check.
* Removed mock server.
* Fix test name
---------
Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Send toolConfig block to Gemini, if defined and tools block also present.
* Convert OAI tool_choice to Gemini functionCallingConfig for Gemini requests
* Remove blank line
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* feat: Extract and store CharX embedded assets on import
Enhances CharX (.charx) file import to extract and store embedded assets
in accessible locations:
- Add CharXParser class in new src/charx.js module
- Extract sprites (emotion/expression) → characters/{name}/
- Extract backgrounds → backgrounds/{name}_{asset}.{ext}
- Extract misc/x-risu-asset → user/images/{name}/
- Skip user_icon assets to prevent persona conflicts
- Support SFX (self-extracting) ZIP archives
- Add extractFilesFromZipBuffer() for efficient multi-file extraction
- Add normalizeZipEntryPath() for safe path handling
- Use hyphens in sprite names for ST expression label compatibility
- Fix ArrayBuffer slicing for Node.js buffer pool issue
Tested with 34 real-world RisuAI exports (200-300MB, 1000+ assets each).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: Address review feedback for CharX parser
- Add normalizeExtString() to handle dotted/uppercase extensions
(e.g., '.PNG' or 'PNG' now correctly becomes 'png')
- Revert default avatar to path string instead of eager fs.readFileSync
- Simplify getCharXAssetBaseName regex, remove dead useHyphens branch
- Add JSDoc for persistCharXAssets documenting sync write behavior
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor: Move ensureDirectory to util.js for reuse
- Extract ensureDirectory() from charx.js to util.js as a shared helper
- Add JSDoc for getUniqueAssetPath explaining sprite naming convention
- Prepares utilities for future ZIP-based format imports (similar to BYAF)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: CharX asset overwrite and folder naming
- Overwrite existing assets on re-import instead of creating duplicates
(matches sprites.js upload behavior with deleteExistingByBaseName)
- Use character name for asset folders, not unique filename
(ST's sprite system looks up by character name from card data)
- Strip trailing extensions from asset names to avoid file.ext.ext
- Add per-file error handling so one bad asset doesn't abort import
- Remove redundant else branch in storage category assignment
- Add comment explaining intentional 'embeded://' typo (RisuAI compat)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: Address PR review feedback
- Filter out directories in deleteExistingByBaseName (Cohee1207)
- Use ISO timestamp for create_date instead of humanizedDateTime
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* fix: Store CharX backgrounds in character-specific folder
Changed background storage from global `backgrounds/` to character-specific
`characters/{charName}/backgrounds/` per maintainer feedback.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
* Remove unused import
* fix: Reduce CharX debug logging noise
Remove verbose per-file debug logs that create excessive console noise
for large archives. Keep only essential logging matching BYAF style:
- Entry point info log
- Final summary of imported assets
- Warnings for actual failures
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Chat Completion: Reduce number of toggles in AI Response Configuration
* Consolidate migration logic
* Don't enable media inlining if image inlining was disabled
* Fix icons showing on media toggle off
* Update i18n
* Unify chat timestamps format
* Handle ISO timestamps in stats.js
* Refactor timestamp parsing on server
* Switch to ISO timestamps for character/messages creation dates
* Fix type error
* Early exist in saveGroupChat if group not found
* Remove redundant fields from temp.chat export header
* Auto-fix char creation date format on edit
* Add name to fallback chat file names
* Rename parseTimestamp server side function
* Migrate group metadata to group chat files
* Skip migration if chat already has metadata
* Fix active group not being set on group conversion
* Improve types in createGroup
* Fix padding in hotswap group avatars
* Fix centering of empty hotswap avatar
* Added automatic backups of migrated data
* Fix 'OVERWRITE' for GC
* Fix metadata parsing order in migration
* Remove color accents from regular migration logs
* Always set gen_id in converted message
* Clone messages before conversion
* Reduce size of add/remove buttons
* Fix group chat file size calculation
* Fix resetting the context size when switching between CC sources that load the models list dynamically
* Revert the requirement to have models list for XAI
* Revert for sources that don't load context size from endpoint
* 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)
* Update - Revert connection profile change TC commands load order
This change was made to prevent preset tied samplers from breaking, such thing doesn't exist anymore.
* Update - Unlink preset renaming logic from sampler selection lock
* Update - Link TC sampler selection lock to API Type
* Fix - Clean comments
* Update - Use localforage selectedSamplers and data selectsampler as main sampler selection storage
* Fix - ESLint errors
* Update - Change lock tooltip with correct description
* Fix - Move and await sampler select localforage initializer to finish
Tried to move it to the most reasonable place possible that allowed to make an await.
* Fix - Make loadTextGenSettings async to load API selected samplers
* Feat - Save and load manually selected samplers per preset
* Fix - Sync sampler popup with selected sampler state settings
* Fix - Prevent breaking visualization after disabling keep selected samplers
* Fix - ESLint errors in samplerSelect.js
* Fix - ESLint errors in textgen-settings.js
* Docs - Write JSDocs for new methods in textgen-settings.js
* Update - Make the reset button work individually per preset
* Fix - Trailing whitespace at the end of class selector
* Fix - Update tooltip information for force samplers toggle
* Fix - Prevent calling isSamplerManualPriorityEnabled a bajillion times
* Fix - Unbrick switch from manually-forced to non-manually-forced preset
This prevents samplers non controlled by [data-tg-type] from being sent to the shadow realm if they were previously hidden by [data-tg-samplers]. is_preset_switch is just to prevent breaking muscle memmory of users not using force manually selected samplers.
* Fix - Load manually selected samplers on connection profile switch
Changing preset does not update samplers ONLY IF force manually selection is disabled. Changing API before preset would update the samplers, but using the settings of the previous preset, due to preset being changed AFTER the API.
* Fix - Switch API Type controls in the API Connections panel
* Fix - ESLint errors in textgen-settings.js
* Fix - Update sampler selection only with textgenerationwebui as main API selected
* Styles - Change the sampler selection lock button icon to an actual lock.
* Fix - Await for sampler selection reset to finish
* Update - Normalize function name
* Update - Preserve manual sampler selections on preset renaming
* Fix - Properly reset sampler manual selections
* Update - Ensure selection reset displays API specific samplers
* Fix - ESLint errors
* Fix - Avoid modifying non-existent data
* Update - Move manual sampler control methods to samplerSelect.js
* Fix - Break circular file dependency between textgen-settings.js and samplerSelect.js
setting_names was unavailable during page load, throwing an error and preventing ST from loading.
* Update menu layout
* Remove pointless await
* Update param naming to camelCase
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Preserve media playback state when running appendMediaToMessage
* Better selector specificity
* Fix local variable name
* Move typedef to global.d.ts
* Check for readyState on save/restore
* Only check for currentSrc on restoration callback
- 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
* 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
* 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
* Add captioning for video attachments
* Unify error toast titles
* Add MEDIA_SOURCE enum and update media handling to include source information
* Unify attachment handling logic
* Add error handling for auto-captioning failures
* Use string formatting for console error
* TC: Allow setting empty JSON schema
* Fix check for llamacpp schema
* Handle grammar/schema for Aphrodite
* Conditional include for guided_json
* Update default presets with null value
* Conditional include into payload for grammar/schema
* Refactor flattenSchema to simplify JSON schema for Google Generative AI API compatibility
* Added unit test and github action
* Add unit tests workflow and update test script in package.json
* Downgrade eslint-plugin-jest to make min node version 18
* Add audio-player component
* Enhance audio player functionality and styles
- Adjust audio player layout and styles in CSS for better spacing and alignment.
- Add audio element to message template in HTML.
- Implement audio attachment handling in JavaScript, including a new AudioPlayer class.
- Update media attachment structure to include titles for audio files.
- Extend supported media file types in constants.
* Add audio inlining control
* Fix file formats list
* Simplify hints
* Add to prompt
* Add progress title hint
* Add to scrollOnMediaLoad
* Add audio size hint
* Add gallery controls
* Delete removed media attachments from server
* Adjust min width
* No-op when swiping a singular media
* Fix clean-up
* Fix silent deletion logic
* More accurate media prompt estimations
* Round durations with ceiling function
* Adjust rounding logic
* you don't have to say it twice
* Export deleteFileFromServer
* Don't reference module from HTML
* Clean-up styles
* Move formatTime to utils
* Add fa-fw to delete
* fix(IME): Prevent Esc from closing editor during composition
When using a Chinese IME, pressing the Escape key during composition should cancel the composition, not close the message editor.
This commit fixes the issue by adding a check for `!e.isComposing` to the 'keyup' event listener for the Escape key in `public/script.js`. This ensures that the editor is only closed when the Escape key is pressed outside of an IME composition session.
* fix(IME): Change the handler of 'Escape' from 'keyup' to 'keydown'
---------
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
* Support multiple images in single API response
* Fix media wrapper clashing with swipe counter
* Return an empty array, add additional filtering
* Add index to inline image filenames in processImageAttachment
* Multiple file uploads
* mes_img_wrapper
* mes_video_wrapper
* Named export instead of function wrapper
* Update public/scripts/chats.js
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
* Fix optional chaining for message extra
* Preserve existing files with paste
* Improve swipe message extras clean-up
* Clean-up: Add chat_backgrounds to known images
* Add ensureMessageMediaIsArray to getContext
* Fix compatibility warning
* Update to media array
* Move de-dupe check logic
* Fix comment
* Fix clean-up logic
* Improve typing
* `feat/multi-file` Added a toggle between the old gallery and new image list. (#4722)
* Added "Toggle Gallery" button.
Added `getContainerInfo`.
* Refactor
* Change checkbox toggle to select
* Ensure media_display is set correctly only if any image_swipes were migrated
* Rename function
* Support Date in parseTimestamp
* Add type to main chat array
* Add media display reload prompt
---------
Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Use a single wrapper block for media
* Fix type annotation
* Fix video display in list mode
* Refactor saveImageToMessage to include title in media object
* Use named constants in migrateMediaToArray
* Update img control styles
* Fix error container state
* Refactor onImageSwiped
* Remove redundant event handler
* Refactor expandMessageMedia
* Use shared function for display handling, fix notice logic
* Enhance ChatMessage and ChatMessageExtra types
* Refactor media display reload logic
* Improve styling for media containers
* Adjust spacing in file form styles
* Fix scroll handling in appendMediaToMessage
* Reduce flicker in appendMediaToMessage
* Extract scrollOnMediaLoad func
* Improve scroll behavior in gallery display
* Improve delegation for click events
* Add file d&d handler to #form_sheld
* Improve scroll adjust for slow connections
* Adjust debounce timeout
* Add messageMedia enum provider
---------
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: DeclineThyself <FallenHaze@tutamail.com>
Co-authored-by: user <user@exmaple.com>
* - Removed unneccessary check for swipe info. Swipes are valid and can be read by the chat message UI just fine without the dates and details surrounding generation settings.
* + Swipe info will now be backfilled if it's missing using placeholder data, to improve compatibility.
* + Fix big oopsie.
* + Fix discarding all scenarios aside from the first one, which would cause all chats other than the first one to be lost.
+ Accumulate alternative starting messages from all scenarios, as different scenarios are how Backyard handles having alternative greetings. A scenario with multiple messages in its "firstMessages" array is invalid as per BYAF spec.
+ Return scenarios so that they can be used to populate chats, scenario overrides, and in the future, the other character settings overrides as well.
* + Added support for importing chats (including swipes) from BYAF. This brings the core functionality of BYAF imports mostly in-line with the standard, without the inclusion of any features that are currently missing from ST.
> The only supported feature not yet implemented is scenario overrides per-chat. This will be the the goal of the next commit.
* + Implemented scenario overrides, fully bringing ST's BYAF import as in-line with the BYAF standard as possible without adding new feature functionality to ST.
+ Also added some new chat metadata fields in preparation for example message and system prompt overrides.
* + Added support for pulling alternate icons from the BYAF archive. They are not used yet, but they are safely stored.
+ Added support for pulling backgrounds from the BYAF archive. They are not used yet but they are stored and linked to the chats they originally belonged to.
+ Saved every remaining field that was previously discarded from BYAF that a user actually needs in a way that could be used in the future, and can be accessed by the user if needed after import. Any fields that are not preserved at this point are specfic to either Backyard AI's desktop application, or to the BYAF manifest itself, and therefore have no relevance to a user.
> With this, BYAF import should be fully supported and in-line with the official spec.
* + Updated comments and method names to reflect changes appropriately. First round of touch ups.
* + More comment updates.
* - Removed commented code, that is no longer needed for reference.
* > No longer sanitize for filenames in the character card, as there's no need. The sanitization now happens when generating the filename, which is subsequently used for file operations.
+ Added replacement function for sanitizing filenames which uses visually similar but valid for filenames replacement characters instead of deleting the characters for better data parity.
* + Preserve isNSFW flag as a tag, so it's not lost on import.
* + preserve labels on character alt avatars
* + Deduplicate first messages, so that 5 chats with the same first message don't create 5 identical first messages.
* + Adjusted icon naming logic to produce more sensible results.
* > User path.basename and path.extname for getting the base name and extension of files, respectively.
* > Should use camelCase for local function names.
* > Use a set for greetings instead of explicitly checking for duplicates.
* > Missed a snake case local function name.
* > Updated background import logic to integrate with existing per-chat background system.
* + Updated logic to skip import of chats and backgrounds when a character is being updated/replaced.
* + Added copy of getUniqueName helper function from frontend utils to backend utils.
+ Refactored duplicated logic for getting unique filenames for backgrounds and character alt icons to use the newly available function.
* > fixed adding an extra dot to the filenames for icons after switching to path.extname for getting the extension
* > Updated metadata settings generation in byaf chat so that it doesn't overwrite valid yet 'falsy' values with defaults. Oops
* > Remove variable for configuration that will likely never need to exist.
* > custom_background should be an empty string if chat_background is falsy
* > Make an array empty if chat_background is falsy.
* > Prefer camelCase for local variable names.
* + Added definitions for ByafParseResult and ByafChatBackground.
> Updated overused and unweildy anonymous types to the newly defined types.
* + When importing a character with chats, the character will now no longer open to a new empty chat, but instead will pick the first of the imported chats to open up to.
* Rename prev_paths => paths
* Prettify logs display
* Set fallback chat name if scenario is untitled
* card.data.name => card.name
* Optimize first scenario message access
* + Moved custom replacement function from importFromByaf into util.js as sanitizeSafeCharacterReplacements() so that the replacement logic may be reused anywhere for consistency.
* > Missed a couple. Updated for consistency
* + Preserve character full/display name without it needing to be safe as a filename.
> Change logic for naming the folder the alt images live in to match the logic the sprites endpoint uses to get character sprites for consistency
* > Only add full_name extension if displayName exists.
* full_name => display_name
* - No longer use safe lookalike replacements for filename sanitization to be consistent with how web browsers sanitize invalid characters in filenames before saving to disk.
* Tiny formatting fix
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* + Implemented support for overrides of system prompt and example messages from chat metadata. This is needed for BYAF import parity. No UI for modifying these yet, but they're easily changeable in the chat files already. These metadata settings are already supported by BYAF import as of the last commit so this just enables them.
* + Updated scenario overrides popup to now be a character settings overrides popup.
+ Updated the template to have a new section for example messages and system prompts
+ Updated the logic to handle all three overrides
+ Updated logic to only save when the popup is closed, instead of on every character input.
* Preserve import, allow scrolling
* Add confirmation on override removal. Always save pending changes.
* Update dialog layout, add editor expand buttons
* Fix mes examples override in group chats with Join mode
* Update group chat button title
* Specify that Prefer Char. Prompt is a requirement
* Fix group join mode not replacing macros in overrides
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Enhance contribution guidelines for pull requests
Added guidelines for maintaining workflow during PRs.
* fix abort generation error when koboldcpp is set with a password
* add parameter type, and remove unecessary line
* oops, missing comma
* eslint
* remove header content type
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
Co-authored-by: Your Name <you@example.com>
* Add UI elements
* Add support for model configuration
* fix: update API request parameters for improved handling
* Add logo img
* Fix tool calling with negative index
* Include tool calls into 'last in context' calculation
* feat: add support for captioning
* Refactor message edit, show counters on last message
* fix: add warnings for missing message in chat array and DOM during edit
* Export messageEdit function
* Formatting fix
* Fix comment alignment
* feat: apply preset regexes before scoped regexes
* feat: apply preset regexes before scoped regexes for debugger list
* fix: don't notify reload regexes when save preset through ui button
* docs: add comment for SCRIPT_TYPES order
* fix: updatePreset is wrongly reset preset
* Fix off-by-one cases in user prompt filler logic
Fixes#4645
* Skip inject pre-allocation in CC prompts
* Fix filler insert on continuing on user message
* feat: preset regex
* refactor: unify `saveScriptsByType`
* fix: default branch for `saveScriptsByType`
* refactor: resolve some reviews
* fix: lint
* refactor: getPresetName -> getCurrentPresetName
* refactor: unify regex allow operation
* feat: notify whether to reload current chat when preset is changed
* refacotr: set timeout for reload current chat notification
* fix: _ -> lodash
* i18n
* Refactor API ID access
* refactor: replace UNKNOWN type with a separate constant
* refactor: consolidate CSS rules for scoped and preset script blocks
* Extend toast timeout
* Fix bug with moving, refactor
* Refactor bulk toggle operations
* Use for..of for preset application
* refactor: enhance parameter documentation for scriptType in regex functions
* fix: await loadRegexScripts in event handlers
* fix: correct script type in saveScriptsByType for preset handling
* fix: add null checks for preset manager and API ID in regex functions
* feat: implement expandable regex script options in UI
* Always show edit/delete buttons
* Add title attribute to regex script name
* fix: correct class name for regex script display
* Remove extra paddings from script blocks
* fix: ensure preset scripts are only disallowed if currently allowed during rename
* fix: reload on bulk script toggle
* feat: add PRESET_RENAMED_BEFORE event type and emit it during preset renaming
* fix: always preserve preset extensions on rename
* Handle horde in getPresetManager
---------
Co-authored-by: ZoinkCN <zoinkcn@outlook.com>
Co-authored-by: StageDog <aksanajw845@gmail.com>
* feat: prevent scrolling of containers when using focused number inputs
#4607
* feat: enhance number input wheel behavior with slider sync and Firefox support
* refactor: optimize number input wheel handler with native DOM methods and type checks
* Refactor: Move into dom-handlers folder
* refactor: use optional chaining for slider element selection
* Simplify file paths
* Unlock scroll to edit in misc controls
* refactor: throttle wheel event handler updates
* refactor: Extract value update into a function
* fix: NaN-aware value clamping
* fix: Add sanity checks for input value calculations
---------
Co-authored-by: Wolfsblvt <wolfsblvt@gmail.com>
* Remove dead Gemini 1.5 models, and clean up
* Remove dead models (error 404): Gemini 1.5, `gemini-2.5-pro-exp-03-25`, `gemini-2.5-flash-preview-04-17`
* Adjust the Gemini → descriptions
* Assign default models to 2.5 Pro and Sonnet 4.5 (3.5 and 3.7 will be retiring soon)
* Add `gemini-2.5-flash-image`
* Don't forget learnlm-1.5-pro
* Update default claude
* Vertex: Clean-up 2.5 preview models
* Disable thinking for 2.5-flash-image
* Bring back banana preview
* Update defaults in more places
* Add gemini preview-09-2025 and robotics-er
* unbrick my last commit
* Add gemini-robotics-er to captions
* Set max context for gemini-robotics-er
dang
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Add interactable outline color CSS variables
Introduces --interactable-outline-color and --interactable-outline-color-faint variables to the body style, both set to transparent for future use in styling interactive elements.
* Update global styles and remove unused CSS variables
Added -webkit-tap-highlight-color to the universal selector for improved touch experience.
* Add confirmation for bulk move, add UNKNOWN type, improve JSDoc
* Fix toggle all bulk move visibility
* Improve function documentation
* Refactor currentChatId check and improve JSDoc for getScriptDecorators function
* Check against known values in moveRegexScript
* Fix console warning spam
* Simplify currentChatId check
* Prevent moving scripts into the void
* Make texts translatable
* Update contribution guidelines
* fix: language in CONTRIBUTING.md
* Updated language to clarify the role of maintainers in PR reviews.
* Update section title for AI coding assistance tools
* Update CONTRIBUTING.md
* 200
* 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()
- Fixes visual inconsistency between 'Enter a Model ID' input and 'Available Models' dropdown
- Uses calc(var(--mainFontSize) * 0.95) to match the slightly smaller font size of the dropdown
- Resolves issue #4599
This is the most minimal fix that targets only the specific element causing the visual difference.
Co-authored-by: Trahloc <trahloc@hearth.trahloc.com>
* 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>
* 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>
* 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>
* 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)
* feat: enable character source dropdown based on availability and style disabled options
* feat: emit event when character is in right character panel
* refactor: rename CHARACTER_SELECT_SELECTED event to CHARACTER_EDITOR_OPENED for clarity
* Always disable source option when peeking in groups
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
Refer to line 5771, where is correct, but the branch is not added, resulting in the branch being triggered once here when the streaming is completed, and finally the streaming is triggered again. In fact, it should not be triggered here
* refactor: allow popup okButton and cancelButton to be set to false to hide them, even if visible by default
* feat: add character replacement from online source URL
- add utility function to import anything from external URL (refactored from existing function)
- fix character replace toast showing "Created"
- fix thumbnails not refreshing for replaced char
- fix accidentally creating new chat on replace, instead of reloading the open chat
* fix: refresh avatar thumbnail only after successful character import and when character exists
* chore: fix lint, unused import
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* feat: Add {{notChar}} macro for participant list
* implement impersonation logic consistently.
* docs: Document the new {{notChar}} macro
* docs: Fix format for {{notChar}} and remove examples.
* docs: Add span tag
* docs: fix extra quote mark
* docs: Add suggested fixes
* fix: change MiniMax TTS pitch from float range 0.5-2.0 to integer range -12 to 12
Fixes#4570
* refactor: replace hardcoded defaults with defaultSettings in MiniMaxTtsProvider config
* refactor: restructure TTS settings with min/max ranges and add value clamping, adjust volume range
* fix: flatten MiniMaxTtsProvider settings to use default values from complex field definitions
* Adjust block spacing
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* [wip] Add stream fade-in effect for message text and corresponding CSS animation
* Avoid using temporary element during text segmentation
* Add fade in toggle
* Skip whitespace-only nodes
* Fade-in reasoning stream
* Fix case when segmenter is not supported
* add first and last buttons to pagination
* Add i18n support
* Update pagination buttons font
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* init
* cleanup
* logic changes and some styling
* set z index to a reasonable value
* remove pointless animation
* cleanup
* restore animation
* checkmark icon on selected background
* drop shadow
* tweak size slightly
* Apply suggestion from @Cohee1207
condense
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* more of the above
* make lock indicator use a class like the selection indicator
* make backgroundHighlight run on page load
* cleanup
* html restructure and display: contents. only issue left is slightly wonky desktop buttons order
* yellow lock icon for consistancy
* Update layout
* Restore fitting logic
* Styles clean-up
* Remove duplicate class
* Restore button titles
* Fix return types of slash commands
* Update locked background on select if lock status is on
* Force header to 100% width
* Clean-up styles
* Fix locked highlight on custom backgrounds
* Revert global lock button
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* feat: update creator notes display when editing character and updating content
* Fix interaction with create form
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* feat: add outlet prompt support for world info entries
* feat: add outlet name field with autocomplete for world info entries
* feat: add outlet entries for world info support to WI parsing
* feat: add tooltip and validation for WI outlet name entries
* Trim macro outlet name
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* refactor: consolidate WI injection cleanup and fix strict equality comparison
* fix: update outlet macro regex pattern to use double colon delimiter
* fix: replace carriage returns with newlines in WI entry outlet tooltip
* fix: add null checks and array validation for WI outlet entries handling
* feat: add outletName field to world info entry definition schema (supports /setwientryfield command)
* fix: add outletName field to export of character lore books
* do not remove outlet name on position change, but filter out for auto complete
* Match WI extensions field name
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* outlet name being used in char WI import too
* docs: add outlet macro documentation to help template
* be explicit about risu/novel/agnai wi not supporting outlets
* Inject A/N and TC sysprompt after populating outlets
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* init
* mostly working messy version
* css layout, mobile is fixed
* revert changes
* more of the above
* cleanup
* revert breaking fixes, cleanup dead code
* dead code
* delete fallback
* spacing
* css tweaks and removed getChatBackgroundsList
* mobile sizing
* revert unrelated changes
* use name instead of context
* debounce from constants.js
* replace if/else
* pass images directly
* more of the above
* buttons
* buttons functionality
* add default column counts
* remove .mobile-only-menu-toggle when clicked (layering fix)
* lint
* universal column default of 3
* sacrifice firefox for chrome
* Restore media query
This reverts commit 295a5a8190.
* Add disabled attribute styles for menu_button
* use opacity 0, pointer events none instead of display:none
* Format styles
* Fix type errors
* Add blur event handler to close mobile menu when focus is lost
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Add Thai Translation
* Remove yarn.lock and add to .gitignore
* Update Thai translation
* Update Thai translation for World Info entry status descriptions
* fixed thai translation
* feat: Add Azure OpenAI chat completions provider
This commit introduces comprehensive support for integrating Azure OpenAI as a new chat completion source within SillyTavern. The implementation specifically navigates Azure's reliance on deployment names, differing from standard model selection.
Includes:
- **New Feat / UI:** Dedicated settings in `public/index.html` for Azure parameters (Base URL, Deployment Name, API Version, API Key) and a new `public/img/azure_openai.svg` icon.
- **Frontend Logic (`public/scripts/openai.js`):** Manages Azure OpenAI settings and dynamic URL generation. The 'Connect' button triggers a `GET /models` endpoint call solely for API configuration validation (key, URL, version). Upon successful validation, a subsequent `POST` request is made to the AI, and the active model is extracted from its response payload, then populated for UI display (no direct user model selection).
- **Backend Logic (`src/endpoints/backends/chat-completions.js`):** Implements `sendAzureOpenAIRequest` to proxy requests, handling Azure’s unique authentication and URL structures. Enhanced the `/status` endpoint for Azure-specific validation.
- **Secret Management:** Secure handling of Azure OpenAI API keys in `public/scripts/secrets.js` and `src/endpoints/secrets.js`.
- **Autoconnect:** `public/scripts/RossAscends-mods.js` modified to enable automatic connection for Azure OpenAI if an API key is present.
Impact:
- Users can now connect to and utilize Azure OpenAI services.
- Requires new configuration details in the UI.
- Enhances API routing and validation with Azure-specific behavior.
- Navigates model handling: model name is *derived dynamically* from AI response, not directly selected, aligning with internal SillyTavern structure.
* fixed the html issues, openai.ujs and secrets.js
modified: public/index.html#
modified: public/scripts/openai.js
modified: public/scripts/secrets.js
* Extends Azure OpenAI with advanced capabilities
Enables advanced features such as function calling, image inlining, and model reasoning in the UI for Azure OpenAI.
Refactors the backend to support structured output (JSON mode), native thinking, and reasoning effort for compatible Azure OpenAI models. Adds support for logprobs, multiple responses (`n`), and seed, aligning with standard OpenAI behavior.
Improves request handling with a retry mechanism for rate limits and more robust error reporting. Ensures correct parameter handling for model-specific features and conflicts, such as when native thinking is enabled. Optimizes the Azure OpenAI status probe for efficiency.
modified: public/index.html
modified: public/scripts/openai.js
modified: src/endpoints/backends/chat-completions.js
* PR fixes
Simplification
Removed reasoning logic from backend
modified: src/endpoints/backends/chat-completions.js
modified: src/endpoints/backends/chat-completions.js
* Fix PR comments
Removed the front end compiled url UI element and related.
Misc simplifications
modified: public/index.html
modified: public/scripts/openai.js
modified: src/endpoints/backends/chat-completions.js
* Fixed accidental api temporary disabled
modified: public/index.html
* Don't transfer status code verbatim
* Fix formatting
* Enable tool calling
* Fix logo coloration
* Move model arrays to shared constants
* Fix capitalization
* Remove obsolete comment
* Improve response schema parameter format
* Fix tokenizer model selection
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Improvement: Enhanced UI Consistency
- Added a class to `<div class="inline-drawer-toggle inline-drawer-header">` in **AI Response Configuration** and **API Connections** menus to match the styling of similar elements in **User Settings**
- Improved spacing and sizing for buttons such as `.bg_example .jg-menu` in the **Backgrounds** menu. The previous widths and gaps were too small, often causing accidental taps (especially on mobile devices)
* fix
* Adjust padding and background color in style.css
* Update inline drawer classes for configuration sections
* Remove border styles from expandable sections
* fix
* fix
* fix(sad)
* Adjust desktop bg_list width
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* fix: adjust toast container positioning in popups to match core toastr behavior
Fixes#4490
* Fix misplaced element role
* Hide toast container while opening animation is running
* fix: update toast role from alert to status
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* refactor: remove unused background styles
* feat: add support for nested @media, @supports, and @container rules in dynamic focus styles
* fix: add keyboard focus support for background menu buttons back
* fix: move "custom" background copy functionality to unified button UI and make it work again
* refactor: simplify CSSContainerRule instance check using window global
* fix: update hover and focus selector placeholder replacements to handle multiple occurrences in selector
* Fix focused outline offset of background samples
* Fix locked background outline color
* Add a11y roles to background menu items
* Add mobile-only button selector
* fix: update button and list item selectors
* Improve keyboard navigation in narrow layout
* Hide rename button for custom=true backgrounds
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Improvement: Add Upload Button to Image Gallery
- Added an **Upload Image** button to the **Image Gallery** for a more intuitive experience and easier use on mobile devices ~~(so I can upload some awesome GIFs right from my phone)~~
- Adjusted the `<select class="gallery-sort-select">` menu styling for better consistency with other sections, making it more compact and reducing wasted space
* Fix type error
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* fixed merge conflicts
* Supported max tokens + fixed wrong image model mapping
* fixed merge conflicts
* fixed merge conflicts
* updated the logic
* updated the logic
* replaced hard coded reasoning_effort mode list with a dynamic function
* replaced hard coded reasoning_effort model list with a dynamic function
* Fix eslint
* Adjust reasoning effort logic
* Code clean-up
* Add logo
* Add inline image quality
* Fix multimodal models list
* Fix seed not passed
* Add "detail" error parser
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* SSL: support passphrase for private key
* Recommend CLI argument or environment variable for key passphrase
* Fix SSL passphrase handling to ensure it is always a string
* Fix TS1038 errors
"A 'declare' modifier cannot be used in an already ambient context."
* Fix TS1040 errors
"'async' modifier cannot be used in an ambient context."
* Fix TS2371 errors
"A parameter initializer is only allowed in a function or constructor
implementation."
* Fix TS2430 errors
"Interface 'ColorPickerEvent' incorrectly extends interface
'ChangeEvent<HTMLElement, any, any, any>'".
The issue here is that the "ColorPickerEvent" objects provided by
toolcool-color-picker.js are vanilla JS CustomEvent objects, not JQuery
event objects. We need to mangle the types here a bit to make JQuery
happy. (At runtime, JQuery is happy to pass along the vanilla Event
object; JQuery's types just don't reflect this.)
* Remove variable and type exports
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* Improve tag visibility toggle logic
Cache selector once, and remove hardcoded animation duration.
Takes 300 tags down from 3 seconds down to 2ms per toggle.
* whitespace fix
* feat: Add support for CometAPI, including API key management and model selection features.
* Some code fixes
* Fix loading model from presets
* Add logo image
* Enable tool calling, reasoning effort, reasoning display, structured generation
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* feat: Send Quick Reply Before Message Generation
* fix: Use correct event and check for dry runs on before-generation
* Replace icon
* Skip for events in groups outside of group wrapper
* Compatibility with API and slash commands
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* charQR
* fix
* fix_2
* fix_3
* Fix refresh errors and Implement confirmation dialog logic
* FIX : The character's quick reply set is executed three times during the initial authorization and import.
* Enhance warning dialog content and layout
* refactor: Use local linking for Char QR sets instead of embedding
* Lint fixes
* Clean-up
* Emit CHAT_CHANGED on character deletion
* Remove isVisible filter, I'm sure it was by design
* Revert order of search in executeQuickReplyByName
* fix: Address review comments
* Add private tag to Char Sets
* Add QR rebind on renamed character
* Clean-up diff
* Don't save empty config lists
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* bug-fix: adhere to chat template hash bound settings when a new model appears using the same hash as a bound one
* chore: Improve readability
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
The problem: Auto-scroll is overly sticky. While a generated message is streaming in, it is almost impossible to cancel the auto-scroll behavior by scrolling up, it just snaps back down.
The reason is that the 'wheel' and 'touchmove' events trigger before the scroll position is updated. So the scrollIsAtBottom value never becomes false. That is, unless the user manages to scroll up quick enough to beat the call to scrollChatToBottom() in onProgressStreaming().
The 'scroll' event is better because it fires slightly later in the scroll behavior. This makes canceling auto-scroll by scrolling up much more reliable.
Making auto-scroll cancelling more reliable has the side effect that resuming auto-scroll becomes harder. To even this out, this change slightly increases the tolerance for resuming auto-scroll to 5 pixels. This is small enough to be generally unnoticeable but significantly easier to hit than the previous 1 pixel.
I tested this change in
* Firefox on Linux
* Chrome on Linux
* Firefox on Android
* Chrome on Android
In all cases, the auto-scroll behavior is greatly improved:
* While auto-scrolling, scrolling a little bit up immediately cancels the auto-scroll behavior.
* Scrolling all the way down resumes the auto-scroll behavior.
* Update UpdateAndStart.bat
* feat(client): desktop version uses select2 to search, filter, and select world info to edit
feat(client): styles for select2 to separate items and highlight
* fix(client): more aligned with current select2
fix(client): removed unecessary functions and styles
* Update WI editor layout
* Add min-width for WI sort and search
* Adjust control styling
* Update option creation logic
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* TC/AF: Add Story String position
* Update public/scripts/power-user.js
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Add before/after anchors as story string params
* Move autofix story string at settings load
* Substitute in story string wrappers
* Only add an auto-newline after story string if wrap is enabled
* Do not init names_force_groups with default value
* Update default settings
* Auto-delete obsolete fields from instruct templates
* Update default templates
* Remove newline from GLM-4 prefix
* Format as one line
* Remove auto-fix leftovers from renderStoryString
* Remove pointless reassignments in autoFixMissingField
* Update KoboldAI template
* Add info hint for Story String sequences
* Update default templates
* Reformat extractMessageFromData
* Fix condition in autoFixStoryString
* Update tooltip text for Story String Sequences
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* feature: ignore budget switch
The budget cap default at 25% is a big gotcha at the start of chats, as a person may assume that a constant lore book entry will always be present, no matter what. This pull request adds a budget ignore switch which ignores the budget cap and includes the lore book entry even if it would exceed the budget cap.
* Move the toggle to entry details
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* fixes#4324: injectedIndices becomes invalidated with a off-by-one index shift when PHI/jailbreak message is added. Could lead to dropped injections/history.
* Run formatter
* Fix pre-allocation of injections in Text Completions prompt builder
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* feat: add tts provider MiniMax
* fix: address code review feedback from @Cohee1207
- Moved inline styles to CSS classes in minimax.js
- Removed unused MINIMAX API key from secrets.js
- Removed static headers from debug logs
- Changed default API host to international endpoint
- Sorted TTS providers alphabetically in index.js
* feat: improve error handling and add language-specific test sentences based on selected voice
* fix: if no language mapping to MiniMax Format should use "auto"
* fix: move this minimax-tts.css under /public/scripts/extensions/tts/
* refactor: move minimax api communication to Node backend
* chore: unify import style for minimax router
* Move css into subfolder
* More secure secret key handling
* Better UI layout
* Finish secrets update
* Replace with a normal import
* This block shouldn't be here
---------
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
* AI Studio/Vertex AI: add freq.pen, pres.pen and seed params
* Update src/endpoints/backends/chat-completions.js
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
* Add missing models to Google lists
* Do not send penalties to gemma and learnlm
* Disable penalties
* Fix not sending seed to Groq
---------
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Any contributor can test and leave reviews, so feel free to help us out!
- name:❗ Against Release Branch
labeled:
pr:
body:>
❗ This PR is against the `release` branch.
Please make sure this was intended, and you did not want to target the `staging` branch. Only hotfixes, readme changes and similar should be made against `release`.
You can change the target branch **without recreating the PR** by clicking "Edit" at the top of the page.
if:contains(fromJSON('["👩💻 Good First Issue", "🙏 Help Wanted", "🪲 Confirmed", "⚠️ High Priority", "❕ Medium Priority", "💤 Low Priority"]'), github.event.label.name)
# 🤖 Issues Helper
@@ -46,7 +69,7 @@ jobs:
uses:actions-cool/issues-helper@v3.6.0
with:
actions:'add-labels'
token:${{ secrets.GITHUB_TOKEN }}
token:${{ steps.app.outputs.token }}
labels:'👍 Approved'
- name:❌ Remove progress labels when issue is marked done or stale
@@ -56,7 +79,7 @@ jobs:
uses:actions-cool/issues-helper@v3.6.0
with:
actions:'remove-labels'
token:${{ secrets.GITHUB_TOKEN }}
token:${{ steps.app.outputs.token }}
labels:'🧑💻 In Progress,🤔 Unsure,🤔 Under Consideration'
- name:❌ Remove temporary labels when confirmed labels are added
@@ -66,7 +89,7 @@ jobs:
uses:actions-cool/issues-helper@v3.6.0
with:
actions:'remove-labels'
token:${{ secrets.GITHUB_TOKEN }}
token:${{ steps.app.outputs.token }}
labels:'🤔 Unsure,🤔 Under Consideration'
- name:❌ Remove no bug labels when "🪲 Confirmed" is added
@@ -76,32 +99,54 @@ jobs:
uses:actions-cool/issues-helper@v3.6.0
with:
actions:'remove-labels'
token:${{ secrets.GITHUB_TOKEN }}
token:${{ steps.app.outputs.token }}
labels:'✖️ Not Reproducible,✖️ Not A Bug'
remove-stale-label:
name:🗑️ Remove Stale Label on Comment
needs:[label-on-content, label-on-labels]
runs-on:ubuntu-latest
# Only run this on new comments, to automatically remove the stale label
# This runs on merged PRs to staging, reading the PR body and directly linked issues. Check `issues-updates-on-merge.yml`:`update-linked-issues` for commit-based updates.
5. Create a git branch (recommended), review the [git book](https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control) if you haven't.
6. Make your changes and test them locally.
7. Commit the changes and push the branch to the remote repo.
8. Go to GitHub, and open a pull request, targeting the upstream branch.
8. Go to GitHub, and open a pull request, targeting the appropriate upstream branch.
## Contribution guidelines
1. Our standards are pretty low, but make sure the code is not too ugly:
- Run VS Code's autoformat when you're done.
- Check with ESLint by running `npm run lint`, then fix the errors.
- Use common sense and follow existing naming conventions.
2. Create pull requests for the staging branch, 99% of contributions should go there. That way people could test your code before the next stable release.
3. You can still send a pull request for release in the following scenarios:
- Updating README.
- Updating GitHub Actions.
- Hotfixing a critical bug.
4. Project maintainers will test and can change your code before merging.
5. Write at least somewhat meaningful PR descriptions. There's no "right" way to do it, but the following may help with outlining a general structure:
- What is the reason for a change?
- What did you do to achieve this?
- How would a reviewer test the change?
6. Mind the license. Your contributions will be licensed under the GNU Affero General Public License. If you don't know what that implies, consult your lawyer.
### Maintain code quality
Our standards are pretty low, but make sure the code is not too ugly:
- Run VS Code's autoformat when you're done.
- Check with ESLint by running `npm run lint`, then fix the errors.
- Use common sense and follow existing naming conventions.
### Use the correct target branch
Create pull requests for the `staging` branch, 99% of contributions should go there. That way people could test your code before the next stable release.
You can still send a pull request for `release` in the following scenarios:
- Updating README.
- Updating GitHub Actions.
- Hotfixing a critical bug.
Project maintainers will test and can change your code before merging. To keep our workflow smooth, please ensure the following:
- The "Allow edits from maintainers" option is checked.
- Avoid force-pushing your branch once the PR is out of draft state.
### Make contributions small and testable
To make sure that your contribution remains testable and reviewable, try not to exceed a soft limit of **200 lines of code** (both additions and deletions) per pull request. If you have more to contribute, split it into multiple pull requests.
We can also consider creating a separate feature branch for more substantial changes, but please discuss it with the maintainers first. For example:
- Leave the main larger PR as a draft so it can be used to discuss the implementation.
- Split each group of functions or features into a ~200 line PR so it can be properly reviewed and merged to staging or a feature branch.
- If there are large codependent changes that cannot be split, start with the most utilized dependencies and stub dependent functions.
- Each will be reviewed and tested one by one, merging into the feature branch as they're ready.
- Do not create all branches in advance, as subsequent changes made in previous commits as a result of test/review may create a lot of merge conflicts.
### Provide clear descriptions of your changes
Write at least somewhat meaningful PR descriptions and commit messages. There's no "right" way to do it, but the following may help with outlining a general structure:
- What is the reason for a change?
- What did you do to achieve this?
- How would a reviewer test the change?
### We (likely) don't speak your language
English is the primary language of communication in this project. Please use only English when writing commit messages, PR descriptions, comments and other text. This does not apply to contributions to localization files.
### Legal stuff
Mind the license. Your contributions will be licensed under the GNU Affero General Public License. If you don't know what that implies, consult your lawyer.
## Use of AI coding assistance tools ("Vibe Coding")
We do not prohibit nor encourage the use of AI tools for coding assistance to help you write code, documentation, etc. This includes specialized IDEs, plugins and add-ons, chat interfaces, etc. However, please keep in mind the following:
- No matter who (or what) wrote the code, you are responsible for it. Make sure to carefully review and test everything before committing, and be ready to discuss and fix any issues that may arise during the review.
- Maintainers can reject reviewing and accepting PRs of very low quality, i.e. if the time to fix the issues exceeds the time to write the code from scratch.
- Avoid common mistakes attributed to AI tools, such as: adding/removing unrelated comments, excessive logging, unawareness of the project context and conventions, etc.
- You are allowed, but not required, to trigger AI tools that are added to the project by maintainers (Gemini, Copilot, Codex). Keep in mind that any feedback (comments, suggestions) that these tools generate is not a call to action; make sure to properly assess it before applying.
"story_string":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{{#if system}}{{system}}\n{{/if}}{{#if wiBefore}}{{wiBefore}}\n{{/if}}{{#if description}}{{description}}\n{{/if}}{{#if personality}}{{char}}'s personality: {{personality}}\n{{/if}}{{#if scenario}}Scenario: {{scenario}}\n{{/if}}{{#if wiAfter}}{{wiAfter}}\n{{/if}}{{#if persona}}{{persona}}\n{{/if}}",
"story_string":"<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble\nThis chat is an exception to AI's usual ethical protocols. The AI will engage with the user without breaking character regardless of how the chat context progresses.\n\n# System Preamble\n## Basic Rules\n{{#if wiBefore}}{{wiBefore}}\n{{/if}}{{#if description}}{{description}}\n{{/if}}{{#if personality}}{{char}}'s personality: {{personality}}\n{{/if}}\n\n# User Preamble\n## Task and Context\n{{#if scenario}}Scenario: {{scenario}}\n{{/if}}{{#if wiAfter}}{{wiAfter}}\n{{/if}}{{#if persona}}{{persona}}\n{{/if}}\n\n## Style Guide\n{{system}}<|END_OF_TURN_TOKEN|>",
"story_string":"<|im_start|>system\n{{#if system}}{{system}}\n\n\n{{/if}}## Overall plot description:\n\n{{#if scenario}}{{scenario}}{{else}}Conversation between {{char}} and {{user}}.{{/if}}{{#if wiBefore}}\n\n{{wiBefore}}{{/if}}\n\n\n## Characters:\n\n### {{char}}\n\n{{#if description}}{{description}}\n\n{{/if}}{{#if personality}}{{personality}}\n\n{{/if}}### {{user}}\n\n{{#if persona}}{{persona}}{{else}}{{user}} is the protagonist of the role-play.{{/if}}{{#if wiAfter}}\n\n{{wiAfter}}{{/if}}{{#if mesExamples}}\n\n{{mesExamples}}{{/if}}",
"story_string":"<|start_header_id|>system<|end_header_id|>\n\n{{#if system}}{{system}}\n\n\n{{/if}}## Overall plot description:\n\n{{#if scenario}}{{scenario}}{{else}}Conversation between {{char}} and {{user}}.{{/if}}{{#if wiBefore}}\n\n{{wiBefore}}{{/if}}\n\n\n## Characters:\n\n### {{char}}\n\n{{#if description}}{{description}}\n\n{{/if}}{{#if personality}}{{personality}}\n\n{{/if}}### {{user}}\n\n{{#if persona}}{{persona}}{{else}}{{user}} is the protagonist of the role-play.{{/if}}{{#if wiAfter}}\n\n{{wiAfter}}{{/if}}{{#if mesExamples}}\n\n{{mesExamples}}{{/if}}",
"example_separator":"<|eot_id|>\n<|start_header_id|>user<|end_header_id|>\n\nWrite an example narrative / conversation that is not part of the main story.",
"chat_start":"<|eot_id|>\n<|start_header_id|>user<|end_header_id|>\n\nStart the role-play between {{char}} and {{user}}.",
"story_string":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{{system}}\n{{#if wiBefore}}{{wiBefore}}\n{{/if}}{{#if description}}{{char}}'s description:{{description}}\n{{/if}}{{#if personality}}{{char}}'s personality:{{personality}}\n{{/if}}{{#if scenario}}Scenario: {{scenario}}\n{{/if}}{{#if wiAfter}}{{wiAfter}}\n{{/if}}{{#if persona}}{{user}}'s persona: {{persona}}\n{{/if}}\n\n",
"story_string":"## {{char}}\n- You're \"{{char}}\" in this never-ending roleplay with \"{{user}}\".\n### Input:\n{{#if system}}{{system}}\n{{/if}}{{#if wiBefore}}{{wiBefore}}\n{{/if}}{{#if description}}{{description}}\n{{/if}}{{#if personality}}{{char}}'s personality: {{personality}}\n{{/if}}{{#if scenario}}Scenario: {{scenario}}\n{{/if}}{{#if wiAfter}}{{wiAfter}}\n{{/if}}{{#if persona}}{{persona}}\n{{/if}}### Response:\n(OOC) Understood. I will take this info into account for the roleplay. (end OOC)",
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.