Compare commits

..
110 Commits
Author SHA1 Message Date
Cohee 74c158bd2e Merge pull request #4656 from SillyTavern/staging
Staging
2025-10-16 20:31:22 +03:00
Cohee 91112362af Fix isClaude3or4 for OR caching 2025-10-15 22:59:41 +03:00
Cohee bd30a31815 Forgor context size 2025-10-15 21:30:52 +03:00
Cohee 23a59f27f1 claude-haiku-4-5 2025-10-15 21:27:46 +03:00
Cohee 10ebf09438 Fix control binds in gpt-sovits provider
Fixes #4655
2025-10-15 20:10:26 +03:00
Cohee 87d33b4d0b Highlight just imported chats in the list 2025-10-15 01:12:29 +03:00
Cohee b2c3f749d2 1.13.5 2025-10-15 00:56:03 +03:00
Cohee 3234045d64 Add bulk and drag&drop to chats import (#4652)
* Add bulk and drag-drop to chats import

* Perform list refresh only once
2025-10-15 00:43:30 +03:00
Cohee 0748af59e3 Fix missing swipe_info on first messages 2025-10-13 01:16:06 +03:00
Cohee a559f45ad4 Fix off-by-one cases in user prompt filler logic (#4648)
* 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
2025-10-12 23:36:17 +03:00
IceFog72 2ef9b3977b groupMemberListPopout placement (#4649)
`$('body').append(newElement);` -> `$('#movingDivs').append(newElement);`
2025-10-12 22:53:01 +03:00
LandCohee b7f93b3594 expose openThirdPartyExtensionMenu for Video Avatar extension (#4646)
* init

* Use less egregious export method

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-11 22:13:18 +03:00
df7f046912 Preset Regex: add preset type for script regexes (#4642)
* 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>
2025-10-11 22:10:06 +03:00
Cohee e4d779d450 NanoGPT: Add reasoning content display
Fixes #4643
2025-10-11 00:26:45 +03:00
CoheeandWolfsblvt df8f2a477a feat: prevent scrolling of containers when using focused number inputs (#4629)
* 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>
2025-10-10 21:42:44 +03:00
Cohee aaad129d1b Add missing props to ConnectionProfile typedef 2025-10-10 20:43:11 +03:00
bmen25124 d48a3639ed Added "custom_prompt_post_processing" to custom-request (#4639) 2025-10-10 20:37:23 +03:00
Mijyuoon 7944b7c7ff Add required icon sizes for PWAs on Firefox for Android (#4641) 2025-10-10 20:35:29 +03:00
cloak1505andCohee bc40d93b49 Remove dead Gemini 1.5 models, and clean up (#4636)
* 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>
2025-10-10 20:11:04 +03:00
Wolfsblvt 5fd64bef2e fix: improve bot detection and event filtering in GitHub workflow conditions 2025-10-09 00:24:04 +02:00
Cohee 20c7286ea1 Webpack: Only serve lib.js under root path 2025-10-09 01:22:10 +03:00
Wolfsblvt 59d4c7f5d7 fix: restrict app token generation to internal PRs and add fallback auth token (on PR comments) 2025-10-09 00:02:39 +02:00
Cohee 780633e05a text-embedding-005 2025-10-08 21:24:55 +03:00
Rivelle a418ad0f14 Add -webkit-tap-highlight-color for smoother touch experience (#4630)
* 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.
2025-10-08 19:46:43 +03:00
Cohee 2929ae66ad Remove recursive subtitution in getOutletPrompt 2025-10-08 10:49:49 +00:00
Cohee 21eee36eb3 Regex: Re-export getRegexScripts for legacy extensions 2025-10-08 09:26:06 +00:00
Cohee 9dddbbb04a Regex: Code clean-up (#4628)
* 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
2025-10-07 23:49:20 +03:00
StageDogandZoinkCN f15c91fa8e Preset Regex: refactor regex scope detection (#4618)
* refactor: explicit type for regex scope + feat: bulk move regex

* fix: eslint

* i18n: polish

* refactor: jsdoc + use object type for option

* fix: default return type for `getScriptsByType`

* refactor: simplify

* refactor: share default options

* refactor: remove unrequired css

* fix: move regexes to global + refactor: make regex operation interfaces more consistant

---------

Co-authored-by: ZoinkCN <zoinkcn@outlook.com>
2025-10-07 22:30:11 +03:00
Cohee 7296d89b58 Update PR template 2025-10-07 21:58:29 +03:00
Cohee 96ae49a89f Update contribution guidelines (#4613)
* 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
2025-10-07 21:57:42 +03:00
Wolfsblvt 01e3880587 refactor: add has() and get() to MacrosParser (#4626) 2025-10-07 21:19:24 +03:00
Wolfsblvt 806726d737 Workflows Switch all to use app token/app for any PR/issue labeling/commenting action (#4624)
* ci: switch workflows to use app token/app id authentication

* That wasn't supposed to go in this PR

* chore: refactor to local token minting step [Test]

* chore: expose token output from setup-app-token action and add PR checkout step

* ci: replace checkout and custom app token with create-github-app-token action in PR merge conflict workflow

* ci: add test label action to PR conflict check workflow

* another test...

* I am losing my sanity

* can this work now? please? This action adds my debug level?

* it needs to run always

* let's do it via curl...?

* why did it (totally not me) remove the always() again

* Sorry I screamed at you, Qwen. Does this work?

* refactor: consolidate GitHub App token creation into individual jobs

* chore: remove debug label functionality from merge conflict workflow

* chore: let's figure out why labeler is not behaving

* chore: remove temporary GitHub API token validation check from PR workflow

* ci: ensure workflow jobs run regardless of previous job failures by adding if: always()
2025-10-07 20:49:32 +03:00
Cohee 9a56a2ba2e Workflow: Update private key secret for GitHub app token 2025-10-07 17:01:28 +03:00
WolfsblvtandCohee f88ba369dd Workflows: Replace ISSUES_BOT_TOKEN with GitHub App for labeling + 'against release' auto comment (#4621)
* ci: replace ISSUES_BOT_TOKEN with GitHub App authentication for PR auto-labeling workflow

* Update PR auto comments for target branch guidance

Added note about changing target branch for PRs.

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-07 16:55:15 +03:00
TrahlocandTrahloc c14d88dbe0 Fix font size difference in API Connections dropdowns (#4620)
- 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>
2025-10-07 16:11:18 +03:00
StageDogandZoinkCN 72f91bcf83 Preset Regex: event change (#4616)
* feat: PRESET_RENAMED event

* fix: emit PRESET_DELETED only when the deletion successes

---------

Co-authored-by: ZoinkCN <zoinkcn@outlook.com>
2025-10-07 15:27:10 +03:00
IceFog72 d3019c7d49 Summarize Popout placement (#4615)
$('body').append(newElement); -> $('#movingDivs').append(newElement);
2025-10-07 00:13:34 +03:00
Wolfsblvt 74ff23ec0c fix: remove focus call before keyup event dispatch that traps cursor (#4607) 2025-10-06 23:25:49 +03:00
WolfsblvtandCohee 9463d1a152 Reprint non-tainted group chat on switching personas (#4603)
* fix: reprint non-tainted group chat on switching personas

* feat: mark chat as tainted when sending user message

* feat: mark chat as tainted when adding custom messages or captions

* feat: export createOrEditCharacter function and integrate it into retriggerFirstMessageOnEmptyChat

* fix: optimize loadPersonaForCurrentChat by storing current chat ID in a variable

* Improve conditions of first message retrigger

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-06 22:45:26 +03:00
befb2ffb78 deleteSwipe now emits the deleted message Id. (#4609)
* deleteSwipe now emits the deleted message Id.

* Fixed:

this_edit_mes_id can be a string (don't ask). Either wrap it in parseInt or Number function
https://github.com/SillyTavern/SillyTavern/pull/4609#discussion_r2405534766

I think it's better to use messageId in naming. Most of weirdly abbreviated params and variables come way back from TavernAI code.
https://github.com/SillyTavern/SillyTavern/pull/4609#discussion_r2405537550

* Revert outside number conversions

---------

Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-06 22:10:13 +03:00
StageDog aa699a3f93 feat: emit dryRun when GENERATE_AFTER_DATA (#4614) 2025-10-06 22:04:04 +03:00
Wolfsblvt c4cb0b783a security: update GitHub workflows to use ISSUES_BOT_TOKEN instead of GITHUB_TOKEN (#4606) 2025-10-06 11:33:38 +03:00
WolfsblvtandCohee 39fd16fe86 Fix not jumping twice to group chat when creating a new group chat with deleting the old one (#4602)
* fix: do not jumo to chat twice on new group chat with delete

* fix: prevent metadata reset when deleting non-active group chat

* Bring back group chat splice call

* Always delete past group metadata on chat delete

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-06 11:25:38 +03:00
WolfsblvtandCohee a65f708fd8 Allow create new world books via /getpersonabook and /getcharbook (#4597)
* feat: allow create new world books via /getpersonabook and /getcharbook

Refactor character world info management into dedicated functions

Extract character world assignment logic from UI handlers into reusable functions
Add support for automatic lorebook creation in slash commands
Improve code maintainability by centralizing world info operations

* refactor: update boolean enum provider from onOffToggle to trueFalse in world info commands

* fix: improve world info name uniqueness check using getUniqueName utility

* Unset current persona WI on file deletion

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-05 16:41:54 +03:00
Wolfsblvt 23b1360204 fix: add optional chaining to prevent undefined error when accessing first_mes (#4601) 2025-10-05 01:41:04 +03:00
Jakub JędrzejczykandCohee e68f9e482e Authentik automatic login support (#4600)
* feat: authentik auto login

* refactor: move SSO login configuration under sso section in config

* Migrate SSO config keys read

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-04 23:47:43 +03:00
Wolfsblvt d56c649d86 style: hide self-responses label when activation strategy is not natural (#4593) 2025-10-04 13:30:11 +03:00
Wolfsblvt 08f48a9867 fix: enable character source (open link) when group is selected (#4592) 2025-10-04 13:26:13 +03:00
Wolfsblvt 06f5cea402 Fix group chat on new chat not respecting saved persona connections (#4594)
* fix: (new) group chat doesn't respect persona connections

Fixes #3876

* refactor: simplify persona connection filtering with destructuring and type comparison

* fix: remove redundant type check in persona connection filtering logic

(char avatar and group key *should* always be unique and different anyway, no need to check on type. Makes this more flexible)
2025-10-04 13:24:49 +03:00
Cohee 334a5409a0 Persona description editor expand (#4591)
* Enhance persona description section with expandable editor icon

* Fix selector for persona description update to use data attribute
2025-10-04 13:15:32 +03:00
Cohee 326d1c34c8 Emit event on message swipe deletion (#4590)
Closes #4567
2025-10-03 21:20:29 +03:00
WolfsblvtandCohee df2dee8482 Fix make /profile await the for an actual successful API connection (#4589)
* fix: add connection status check after profile switch in connection manager

Fixes #4262

* feat: add timeout parameter to connection manager await functionality & catch timout error

* Add rejectOnTimeout option to waitUntilCondition

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-03 20:43:35 +03:00
Cohee 654ddb1608 Emit prompt events in generateRaw (#4587)
Closes https://github.com/SillyTavern/Extension-PromptInspector/issues/4
2025-10-03 19:50:01 +03:00
WolfsblvtandCohee 3e3dfbe05e Small change, (visually) disable "Link to Source" on characters that weren't downloaded from a source (#4588)
* 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>
2025-10-03 19:48:13 +03:00
Wolfsblvt c9e022a790 gitignore vscode workspaces 2025-10-03 08:16:00 +02:00
shanmaocc 58a294639a Fix duplicate CHARACTER_MESSAGE_RENDERED events during streaming (#4584)
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
2025-10-02 23:56:45 +03:00
WolfsblvtandCohee 7bedaed92c Extend Update/Replace character function to replace directly from URL + Fixes on cached thumbnail (#4581)
* 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>
2025-10-02 23:05:19 +03:00
Wolfsblvt 1d1b606f72 fix: prevent duplicate tag imports by filtering already assigned tags, fixing an unintended error toast (#4582) 2025-10-02 21:30:39 +03:00
Cohee 1d279e500e Allow saving empty secrets via secret manager and slash command (#4580)
* Allow saving empty secrets via secret manager and slash command
Closes #4577

* Fix logic on cancel

* Fix /secrets-read with empty secret value
2025-10-02 21:23:42 +03:00
Quairon-Nailo 8a5531b4ec feat: Add {{notChar}} macro for participant list (#4579)
* 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
2025-10-02 21:05:52 +03:00
WolfsblvtandCohee d2f3a85742 Fix MiniMax (TTS) pitch on API calls being the wrong range (#4578)
* 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>
2025-10-02 21:03:22 +03:00
DeclineThyselfanduser 9415185a89 Performance improvements due to using chatElement instead of $('#chat'). (#4576)
* Performance improvements due to using chatElement instead of $('#chat').

* Reverts change `hideSwipeButtons()` change.

https://github.com/SillyTavern/SillyTavern/pull/4576#discussion_r2394996102

---------

Co-authored-by: user <user@exmaple.com>
2025-10-01 22:49:13 +03:00
LandCohee 7f9cbb04c6 Scroll to top button (#4569)
* init

* implement review suggestions

* remove unnecessary css variables

* respect reduced motion

* simplify setupScrollToTop call

* power_user flag fix

* simplify, more of above

* remove remove button when drawer is closed logic

* throttle scroll checker

* Fix review comments

* Make scrollToTop a shared function

* Refactor logic

* Replace on hover color

* Prefer theme colors for button

* Increase hover brightness for scroll-to-top button

* Clean-up diff

* Fix type annotation

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-10-01 19:47:00 +03:00
Cohee 873868389c Use textContent for copy from codeblocks 2025-09-30 00:15:37 +03:00
Cohee d3774fec96 Check if messages is array before applying cache setting
Fixes #4564
2025-09-29 23:58:05 +03:00
Cohee dd2011f5be Streaming fade-in animation (#4568)
* [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
2025-09-29 23:32:41 +03:00
Cohee c4cc6f611e claude-sonnet-4-5 2025-09-29 23:22:12 +03:00
Cohee d73fd1a0e5 Merge branch 'release' into staging 2025-09-25 22:20:30 +03:00
dependabot[bot] 8f7b6b43c3 Bump tar-fs from 3.0.9 to 3.1.1 in /tests (#4561)
Bumps [tar-fs](https://github.com/mafintosh/tar-fs) from 3.0.9 to 3.1.1.
- [Commits](https://github.com/mafintosh/tar-fs/compare/v3.0.9...v3.1.1)

---
updated-dependencies:
- dependency-name: tar-fs
  dependency-version: 3.1.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-25 22:19:56 +03:00
André M PivaandCohee 0f49a059e3 Feat: add first and last buttons to pagination component (#4560)
* add first and last buttons to pagination

* Add i18n support

* Update pagination buttons font

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-25 20:42:47 +03:00
Cohee a3e47ce0a6 Remove bg lock/unlock toasts 2025-09-25 20:13:44 +03:00
LandCohee 4127b688c9 Update BG header layout (#4519)
* 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>
2025-09-25 20:12:12 +03:00
WolfsblvtandCohee c9419a383e Fix creator notes display field (in char panel) not updating when changed in Advanced Definitions (#4552)
* 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>
2025-09-23 21:58:20 +03:00
Cohee 45a7c6b2aa Assets: Display extension author in the list (#4551)
* Assets: Display extension author in the list

* Fix overflow of long text
2025-09-23 15:00:11 +03:00
Cohee f838d5c88d Fix WI AN position, break outlets in AN
Fixes #4554
2025-09-23 10:53:38 +00:00
Cohee 85fc7fe971 Fix: Close chat before performing deletion (#4545) 2025-09-22 00:59:46 +03:00
equal-l2 2679020ecd Add new Grok models (#4541)
* Add new Grok models

* Fix xAI request fields filtering

* Fetch xAI model lists from API
2025-09-21 17:41:39 +03:00
Cohee 8d19a6e77f Firefox: Fix parsing of style tags in creators notes 2025-09-21 01:37:33 +03:00
Cohee 64d7865837 Caption: Add refresh models button 2025-09-21 00:50:40 +03:00
Cohee 00cd7f8180 Mistral: Remove hard coded model lists 2025-09-20 20:42:14 +03:00
Cohee 3246d2960c Gemini: Fix parsing multiple tool calls in one response
Fixes #4537
2025-09-20 20:24:42 +03:00
Cohee 068ddd7c94 Mistral: Load caption models from endpoint 2025-09-20 00:22:12 +03:00
Cohee deec251f09 Return newline at the end of styles 2025-09-18 21:20:55 +03:00
Cohee 4e01c9c0dc Use variable for mobile jumbo list button 2025-09-18 21:19:44 +03:00
7cba4e88ab Add new WI position 'outlet' to expose WI entries triggered to be placed as macros literally anywhere (#4523)
* 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>
2025-09-18 21:12:14 +03:00
RossAscends 1fe8d96ab2 revert mobile char panel autoclose 2025-09-18 07:53:28 +09:00
RossAscends 97e4b41bc2 mobile: only autoclose char panel if it's actually open 2025-09-18 03:42:20 +09:00
RossAscends 1e7309fa17 i forgor one of em 2025-09-17 20:46:49 +09:00
RossAscends 2c25b5f012 completely ignore panel pins on mobile 2025-09-17 20:44:11 +09:00
RossAscends 136ddbc079 vert center mobile char list back button 2025-09-17 19:29:02 +09:00
RossAscends a0b2b740c9 Merge branch 'staging' of github.com-RA:sillytavern/sillytavern into staging 2025-09-17 18:19:59 +09:00
RossAscends 9298a34fea mobile fixes: close charlist on char select, hide L/R panel locks, larger charlist back button 2025-09-17 18:19:55 +09:00
Cohee ab66a9fed1 Caption: Rename Anthropic => Claude 2025-09-17 07:58:13 +00:00
07a4007363 feat: [Electron Hub] Added Text-to-Speech, Prompt cost, Sort/Group/Se… (#4528)
* feat: [Electron Hub] Added Text-to-Speech, Prompt cost, Sort/Group/Search for model list

* feat: [Electron Hub] Added Text-to-Speech, Prompt cost, Sort/Group/Search for model list

* Update public/scripts/extensions/tts/electronhub.js

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* Update public/scripts/openai.js

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* Update public/scripts/openai.js

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* feat: [Electron Hub] Added Text-to-Speech, Prompt cost, Sort/Group/Search for model list

* feat: [Electron Hub] Show model capabilities

* Support logit_bias

* Small tweaks

* Added tokenizer selection logic

* Added tokenizer selection logic

* Fixed ESLint

* Small tweaks

* Split localization tags

* Fix formatting

* Refactor icons, add tool icon

* Support newer oai model tokenizers

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-16 22:22:27 +03:00
LandCohee eec837cee6 Layout Update (#4514)
* 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>
2025-09-16 13:20:06 +03:00
RossAscends 33458b86b0 Merge branch 'staging' of github.com-RA:sillytavern/sillytavern into staging 2025-09-16 00:44:52 +09:00
RossAscends 76d48bf8f8 nomnalize TGWebUI grammar string HTML nest 2025-09-16 00:44:48 +09:00
L 9b0e84832f div id="logo block" update (#4524) 2025-09-15 10:06:52 +03:00
L 5170984446 Backgrounds Drawer Max Height (#4515)
* init

* lint

* shrink drawer, plus why is css messy

* put questionable hint back in

* copy other drawers
2025-09-15 09:50:29 +03:00
GoldenglowMeow e0edd57653 fix(perf): disable periodic expired item check in node-persist (#4521) 2025-09-14 21:00:17 +03:00
RossAscends 4d366e463d Merge branch 'staging' of github.com-RA:sillytavern/sillytavern into staging 2025-09-15 02:59:31 +09:00
RossAscends b814e29d40 show grammar string input in tabby API samplers list 2025-09-15 02:59:24 +09:00
1e05eac7df Update ru-ru locale (#4522)
* Work on tl

* eslint fix

* Update data-i18n attribute for expand view button

* Add data-i18n to button

---------

Co-authored-by: Yokayo <nonameutubecomm@gmail.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-14 20:57:33 +03:00
Cohee 23e5a7ca38 Fix prompt cost block showing when switching API type to TC and type is not OpenRouter 2025-09-14 20:46:53 +03:00
RossAscends f1dd51867d standardize ooba logit bias HTML nest 2025-09-15 02:27:57 +09:00
RossAscends 5c0e2e7c96 more TGWebUI sampler HTML nest cleanup 2025-09-15 01:53:52 +09:00
RossAscends 0795e397a6 standardize TGwebui sampler toggle HTML nests 2025-09-15 00:23:51 +09:00
Cohee aec8b8db2a Docker: Update base image to node:lts-alpine3.22 2025-09-13 23:21:16 +03:00
Cohee 8f68b2cae9 Actions: Update Node version in npm publish workflow 2025-09-13 23:13:00 +03:00
Cohee f53f039452 Fix toast position on app init 2025-09-13 21:23:11 +03:00
107 changed files with 4401 additions and 1563 deletions
+10
View File
@@ -41,6 +41,16 @@ labels:
🔬 This PR needs testing!
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.
- name: 🟥 ⬤⬤⬤⬤⬤
labeled:
pr:
+1 -1
View File
@@ -2,4 +2,4 @@
## Checklist:
- [ ] I have read the [Contributing guidelines](https://github.com/SillyTavern/SillyTavern/blob/release/CONTRIBUTING.md).
- [ ] I have read the [Contribution guidelines](https://github.com/SillyTavern/SillyTavern/blob/release/CONTRIBUTING.md).
+54 -9
View File
@@ -15,8 +15,19 @@ jobs:
label-on-content:
name: 🏷️ Label Issues by Content
runs-on: ubuntu-latest
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout Repository
# Checkout
# https://github.com/marketplace/actions/checkout
@@ -32,13 +43,25 @@ jobs:
with:
configuration-path: .github/issues-auto-labels.yml
enable-versioned-regex: 0
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token: ${{ steps.app.outputs.token }}
label-on-labels:
name: 🏷️ Label Issues by Labels
needs: [label-on-content]
runs-on: ubuntu-latest
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: ✅ Add "👍 Approved" for relevant labels
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
if: github.event_name == 'issue_comment' && github.actor != 'github-actions[bot]'
if: always() && (github.event_name == 'issue_comment' && github.event.sender.type != 'Bot')
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Remove Stale Label
# 🤖 Issues Helper
# https://github.com/marketplace/actions/issues-helper
uses: actions-cool/issues-helper@v3.6.0
with:
actions: 'remove-labels'
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ steps.app.outputs.token }}
issue-number: ${{ github.event.issue.number }}
labels: '⚰️ Stale,🕸️ Inactive,🚏 Awaiting User Response,🛑 No Response'
write-auto-comments:
name: 💬 Post Issue Comments Based on Labels
needs: [label-on-content, label-on-labels]
needs: [label-on-content, label-on-labels, remove-stale-label]
runs-on: ubuntu-latest
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout Repository
# Checkout
# https://github.com/marketplace/actions/checkout
@@ -113,4 +158,4 @@ jobs:
uses: peaceiris/actions-label-commenter@v1.10.0
with:
config_file: .github/issues-auto-comments.yml
github_token: ${{ secrets.GITHUB_TOKEN }}
github_token: ${{ steps.app.outputs.token }}
+12 -1
View File
@@ -15,8 +15,19 @@ jobs:
update-linked-issues:
name: 🔗 Mark Linked Issues Done on Push
runs-on: ubuntu-latest
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout Repository
# Checkout
# https://github.com/marketplace/actions/checkout
@@ -31,7 +42,7 @@ jobs:
- name: Label Linked Issues
id: label_linked_issues
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_TOKEN: ${{ steps.app.outputs.token }}
run: |
for ISSUE in $(echo $issues | jq -r '.[]'); do
if [ "${{ github.ref }}" == "refs/heads/staging" ]; then
+38 -5
View File
@@ -15,14 +15,25 @@ jobs:
mark-inactivity:
name: ⏳ Mark Issues/PRs without Activity
runs-on: ubuntu-latest
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Mark Issues/PRs without Activity
# Close Stale Issues and PRs
# https://github.com/marketplace/actions/close-stale-issues
uses: actions/stale@v9.1.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token: ${{ steps.app.outputs.token }}
days-before-stale: 183
days-before-close: 7
operations-per-run: 30
@@ -47,16 +58,27 @@ jobs:
await-user-response:
name: ⚠️ Mark Issues/PRs Awaiting User Response
needs: [mark-inactivity]
runs-on: ubuntu-latest
needs: mark-inactivity
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Mark Issues/PRs Awaiting User Response
# Close Stale Issues and PRs
# https://github.com/marketplace/actions/close-stale-issues
uses: actions/stale@v9.1.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token: ${{ steps.app.outputs.token }}
days-before-stale: 7
days-before-close: 7
operations-per-run: 30
@@ -74,16 +96,27 @@ jobs:
alternative-exists:
name: 🔄 Mark Issues with Alternative Exists
needs: [mark-inactivity, await-user-response]
runs-on: ubuntu-latest
needs: await-user-response
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Mark Issues with Alternative Exists
# Close Stale Issues and PRs
# https://github.com/marketplace/actions/close-stale-issues
uses: actions/stale@v9.1.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token: ${{ steps.app.outputs.token }}
days-before-stale: 7
days-before-close: 7
operations-per-run: 30
+2 -2
View File
@@ -14,7 +14,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: 22
- run: npm ci
publish-npm:
@@ -24,7 +24,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: 22
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm publish
+12 -1
View File
@@ -15,14 +15,25 @@ jobs:
remove-labels:
name: 🗑️ Remove Pending Labels on Close
runs-on: ubuntu-latest
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Remove Pending Labels on Close
# 🤖 Issues Helper
# https://github.com/marketplace/actions/issues-helper
uses: actions-cool/issues-helper@v3.6.0
with:
actions: remove-labels
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ steps.app.outputs.token }}
issue-number: ${{ github.event.issue.number || github.event.pull_request.number }}
labels: '🚏 Awaiting User Response,🧑‍💻 In Progress,📌 Keep Open,🚫 Merge Conflicts,🔬 Needs Testing,🔨 Needs Work,⚰️ Stale,⛔ Waiting For External/Upstream'
+12 -2
View File
@@ -15,15 +15,25 @@ jobs:
label-maintainer:
name: 🏷️ Label if Author is a Repo Maintainer
runs-on: ubuntu-latest
if: contains(fromJson('["Cohee1207", "RossAscends", "Wolfsblvt"]'), github.actor)
if: always() && contains(fromJson('["Cohee1207", "RossAscends", "Wolfsblvt"]'), github.actor)
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Label if Author is a Repo Maintainer
# 🤖 Issues Helper
# https://github.com/marketplace/actions/issues-helper
uses: actions-cool/issues-helper@v3.6.0
with:
actions: 'add-labels'
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ steps.app.outputs.token }}
issue-number: ${{ github.event.issue.number || github.event.pull_request.number }}
labels: '👷 Maintainer'
+88 -16
View File
@@ -16,7 +16,7 @@ jobs:
name: ✅ Check ESLint on PR
runs-on: ubuntu-latest
# Only needs to run when code is changed
if: github.event.action == 'opened' || github.event.action == 'synchronize'
if: always() && (github.event.action == 'opened' || github.event.action == 'synchronize')
# Override permissions, linter likely needs write access to issues
permissions:
@@ -48,7 +48,7 @@ jobs:
# https://github.com/marketplace/actions/action-eslint
uses: sibiraj-s/action-eslint@v3.0.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ secrets.GITHUB_TOKEN }} # ESLint can run with the original permissions
eslint-args: '--ignore-path=.gitignore --quiet'
extensions: 'js'
annotations: true
@@ -71,12 +71,22 @@ jobs:
pull-requests: write
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Label PR Size
# Pull Request Size Labeler
# https://github.com/marketplace/actions/pull-request-size-labeler
uses: codelytv/pr-size-labeler@v1.10.2
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ steps.app.outputs.token }}
xs_label: '🟩 ⬤○○○○'
xs_max_size: '20'
s_label: '🟩 ⬤⬤○○○'
@@ -95,9 +105,19 @@ jobs:
name: 🏷️ Label PR by Branches
runs-on: ubuntu-latest
# Only label once when PR is created or when base branch is changed, to allow manual label removal
if: github.event.action == 'opened' || (github.event.action == 'synchronize' && github.event.changes.base)
if: always() && (github.event.action == 'opened' || (github.event.action == 'synchronize' && github.event.changes.base))
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout Repository
# Checkout
# https://github.com/marketplace/actions/checkout
@@ -109,15 +129,26 @@ jobs:
uses: actions/labeler@v5.0.0
with:
configuration-path: .github/pr-auto-labels-by-branch.yml
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token: ${{ steps.app.outputs.token }}
label-by-files:
name: 🏷️ Label PR by Files
needs: [label-by-branches]
runs-on: ubuntu-latest
# Only needs to run when code is changed
if: github.event.action == 'opened' || github.event.action == 'synchronize'
if: always() && (github.event.action == 'opened' || github.event.action == 'synchronize')
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout Repository
# Checkout
# https://github.com/marketplace/actions/checkout
@@ -127,15 +158,18 @@ jobs:
# Pull Request Labeler
# https://github.com/marketplace/actions/labeler
uses: actions/labeler@v5.0.0
env:
GITHUB_TOKEN: ${{ steps.app.outputs.token }} # labeler action needs some handholding
with:
configuration-path: .github/pr-auto-labels-by-files.yml
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token: ${{ steps.app.outputs.token }}
remove-stale-label:
name: 🗑️ Remove Stale Label on Comment
needs: [label-by-branches, label-by-files]
runs-on: ubuntu-latest
# Only runs on comments not done by the github actions bot
if: github.event_name == 'pull_request_review_comment' && github.actor != 'github-actions[bot]'
if: always() && (github.event_name == 'pull_request_review_comment' && github.event.sender.type != 'Bot')
# Override permissions, issue labeler needs issues write access
permissions:
@@ -144,19 +178,33 @@ jobs:
pull-requests: write
steps:
- name: Mint App Token
if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
id: app
# Only run if the PR is from the same repository
# This action runs on comments, which will not receive the env vars for this
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Remove Stale Label
if: always()
# 🤖 Issues Helper
# https://github.com/marketplace/actions/issues-helper
uses: actions-cool/issues-helper@v3.6.0
with:
actions: 'remove-labels'
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ steps.app.outputs.token || github.token }} # Use fallback to GITHUB_TOKEN if app token is not available
issue-number: ${{ github.event.pull_request.number }}
labels: '⚰️ Stale'
check-merge-blocking-labels:
name: 🚫 Check Merge Blocking Labels
needs: [label-by-branches, label-by-files]
needs: [label-by-branches, label-by-files, remove-stale-label]
runs-on: ubuntu-latest
# Run, even if the previous jobs were skipped/failed
if: always()
@@ -206,12 +254,22 @@ jobs:
write-auto-comments:
name: 💬 Post PR Comments Based on Labels
needs: [label-by-branches, label-by-files]
needs: [label-by-branches, label-by-files, remove-stale-label, check-merge-blocking-labels]
runs-on: ubuntu-latest
# Run, even if the previous jobs were skipped/failed
if: always()
if: always() && (github.event_name == 'pull_request_target')
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout Repository
# Checkout
# https://github.com/marketplace/actions/checkout
@@ -223,13 +281,17 @@ jobs:
uses: peaceiris/actions-label-commenter@v1.10.0
with:
config_file: .github/pr-auto-comments.yml
github_token: ${{ secrets.GITHUB_TOKEN }}
github_token: ${{ steps.app.outputs.token }}
# 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.
update-linked-issues:
name: 🔗 Mark Linked Issues Done on Staging Merge
runs-on: ubuntu-latest
if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'staging'
if: >
always() &&
github.event_name == 'pull_request_target' &&
github.event.pull_request.merged == true &&
github.event.pull_request.base.ref == 'staging'
# Override permissions, We need to be able to write to issues
permissions:
@@ -238,6 +300,16 @@ jobs:
pull-requests: write
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Extract Linked Issues From PR Description
id: extract_issues
run: |
@@ -250,7 +322,7 @@ jobs:
PR_NUMBER=${{ github.event.pull_request.number }}
REPO=${{ github.repository }}
API_URL="https://api.github.com/repos/$REPO/pulls/$PR_NUMBER/issues"
ISSUES=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" "$API_URL" | jq -r '.[].number' | jq -R -s -c 'split("\n")[:-1]')
ISSUES=$(curl -s -H "Authorization: token ${{ steps.app.outputs.token }}" "$API_URL" | jq -r '.[].number' | jq -R -s -c 'split("\n")[:-1]')
echo "linked_issues=$ISSUES" >> $GITHUB_ENV
- name: Merge Issue Lists
@@ -262,7 +334,7 @@ jobs:
- name: Label Linked Issues
id: label_linked_issues
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_TOKEN: ${{ steps.app.outputs.token }}
run: |
for ISSUE in $(echo $final_issues | jq -r '.[]'); do
gh issue edit $ISSUE -R ${{ github.repository }} --add-label "✅ Done (staging)" --remove-label "🧑‍💻 In Progress"
@@ -15,14 +15,25 @@ jobs:
check-merge-conflicts:
name: ⚔️ Check Merge Conflicts
runs-on: ubuntu-latest
if: always()
steps:
- name: Mint App Token
id: app
# Create a GitHub App token
# https://github.com/marketplace/actions/create-github-app-token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ vars.ST_BOT_APP_ID }}
private-key: ${{ secrets.ST_BOT_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Check Merge Conflicts
# Label Conflicting Pull Requests
# https://github.com/marketplace/actions/label-conflicting-pull-requests
uses: eps1lon/actions-label-merge-conflict@v3.0.3
with:
dirtyLabel: '🚫 Merge Conflicts'
repoToken: ${{ secrets.GITHUB_TOKEN }}
repoToken: ${{ steps.app.outputs.token }}
commentOnDirty: >
⚠️ This PR has conflicts that need to be resolved before it can be merged.
+1
View File
@@ -55,3 +55,4 @@ public/scripts/extensions/third-party
.env
/StartDev.bat
yarn.lock
*.code-workspace
+14 -3
View File
@@ -9,7 +9,7 @@
## Getting the code ready
1. Register a GitHub account.
2. Fork this repository under your account.
2. Fork this repository under your account.
3. Clone the fork onto your machine.
4. Open the cloned repository in the code editor.
5. Create a git branch (recommended).
@@ -29,11 +29,22 @@
- 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:
5. 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.
6. 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?
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.
7. 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.
8. 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.
## Further reading
+1 -1
View File
@@ -1,4 +1,4 @@
FROM node:lts-alpine3.21
FROM node:lts-alpine3.22
# Arguments
ARG APP_HOME=/home/node/app
+20 -8
View File
@@ -82,18 +82,30 @@ requestProxy:
enableUserAccounts: false
# Enable discreet login mode: hides user list on the login screen
enableDiscreetLogin: false
# Enable's authlia based auto login. Only enable this if you
# have setup and installed Authelia as a middle-ware on your
# reverse proxy
# https://www.authelia.com/
# This will use auto login to an account with the same username
# as that used for authlia. (Ensure the username in authlia
# is an exact match in lowercase with that in sillytavern)
autheliaAuth: false
# If `basicAuthMode` and this are enabled then
# the username and passwords for basic auth are the same as those
# for the individual accounts
perUserBasicAuth: false
# -- SSO LOGIN CONFIGURATION --
sso:
# Enable's authlia based auto login. Only enable this if you
# have setup and installed Authelia as a middle-ware on your
# reverse proxy
# https://www.authelia.com/
# This will use auto login to an account with the same username
# as that used for authlia. (Ensure the username in authlia
# is an exact match in lowercase with that in sillytavern)
autheliaAuth: false
# Enable's authentik based auto login. Only enable this if you
# have setup and installed Authentik as a middle-ware on your
# reverse proxy.
# https://goauthentik.io/
# This will use auto login to an account with the same username
# as that used for authentik. (Ensure the username in authentik
# is an exact match in lowercase with that in sillytavern).
authentikAuth: false
# Host whitelist configuration. Recommended if you're using a listen mode
hostWhitelist:
# Enable or disable host whitelisting
+6 -3
View File
@@ -1,20 +1,23 @@
{
"chat_completion_source": "openai",
"openai_model": "gpt-4-turbo",
"claude_model": "claude-3-5-sonnet-20240620",
"claude_model": "claude-sonnet-4-5",
"openrouter_model": "OR_Website",
"openrouter_use_fallback": false,
"openrouter_group_models": false,
"openrouter_sort_models": "alphabetically",
"ai21_model": "jamba-large",
"mistralai_model": "mistral-large-latest",
"electronhub_model": "gpt-4o-mini",
"electronhub_sort_models": "alphabetically",
"electronhub_group_models": false,
"custom_model": "",
"custom_url": "",
"custom_include_body": "",
"custom_exclude_body": "",
"custom_include_headers": "",
"google_model": "gemini-pro",
"vertexai_model": "gemini-2.0-flash-001",
"google_model": "gemini-2.5-pro",
"vertexai_model": "gemini-2.5-pro",
"temperature": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
+1 -1
View File
@@ -620,7 +620,7 @@
},
"wi_format": "{0}",
"openai_model": "gpt-4-turbo",
"claude_model": "claude-3-5-sonnet-20240620",
"claude_model": "claude-sonnet-4-5",
"ai21_model": "jamba-large",
"openrouter_model": "OR_Website",
"reverse_proxy": "",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "sillytavern",
"version": "1.13.4",
"version": "1.13.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sillytavern",
"version": "1.13.4",
"version": "1.13.5",
"hasInstallScript": true,
"license": "AGPL-3.0",
"dependencies": {
+1 -1
View File
@@ -113,7 +113,7 @@
"type": "git",
"url": "https://github.com/SillyTavern/SillyTavern.git"
},
"version": "1.13.4",
"version": "1.13.5",
"scripts": {
"start": "node server.js",
"debug": "node --inspect server.js",
+142 -69
View File
@@ -1,6 +1,5 @@
/* Main Page Backgrounds */
#bg1,
#bg_custom {
#bg1 {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
@@ -8,72 +7,46 @@
width: 100%;
height: 100%;
transition: background-image var(--animation-duration-3x) ease-in-out;
z-index: -1;
}
/* Fitting options */
#background_fitting {
max-width: 6em;
max-width: 8em;
}
/* Fill/Cover - scales to fill width while maintaining aspect ratio */
#bg1.cover,
#bg_custom.cover {
#bg1.cover {
background-size: cover;
background-position: center;
}
/* Fit/Contain - shows entire image maintaining aspect ratio */
#bg1.contain,
#bg_custom.contain {
#bg1.contain {
background-size: contain;
background-position: center;
background-repeat: no-repeat;
}
/* Stretch - stretches to fill entire space */
#bg1.stretch,
#bg_custom.stretch {
#bg1.stretch {
background-size: 100% 100%;
}
/* Center - centers without scaling */
#bg1.center,
#bg_custom.center {
#bg1.center {
background-size: auto;
background-position: center;
background-repeat: no-repeat;
}
body.reduced-motion #bg1,
body.reduced-motion #bg_custom {
transition: none;
}
#bg1 {
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');
z-index: -3;
}
#bg_custom {
background-image: none;
z-index: -2;
}
.bg_example.flex-container.locked:not(:focus-visible) {
outline-color: var(--golden);
}
/* This is the main flex container for the entire drawer */
#Backgrounds.drawer-content.openDrawer.bg-drawer-layout {
.drawer-content.openDrawer.bg-drawer-layout {
display: flex;
}
.bg-drawer-layout {
flex-direction: column;
height: calc(100vh - var(--topBarBlockSize));
max-height: calc(100vh - var(--topBarBlockSize));
height: calc(100dvh - var(--topBarBlockSize));
max-height: calc(100dvh - var(--topBarBlockSize));
overflow: hidden;
width: var(--sheldWidth);
max-width: var(--sheldWidth);
padding: 0;
}
@@ -82,11 +55,31 @@ body.reduced-motion #bg_custom {
padding: 5px;
background-color: var(--SmartThemeBlurTintColor);
border-bottom: 1px solid var(--SmartThemeBorderColor);
width: 100%;
}
#bg-header-fixed>.flex-container {
.bg-header-row-1,
.bg-header-row-2 {
display: flex;
gap: 5px;
width: 100%;
}
/* Control buttons in header */
.heading-container-with-controls {
position: relative;
}
.heading-container-with-controls .heading-text {
margin: 10px 0;
}
.heading-container-with-controls .heading-controls {
position: absolute;
right: 5px;
top: 50%;
transform: translateY(-50%);
display: flex;
align-items: center;
gap: 5px;
}
@@ -94,49 +87,92 @@ body.reduced-motion #bg_custom {
flex-grow: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 0 5px 5px;
padding: 0 5px 15px;
position: relative;
}
#bg_menu_content,
#bg_custom_content {
display: grid;
gap: 5px;
width: 100%;
grid-template-columns: repeat(var(--bg-thumb-columns, 5), 1fr);
}
#bg-filter {
font-size: calc(var(--mainFontSize) * 0.95);
}
/* Thumbnail Menu & Buttons */
/* Thumbnails */
.bg_example:hover .BGSampleTitle {
opacity: 1;
}
.bg_example .mobile-only-menu-toggle {
display: none;
}
.bg_example.flex-container {
width: 30%;
max-width: 200px;
margin: 5px;
aspect-ratio: 16/9;
.bg_example {
cursor: pointer;
box-shadow: 0 0 7px var(--black50a);
position: relative;
overflow: hidden;
border-radius: 8px;
border: 0px solid transparent;
outline: 2px solid var(--SmartThemeBorderColor);
outline-offset: -1px;
height: auto;
aspect-ratio: 16 / 9;
}
.bg_example.flex-container:focus-visible {
.bg_example:focus-visible {
outline-offset: inherit;
outline-color: var(--interactable-outline-color);
}
.bg_example_img {
.bg_example.locked-background {
outline: 2px solid var(--golden);
outline-offset: 0;
}
.bg_example.locked-background::after {
content: '\f023';
font-family: 'Font Awesome 6 Free';
font-weight: 900;
position: absolute;
top: -2px;
left: -2px;
right: -2px;
bottom: -2px;
bottom: 5px;
right: 5px;
z-index: 4;
color: var(--golden);
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.8));
font-size: calc(var(--mainFontSize) * 0.8);
pointer-events: none;
}
background-image: inherit;
.bg_example:not(.locked-background) .jg-unlock,
.bg_example.locked-background .jg-lock {
display: none;
}
background-size: cover;
background-position: center;
.bg_example.selected-background {
outline: 2px solid white;
outline-offset: 0;
}
.bg_example.selected-background::before {
content: '\f00c';
font-family: 'Font Awesome 6 Free';
font-weight: 900;
position: absolute;
top: 5px;
left: 5px;
z-index: 4;
color: var(--white100);
filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.8));
font-size: calc(var(--mainFontSize) * 0.9);
pointer-events: none;
}
.bg_example .jg-menu {
@@ -145,9 +181,8 @@ body.reduced-motion #bg_custom {
top: 2px;
right: 2px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 8px;
gap: 3px;
padding: 3px 5px;
border-radius: 5px;
padding: 3px 3px;
z-index: 3;
backdrop-filter: blur(4px);
border: 1px solid var(--SmartThemeBorderColor);
@@ -170,14 +205,14 @@ body.reduced-motion #bg_custom {
.bg_example .jg-button {
display: flex;
width: 30px;
height: 30px;
width: 24px;
height: 24px;
align-items: center;
justify-content: center;
color: white;
padding: 5px;
font-size: 1.1em;
border-radius: 6px;
border-radius: 5px;
transition: background-color var(--animation-duration) ease;
}
@@ -185,16 +220,54 @@ body.reduced-motion #bg_custom {
background-color: rgba(255, 255, 255, 0.2);
}
.bg_example .jg-unlock {
display: none;
/* Scroll-to-Top Button */
#bg-scroll-top {
position: absolute;
bottom: 20px;
right: 20px;
width: 42px;
height: 42px;
background: var(--SmartThemeBlurTintColor);
color: var(--SmartThemeBodyColor);
border: 1px solid var(--SmartThemeBorderColor);
border-radius: 50%;
cursor: pointer;
z-index: 10;
font-size: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity var(--animation-duration) ease;
pointer-events: none;
}
.bg_example.locked .jg-lock {
display: none;
#bg-scroll-top.visible {
opacity: 1;
pointer-events: auto;
}
.bg_example.locked .jg-unlock {
display: flex;
#bg-scroll-top:hover {
filter: brightness(150%);
outline: 1px solid var(--interactable-outline-color);
}
#bg-scroll-top .fa-solid {
margin: 0;
padding: 0;
line-height: 1;
}
.thumbnail-clipper {
position: absolute;
top: -2px;
left: -2px;
right: -2px;
bottom: -2px;
overflow: hidden;
border-radius: inherit;
background-size: cover;
background-position: center;
}
.bg_example:not([custom="true"]) .jg-copy,
+31 -44
View File
@@ -10,6 +10,18 @@
flex-basis: 100%;
}
#rm_button_panel_pin_div,
#lm_button_panel_pin_div {
display: none;
}
#rm_button_characters {
font-size: var(--topBarIconSize);
}
#CharListButtonAndHotSwaps {
align-items: center;
}
#send_form.compact #leftSendForm,
#send_form.compact #rightSendForm {
@@ -21,6 +33,15 @@
display: none;
}
#bg_menu_content,
#bg_custom_content {
grid-template-columns: repeat(var(--bg-thumb-columns, 3), 1fr);
}
.bg_list {
width: unset;
}
.bg_button {
font-size: 15px;
}
@@ -40,6 +61,11 @@
z-index: 4;
}
.bg_example.mobile-menu-open .mobile-only-menu-toggle {
opacity: 0;
pointer-events: none;
}
.bg_example .mobile-only-menu-toggle {
display: flex;
align-items: center;
@@ -57,48 +83,13 @@
backdrop-filter: blur(2px);
}
#bg-header-controls {
flex-wrap: wrap;
row-gap: 10px;
.bg_example .jg-button {
width: 30px;
height: 30px;
}
#bg-header-fixed>.flex-container {
flex-wrap: wrap;
row-gap: 0px;
}
#Backgrounds:not(.selection-mode-active) #bg-header-fixed>.flex-container::after {
content: '';
order: 1;
flex-basis: 100%;
height: 0;
}
/* --- Row 1 Item --- */
#bg-header-fixed #bg-header-title {
order: 1;
flex-grow: 1;
}
#bg-header-fixed #background_fitting,
#bg-header-fixed #auto_background {
order: 1;
}
/* --- Row 2 Item --- */
#bg-header-fixed #bg-filter {
order: 2;
flex-grow: 1;
min-width: 0;
}
/* --- Row 3 Item --- */
#bg-header-fixed #add_background_button_top {
order: 3;
width: 100%;
text-align: center;
padding-top: 0.5em;
padding-bottom: 0.5em;
#background_fitting {
max-width: 6em;
}
#Backgrounds.drawer-content.openDrawer.bg-drawer-layout {
@@ -429,10 +420,6 @@
.horde_multiple_hint {
display: none;
}
.bg_list {
width: unset;
}
}
/*landscape mode phones and ipads*/
+4
View File
@@ -301,6 +301,10 @@ select.keyselect+span.select2-container .select2-selection--multiple {
display: none;
}
.world_entry:not(:has(select[name="position"] option[value="7"]:checked)) .world_entry_form_control:has(input[name="outletName"]) {
display: none;
}
.world_entry label[for="__invisible"] {
visibility: hidden;
pointer-events: none;
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

+149 -180
View File
@@ -49,7 +49,6 @@
<body class="no-blur">
<div id="preloader"></div>
<div id="bg_custom"></div>
<div id="bg1"></div>
<div id="character_context_menu" class="hidden">
<ul>
@@ -254,7 +253,7 @@
</div>
<div id="common-gen-settings-block" class="width100p">
<div id="pro-settings-block" class="flex-container gap10h5v justifyCenter">
<div id="amount_gen_block" class="alignitemscenter flex-container marginBot5 flexFlowColumn flexBasis48p flexGrow flexShrink gap0">
<div id="amount_gen_block" class="range-block-range-and-counter alignitemscenter flex-container marginBot5 flexFlowColumn flexBasis48p flexGrow flexShrink gap0">
<small data-i18n="response legth(tokens)">Response (tokens)</small>
<input class="neo-range-slider" type="range" id="amount_gen" name="volume" min="16" max="2048" step="1">
<div data-randomization-disabled="true" class="wide100p">
@@ -285,7 +284,7 @@
</label>
</div>
</div>
<div id="max_context_block" class="alignitemscenter flex-container marginBot5 flexFlowColumn flexBasis48p flexGrow flexShrink gap0">
<div id="max_context_block" class="range-block-range-and-counter alignitemscenter flex-container marginBot5 flexFlowColumn flexBasis48p flexGrow flexShrink gap0">
<small data-i18n="context size(tokens)">Context (tokens)</small>
<input class="neo-range-slider" type="range" id="max_context" name="volume" min="512" max="8192" step="64">
<div data-randomization-disabled="true" class="wide100p">
@@ -649,7 +648,7 @@
Max Response Length (tokens)
</div>
<div class="wide100p">
<input type="number" id="openai_max_tokens" name="openai_max_tokens" class="text_pole" min="1" max="65536">
<input type="number" id="openai_max_tokens" name="openai_max_tokens" class="text_pole" min="1" max="65536" step="1">
</div>
</div>
<div class="range-block" data-source="openai,custom,xai,aimlapi,moonshot,azure_openai">
@@ -676,6 +675,9 @@
<div data-source="openrouter">
<span data-i18n="Max prompt cost:">Max prompt cost:</span> <span id="openrouter_max_prompt_cost" data-i18n="Unknown">Unknown</span>
</div>
<div data-source="electronhub">
<span data-i18n="Max prompt cost:">Max prompt cost:</span> <span id="electronhub_max_prompt_cost" data-i18n="Unknown">Unknown</span>
</div>
<hr>
<div class="range-block">
<label for="stream_toggle" title="Enable OpenAI completion streaming" data-i18n="[title]Enable OpenAI completion streaming" class="checkbox_label widthFreeExpand">
@@ -1463,12 +1465,10 @@
</div>
</div>
<div class="range-block marginTop5" title="Tokens across which sequence matching is not continued. Specified as a comma-separated list of quoted strings." data-i18n="[title]DRY_Sequence_Breakers_desc">
<div class="range-block-title textAlignCenter">
<div class="range-block-title textAlignCenter flex-container justifyCenter alignitemscenter">
<small data-i18n="Sequence Breakers">Sequence Breakers</small>
</div>
<div class="wide100p">
<textarea id="dry_sequence_breakers_textgenerationwebui" class="text_pole textarea_compact" name="sequence_breakers" rows="3" data-i18n="[placeholder]JSON-serialized array of strings." placeholder="JSON-serialized array of strings."></textarea>
</div>
<textarea id="dry_sequence_breakers_textgenerationwebui" class="text_pole textarea_compact" name="sequence_breakers" rows="3" data-i18n="[placeholder]JSON-serialized array of strings." placeholder="JSON-serialized array of strings."></textarea>
</div>
</div>
<div data-tg-type="ooba, mancer, koboldcpp, tabby, llamacpp, aphrodite" id="dynatemp_block_ooba" class="wide100p">
@@ -1502,7 +1502,7 @@
<div data-tg-type="ooba,infermaticai,koboldcpp,llamacpp,tabby" id="mirostat_block_ooba" class="wide100p">
<h4 class="wide100p textAlignCenter">
<label data-i18n="Mirostat (mode=1 is only for llama.cpp)">Mirostat</label>
<div class=" fa-solid fa-circle-info opacity50p " data-i18n="[title]Mirostat_desc" title="Mirostat is a thermostat for output perplexity.&#13;Mirostat matches the output perplexity to that of the input, thus avoiding the repetition trap&#13;(where, as the autoregressive inference produces text, the perplexity of the output tends toward zero)&#13;and the confusion trap (where the perplexity diverges).&#13;For details, see the paper Mirostat: A Neural Text Decoding Algorithm that Directly Controls Perplexity by Basu et al. (2020).&#13;Mode chooses the Mirostat version. 0=disable, 1=Mirostat 1.0 (llama.cpp only), 2=Mirostat 2.0."></div>
<div class=" fa-solid fa-circle-info opacity50p " data-i18n="[title]Mirostat_desc" title="Mirostat is a thermostat for output perplexity.&#13;Mirostat matches the output perplexity to that of the input, thus avoiding the repetition trap&#13;(where, as the autoregressive inference produces text, the perplexity of the output tends toward zero)&#13;and the confusion trap (where the perplexity diverges).&#13;For details, see the paper Mirostat: A Neural Text Decoding Algorithm that Directly Controls Perplexity by Basu et al. (2020).&#13;Mode chooses the Mirostat version. 0=disable, 1=Mirostat 1.0 (llama.cpp only), 2=Mirostat 2.0.&#13;Tau = Variability parameter for Mirostat outputs.&#13;Eta = Learning rate of Mirostat."></div>
</h4>
<div class="flex-container flexFlowRow gap10px flexShrink">
<div class="alignitemscenter flex-container marginBot5 flexFlowColumn flexGrow flexShrink gap0">
@@ -1511,18 +1511,12 @@
<input class="neo-range-input" type="number" min="0" max="2" step="1" data-for="mirostat_mode_textgenerationwebui" id="mirostat_mode_counter_textgenerationwebui">
</div>
<div class="alignitemscenter flex-container marginBot5 flexFlowColumn flexGrow flexShrink gap0">
<label>
<small data-i18n="Mirostat Tau">Tau</small>
<div class="fa-solid fa-circle-info opacity50p" data-i18n="[title]Variability parameter for Mirostat outputs" title="Variability parameter for Mirostat outputs."></div>
</label>
<small data-i18n="Mirostat Tau">Tau</small>
<input class="neo-range-slider" type="range" id="mirostat_tau_textgenerationwebui" name="volume" min="0" max="20" step="0.01" />
<input class="neo-range-input" type="number" min="0" max="20" step="0.01" data-for="mirostat_tau_textgenerationwebui" id="mirostat_tau_counter_textgenerationwebui">
</div>
<div class="alignitemscenter flex-container marginBot5 flexFlowColumn flexGrow flexShrink gap0">
<label>
<small data-i18n="Mirostat Eta">Eta</small>
<div class="fa-solid fa-circle-info opacity50p" data-i18n="[title]Learning rate of Mirostat" title="Learning rate of Mirostat."></div>
</label>
<small data-i18n="Mirostat Eta">Eta</small>
<input class="neo-range-slider" type="range" id="mirostat_eta_textgenerationwebui" name="volume" min="0" max="1" step="0.01" />
<input class="neo-range-input" type="number" min="0" max="1" step="0.01" data-for="mirostat_eta_textgenerationwebui" id="mirostat_eta_counter_textgenerationwebui">
</div>
@@ -1583,17 +1577,13 @@
</label>
<label data-tg-type="ooba, tabby" class="checkbox_label flexGrow flexShrink" for="add_bos_token_textgenerationwebui">
<input type="checkbox" id="add_bos_token_textgenerationwebui" />
<label>
<small data-i18n="Add BOS Token">Add BOS Token</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative" title="Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative."></div>
</label>
<small data-i18n="Add BOS Token">Add BOS Token</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative" title="Add the bos_token to the beginning of prompts. Disabling this can make the replies more creative."></div>
</label>
<label data-tg-type="ooba, llamacpp, tabby, koboldcpp, dreamgen" class="checkbox_label flexGrow flexShrink" for="ban_eos_token_textgenerationwebui">
<input type="checkbox" id="ban_eos_token_textgenerationwebui" />
<label>
<small data-i18n="Ban EOS Token">Ban EOS Token</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Ban the eos_token. This forces the model to never end the generation prematurely" title="Ban the eos_token. This forces the model to never end the generation prematurely."></div>
</label>
<small data-i18n="Ban EOS Token">Ban EOS Token</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Ban the eos_token. This forces the model to never end the generation prematurely" title="Ban the eos_token. This forces the model to never end the generation prematurely."></div>
</label>
<label data-tg-type="vllm, aphrodite, infermaticai" class="checkbox_label" for="ignore_eos_token_textgenerationwebui">
<input type="checkbox" id="ignore_eos_token_textgenerationwebui" />
@@ -1610,19 +1600,14 @@
</label>
<label data-tg-type="ooba, aphrodite, tabby" class="checkbox_label flexGrow flexShrink" for="temperature_last_textgenerationwebui">
<input type="checkbox" id="temperature_last_textgenerationwebui" />
<label>
<small data-i18n="Temperature Last">Temperature Last</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Temperature_Last_desc" title="Use the temperature sampler last. This is almost always the sensible thing to do.&#13;When enabled: sample the set of plausible tokens first, then apply temperature to adjust their relative probabilities (technically, logits).&#13;When disabled: apply temperature to adjust the relative probabilities of ALL tokens first, then sample plausible tokens from that.&#13;Disabling Temperature Last boosts the probabilities in the tail of the distribution, which tends to amplify the chances of getting an incoherent response."></div>
</label>
<small data-i18n="Temperature Last">Temperature Last</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Temperature_Last_desc" title="Use the temperature sampler last. This is almost always the sensible thing to do.&#13;When enabled: sample the set of plausible tokens first, then apply temperature to adjust their relative probabilities (technically, logits).&#13;When disabled: apply temperature to adjust the relative probabilities of ALL tokens first, then sample plausible tokens from that.&#13;Disabling Temperature Last boosts the probabilities in the tail of the distribution, which tends to amplify the chances of getting an incoherent response."></div>
</label>
<label data-tg-type="tabby" class="checkbox_label flexGrow flexShrink" for="speculative_ngram_textgenerationwebui">
<input type="checkbox" id="speculative_ngram_textgenerationwebui" />
<label>
<small data-i18n="Speculative Ngram">Speculative Ngram</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Use a different speculative decoding method without a draft model" title="Use a different speculative decoding method without a draft model.&#13;Using a draft model is preferred. Speculative ngram is not as effective."></div>
</label>
<small data-i18n="Speculative Ngram">Speculative Ngram</small>
<div class="fa-solid fa-circle-info opacity50p " data-i18n="[title]Use a different speculative decoding method without a draft model" title="Use a different speculative decoding method without a draft model.&#13;Using a draft model is preferred. Speculative ngram is not as effective."></div>
</label>
<label data-tg-type="vllm, aphrodite, infermaticai" class="checkbox_label" for="spaces_between_special_tokens_textgenerationwebui">
<input type="checkbox" id="spaces_between_special_tokens_textgenerationwebui" />
<small data-i18n="Spaces Between Special Tokens">Spaces Between Special Tokens</small>
@@ -1663,9 +1648,11 @@
</div>
</div>
</div>
<div class="range-block wide100p">
<div class="range-block wide100p" id="logit_bias_block_ooba">
<div id="logit_bias_textgenerationwebui" class="range-block-title title_restorable">
<strong data-i18n="Logit Bias">Logit Bias</strong>
<h4>
<span data-i18n="Logit Bias">Logit Bias</span>
</h4>
<div id="textgen_logit_bias_new_entry" class="menu_button menu_button_icon">
<i class="fa-xs fa-solid fa-plus"></i>
<small data-i18n="Add">Add</small>
@@ -1678,7 +1665,7 @@
<div class="logit_bias_list"></div>
</div>
</div>
<div id="cfg_block_ooba" data-tg-type="ooba, tabby" class="wide100p">
<div id="cfg_block_ooba" data-tg-type="ooba, tabby" class="flex-container flexFlowColumn wide100p">
<hr class="width100p">
<h4 class="textAlignCenter">
<span data-i18n="CFG">CFG</span>
@@ -1690,29 +1677,23 @@
<input class="neo-range-input" type="number" min="0.1" max="4" step="0.05" data-for="guidance_scale_textgenerationwebui" id="guidance_scale_counter_textgenerationwebui">
</div>
<div class="range-block">
<div class="range-block-title justifyLeft">
<span data-i18n="Negative Prompt">Negative Prompt</span>
<small>
<div class="fa-solid fa-circle-info opacity50p" data-i18n="[title]Used if CFG Scale is unset globally, per chat or character" title="Used if CFG Scale is unset globally, per chat or character"></div>
</small>
</div>
<div class="wide100p">
<textarea id="negative_prompt_textgenerationwebui" class="text_pole textarea_compact" name="negative_prompt" rows="3" data-i18n="[placeholder]Add text here that would make the AI generate things you don't want in your outputs." placeholder="Add text here that would make the AI generate things you don't want in your outputs."></textarea>
<div class="alignitemscenter justifyCenter flex-container flexShrink">
<small data-i18n="Negative Prompt">Negative Prompt</small>
<div class="fa-solid fa-circle-info opacity50p" data-i18n="[title]Used if CFG Scale is unset globally, per chat or character" title="Used if CFG Scale is unset globally, per chat or character"></div>
</div>
<textarea id="negative_prompt_textgenerationwebui" class="wide100p text_pole textarea_compact" name="negative_prompt" rows="3" data-i18n="[placeholder]Add text here that would make the AI generate things you don't want in your outputs." placeholder="Add text here that would make the AI generate things you don't want in your outputs."></textarea>
</div>
</div>
<div id="grammar_block_ooba" data-tg-type="ooba,aphrodite" class="wide100p">
<div id="grammar_block_ooba" data-tg-type="ooba,aphrodite,tabby" class="wide100p">
<hr class="wide100p">
<h4 class="wide100p textAlignCenter">
<label>
<div class="flex-container justifyCenter alignitemscenter">
<span data-i18n="Grammar String">Grammar String</span>
<div class="margin5 fa-solid fa-circle-info opacity50p " data-i18n="[title]GBNF or EBNF, depends on the backend in use. If you're using this you should know which." title="GBNF or EBNF, depends on the backend in use. If you're using this you should know which."></div>
<a href="https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md" target="_blank">
<small>
<div class="fa-solid fa-up-right-from-square note-link-span"></div>
</small>
<div class="fa-solid fa-up-right-from-square note-link-span"></div>
</a>
</label>
</div>
</h4>
<textarea id="grammar_string_textgenerationwebui" rows="4" class="text_pole textarea_compact monospace" data-i18n="[placeholder]Type in the desired custom grammar" placeholder="Type in the desired custom grammar"></textarea>
</div>
@@ -2077,7 +2058,7 @@
</span>
</div>
</div>
<div class="range-block" data-source="deepseek,aimlapi,openrouter,custom,claude,xai,makersuite,vertexai,pollinations,moonshot,mistralai,fireworks,cometapi,electronhub,azure_openai">
<div class="range-block" data-source="deepseek,aimlapi,openrouter,custom,claude,xai,makersuite,vertexai,pollinations,moonshot,mistralai,fireworks,cometapi,electronhub,azure_openai,nanogpt">
<label for="openai_show_thoughts" class="checkbox_label widthFreeExpand">
<input id="openai_show_thoughts" type="checkbox" />
<span data-i18n="Request model reasoning">Request model reasoning</span>
@@ -2144,7 +2125,7 @@
</div>
</div>
</div>
<div class="range-block m-t-1" data-source="openai,aimlapi,openrouter,custom,azure_openai">
<div class="range-block m-t-1" data-source="openai,aimlapi,openrouter,custom,electronhub,azure_openai">
<div id="logit_bias_openai" class="range-block-title openai_restorable" data-i18n="Logit Bias">
Logit Bias
</div>
@@ -3035,6 +3016,10 @@
<h4 data-i18n="Claude Model">Claude Model</h4>
<select id="model_claude_select">
<optgroup label="Versions">
<option value="claude-sonnet-4-5">claude-sonnet-4-5</option>
<option value="claude-sonnet-4-5-20250929">claude-sonnet-4-5-20250929</option>
<option value="claude-haiku-4-5">claude-haiku-4-5</option>
<option value="claude-haiku-4-5-20251001">claude-haiku-4-5-20251001</option>
<option value="claude-opus-4-1">claude-opus-4-1</option>
<option value="claude-opus-4-1-20250805">claude-opus-4-1-20250805</option>
<option value="claude-opus-4-0">claude-opus-4-0</option>
@@ -3082,7 +3067,7 @@
<div class="marginTopBot5">
<div class="inline-drawer wide100p">
<div class="inline-drawer-toggle inline-drawer-header">
<b data-i18n="Model Order">OpenRouter Model Sorting</b>
<b data-i18n="OpenRouter Model Sorting">OpenRouter Model Sorting</b>
<div class="fa-solid fa-circle-chevron-down inline-drawer-icon down"></div>
</div>
<div class="inline-drawer-content m-b-1">
@@ -3174,46 +3159,32 @@
<option value="gemini-2.5-pro-preview-06-05">gemini-2.5-pro-preview-06-05</option>
<option value="gemini-2.5-pro-preview-05-06">gemini-2.5-pro-preview-05-06</option>
<option value="gemini-2.5-pro-preview-03-25">gemini-2.5-pro-preview-03-25</option>
<option value="gemini-2.5-pro-exp-03-25">gemini-2.5-pro-exp-03-25</option>
<option value="gemini-2.5-flash">gemini-2.5-flash</option>
<option value="gemini-2.5-flash-preview-09-2025">gemini-2.5-flash-preview-09-2025</option>
<option value="gemini-2.5-flash-preview-05-20">gemini-2.5-flash-preview-05-20</option>
<option value="gemini-2.5-flash-preview-04-17">gemini-2.5-flash-preview-04-17</option>
<option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
<option value="gemini-2.5-flash-lite-preview-09-2025">gemini-2.5-flash-lite-preview-09-2025</option>
<option value="gemini-2.5-flash-lite-preview-06-17">gemini-2.5-flash-lite-preview-06-17</option>
<option value="gemini-2.5-flash-image">gemini-2.5-flash-image</option>
<option value="gemini-2.5-flash-image-preview">gemini-2.5-flash-image-preview</option>
</optgroup>
<optgroup label="Gemini 2.0">
<option value="gemini-2.0-pro-exp-02-05">gemini-2.0-pro-exp-02-05 → 2.5-pro-exp-03-25</option>
<option value="gemini-2.0-pro-exp">gemini-2.0-pro-exp → 2.5-pro-exp-03-25</option>
<option value="gemini-exp-1206">gemini-exp-1206 → 2.5-pro-exp-03-25</option>
<option value="gemini-2.0-pro-exp-02-05">gemini-2.0-pro-exp-02-05 → 2.5-exp-03-25</option>
<option value="gemini-2.0-pro-exp">gemini-2.0-pro-exp → 2.5-exp-03-25</option>
<option value="gemini-exp-1206">gemini-exp-1206 → 2.5-exp-03-25</option>
<option value="gemini-2.0-flash-001">gemini-2.0-flash-001</option>
<option value="gemini-2.0-flash-exp-image-generation">gemini-2.0-flash-exp-image-generation</option>
<option value="gemini-2.0-flash-preview-image-generation">gemini-2.0-flash-preview-image-generation</option>
<option value="gemini-2.0-flash-exp">gemini-2.0-flash-exp</option>
<option value="gemini-2.0-flash">gemini-2.0-flash</option>
<option value="gemini-2.0-flash-thinking-exp-01-21">gemini-2.0-flash-thinking-exp-01-21 → 2.5-flash-preview-04-17</option>
<option value="gemini-2.0-flash-thinking-exp-1219">gemini-2.0-flash-thinking-exp-1219 → 2.5-flash-preview-04-17</option>
<option value="gemini-2.0-flash-thinking-exp">gemini-2.0-flash-thinking-exp → 2.5-flash-preview-04-17</option>
<option value="gemini-2.0-flash-thinking-exp-01-21">gemini-2.0-flash-thinking-exp-01-21 → 2.5-flash-preview-05-20</option>
<option value="gemini-2.0-flash-thinking-exp-1219">gemini-2.0-flash-thinking-exp-1219 → 2.5-flash-preview-05-20</option>
<option value="gemini-2.0-flash-thinking-exp">gemini-2.0-flash-thinking-exp → 2.5-flash-preview-05-20</option>
<option value="gemini-2.0-flash-lite-001">gemini-2.0-flash-lite-001</option>
<option value="gemini-2.0-flash-lite-preview-02-05">gemini-2.0-flash-lite-preview-02-05</option>
<option value="gemini-2.0-flash-lite-preview">gemini-2.0-flash-lite-preview</option>
<option value="gemini-2.0-flash-lite">gemini-2.0-flash-lite</option>
</optgroup>
<optgroup label="Gemini 1.5">
<option value="gemini-1.5-pro-latest">gemini-1.5-pro-latest</option>
<option value="gemini-1.5-pro-002">gemini-1.5-pro-002</option>
<option value="gemini-1.5-pro-001">gemini-1.5-pro-001</option>
<option value="gemini-1.5-pro">gemini-1.5-pro</option>
<option value="gemini-1.5-flash-latest">gemini-1.5-flash-latest</option>
<option value="gemini-1.5-flash-002">gemini-1.5-flash-002</option>
<option value="gemini-1.5-flash-001">gemini-1.5-flash-001</option>
<option value="gemini-1.5-flash">gemini-1.5-flash</option>
<option value="gemini-1.5-flash-8b-latest">gemini-1.5-flash-8b-latest</option>
<option value="gemini-1.5-flash-8b-001">gemini-1.5-flash-8b-001</option>
<option value="gemini-1.5-flash-8b-exp-0924">gemini-1.5-flash-8b-exp-0924</option>
<option value="gemini-1.5-flash-8b-exp-0827">gemini-1.5-flash-8b-exp-0827</option>
<option value="gemini-1.5-flash-8b">gemini-1.5-flash-8b</option>
</optgroup>
<optgroup label="Gemma">
<option value="gemma-3n-e4b-it">gemma-3n-e4b-it</option>
<option value="gemma-3n-e2b-it">gemma-3n-e2b-it</option>
@@ -3225,6 +3196,9 @@
<optgroup label="LearnLM">
<option value="learnlm-2.0-flash-experimental">learnlm-2.0-flash-experimental</option>
</optgroup>
<optgroup label="Robotics-ER">
<option value="gemini-robotics-er-1.5-preview">gemini-robotics-er-1.5-preview</option>
</optgroup>
<optgroup id="google_other_models" label="Other"></optgroup>
</select>
</div>
@@ -3350,15 +3324,9 @@
<!-- data-mode="full" is for models that require a service account -->
<optgroup label="Gemini 2.5">
<option value="gemini-2.5-pro">gemini-2.5-pro</option>
<option value="gemini-2.5-pro-preview-06-05">gemini-2.5-pro-preview-06-05</option>
<option value="gemini-2.5-pro-preview-05-06">gemini-2.5-pro-preview-05-06</option>
<option value="gemini-2.5-pro-preview-03-25">gemini-2.5-pro-preview-03-25</option>
<option value="gemini-2.5-pro-exp-03-25" data-mode="full">gemini-2.5-pro-exp-03-25</option>
<option value="gemini-2.5-flash">gemini-2.5-flash</option>
<option value="gemini-2.5-flash-preview-05-20">gemini-2.5-flash-preview-05-20</option>
<option value="gemini-2.5-flash-preview-04-17">gemini-2.5-flash-preview-04-17</option>
<option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
<option value="gemini-2.5-flash-lite-preview-06-17">gemini-2.5-flash-lite-preview-06-17</option>
<option value="gemini-2.5-flash-image">gemini-2.5-flash-image</option>
<option value="gemini-2.5-flash-image-preview">gemini-2.5-flash-image-preview</option>
</optgroup>
<optgroup label="Gemini 2.0">
@@ -3383,67 +3351,7 @@
<div>
<h4 data-i18n="MistralAI Model">MistralAI Model</h4>
<select id="model_mistralai_select">
<optgroup label="Latest">
<option value="open-mistral-nemo">open-mistral-nemo</option>
<option value="open-mistral-7b">open-mistral-7b</option>
<option value="open-mixtral-8x7b">open-mixtral-8x7b</option>
<option value="open-mixtral-8x22b">open-mixtral-8x22b</option>
<option value="open-codestral-mamba">open-codestral-mamba</option>
<option value="ministral-3b-latest">ministral-3b-latest</option>
<option value="ministral-8b-latest">ministral-8b-latest</option>
<option value="mistral-tiny-latest">mistral-tiny-latest</option>
<option value="mistral-small-latest">mistral-small-latest</option>
<option value="mistral-medium-latest">mistral-medium-latest</option>
<option value="mistral-large-latest">mistral-large-latest</option>
<option value="mistral-saba-latest">mistral-saba-latest</option>
<option value="codestral-latest">codestral-latest</option>
<option value="codestral-mamba-latest">codestral-mamba-latest</option>
<option value="pixtral-12b-latest">pixtral-12b-latest</option>
<option value="pixtral-large-latest">pixtral-large-latest</option>
<option value="devstral-small-latest">devstral-small-latest</option>
<option value="devstral-medium-latest">devstral-medium-latest</option>
<option value="magistral-small-latest">magistral-small-latest</option>
<option value="magistral-medium-latest">magistral-medium-latest</option>
</optgroup>
<optgroup label="Sub-versions">
<option value="open-mistral-nemo-2407">open-mistral-nemo-2407</option>
<option value="open-mixtral-8x22b-2404">open-mixtral-8x22b-2404</option>
<option value="ministral-3b-2410">ministral-3b-2410</option>
<option value="ministral-8b-2410">ministral-8b-2410</option>
<option value="mistral-tiny-2312">mistral-tiny-2312</option>
<option value="mistral-tiny-2407">mistral-tiny-2407</option>
<option value="mistral-small-2312">mistral-small-2312</option>
<option value="mistral-small-2402">mistral-small-2402</option>
<option value="mistral-small-2409">mistral-small-2409</option>
<option value="mistral-small-2501">mistral-small-2501</option>
<option value="mistral-small-2503">mistral-small-2503</option>
<option value="mistral-small-2506">mistral-small-2506</option>
<option value="mistral-medium-2312">mistral-medium-2312</option>
<option value="mistral-medium-2505">mistral-medium-2505</option>
<option value="mistral-medium-2508">mistral-medium-2508</option>
<option value="mistral-large-2402">mistral-large-2402</option>
<option value="mistral-large-2407">mistral-large-2407</option>
<option value="mistral-large-2411">mistral-large-2411</option>
<option value="mistral-large-pixtral-2411">mistral-large-pixtral-2411</option>
<option value="mistral-saba-2502">mistral-saba-2502</option>
<option value="codestral-2405">codestral-2405</option>
<option value="codestral-2405-blue">codestral-2405-blue</option>
<option value="codestral-mamba-2407">codestral-mamba-2407</option>
<option value="codestral-2411-rc5">codestral-2411-rc5</option>
<option value="codestral-2412">codestral-2412</option>
<option value="codestral-2501">codestral-2501</option>
<option value="codestral-2508">codestral-2508</option>
<option value="pixtral-12b-2409">pixtral-12b-2409</option>
<option value="pixtral-large-2411">pixtral-large-2411</option>
<option value="devstral-small-2505">devstral-small-2505</option>
<option value="devstral-small-2507">devstral-small-2507</option>
<option value="devstral-medium-2507">devstral-medium-2507</option>
<option value="magistral-small-2506">magistral-small-2506</option>
<option value="magistral-medium-2506">magistral-medium-2506</option>
<option value="magistral-small-2507">magistral-small-2507</option>
<option value="magistral-medium-2507">magistral-medium-2507</option>
</optgroup>
<optgroup id="mistralai_other_models" label="Other"></optgroup>
<option data-i18n="-- Connect to the API --" value="">-- Connect to the API --</option>
</select>
</div>
</form>
@@ -3473,6 +3381,9 @@
</div>
<div id="electronhub_form" data-source="electronhub">
<h4 data-i18n="Electron Hub API Key">Electron Hub API Key</h4>
<div>
<a href="https://playground.electronhub.ai/console" target="_blank" data-i18n="View Remaining Credits">View Remaining Credits</a>
</div>
<div class="flex-container">
<input id="api_key_electronhub" name="api_key_electronhub" class="text_pole flex1" value="" type="text" autocomplete="off">
<div title="Manage API keys" data-i18n="[title]Manage API keys" class="menu_button fa-solid fa-key fa-fw manage-api-keys" data-key="api_key_electronhub"></div>
@@ -3480,10 +3391,43 @@
<div data-for="api_key_electronhub" class="neutral_warning" data-i18n="For privacy reasons, your API key will be hidden after you click 'Connect'.">
For privacy reasons, your API key will be hidden after you click 'Connect'.
</div>
<h4 data-i18n="Electron Hub Model">Electron Hub Model</h4>
<select id="model_electronhub_select">
<option value="" data-i18n="-- Connect to the API --">-- Connect to the API --</option>
</select>
<div>
<h4 data-i18n="Electron Hub Model">Electron Hub Model</h4>
<select id="model_electronhub_select">
<option value="" data-i18n="-- Connect to the API --">-- Connect to the API --</option>
</select>
</div>
<div class="marginTopBot5">
<div class="inline-drawer wide100p">
<div class="inline-drawer-toggle inline-drawer-header">
<b data-i18n="Electron Hub Model Sorting">Electron Hub Model Sorting</b>
<div class="fa-solid fa-circle-chevron-down inline-drawer-icon down"></div>
</div>
<div class="inline-drawer-content m-b-1">
<div class="marginTopBot5">
<label for="electronhub_sort_models" class="checkbox_label">
<select id="electronhub_sort_models">
<option data-i18n="Alphabetically" value="alphabetically">Alphabetically</option>
<option data-i18n="Input Price" value="pricing.input">Input Price (cheapest)</option>
<option data-i18n="Output Price" value="pricing.output">Output Price (cheapest)</option>
<option data-i18n="Context Size" value="context_length">Context Size</option>
</select>
</label>
</div>
<div class="marginTopBot5">
<label for="electronhub_group_models" class="checkbox_label">
<input id="electronhub_group_models" type="checkbox" />
<span data-i18n="Group by vendors">Group by vendors</span>
</label>
<div class="toggle-description justifyLeft wide100p">
<span data-i18n="Group by vendors Description">
Put OpenAI models in one group, Anthropic models in other group, etc. Can be combined with sorting.
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="nanogpt_form" data-source="nanogpt">
<h4 data-i18n="NanoGPT API Key">NanoGPT API Key</h4>
@@ -3666,18 +3610,12 @@
<div data-for="api_key_xai" class="neutral_warning" data-i18n="For privacy reasons, your API key will be hidden after you click 'Connect'.">
For privacy reasons, your API key will be hidden after you click 'Connect'.
</div>
<h4 data-i18n="xAI Model">xAI Model</h4>
<select id="model_xai_select">
<option value="grok-4-0709">grok-4-0709</option>
<option value="grok-3-beta">grok-3-beta</option>
<option value="grok-3-fast-beta">grok-3-fast-beta</option>
<option value="grok-3-mini-beta">grok-3-mini-beta</option>
<option value="grok-3-mini-fast-beta">grok-3-mini-fast-beta</option>
<option value="grok-2-vision-1212">grok-2-vision-1212</option>
<option value="grok-2-1212">grok-2-1212</option>
<option value="grok-vision-beta">grok-vision-beta</option>
<option value="grok-beta">grok-beta</option>
</select>
<div>
<h4 data-i18n="xAI Model">xAI Model</h4>
<select id="model_xai_select">
<option value="" data-i18n="-- Connect to the API --">-- Connect to the API --</option>
</select>
</div>
</div>
<div id="aimlapi_form" data-source="aimlapi">
<h4>
@@ -4279,7 +4217,7 @@
Token Padding
</small>
</div>
<input id="token_padding" class="text_pole textarea_compact" type="number" min="-2048" max="2048" />
<input id="token_padding" class="text_pole textarea_compact" type="number" min="-2048" max="2048" step="1" />
</div>
</div>
<div>
@@ -4959,7 +4897,6 @@
<small data-i18n="Smooth Streaming">
Smooth Streaming
</small>
<i class="fa-solid fa-flask" data-i18n="[title]Experimental feature. May not work for all backends." title="Experimental feature. May not work for all backends."></i>
</div>
<div id="smooth_streaming_speed_control" class="flexBasis100p wide100p">
<input type="range" id="smooth_streaming_speed" name="smooth_streaming_speed" min="0" max="100" step="10" value="50">
@@ -4970,6 +4907,11 @@
</div>
</div>
</label>
<label class="checkbox_label" for="stream_fade_in" title="Fade in streamed text when it appears, instead of it just popping in." data-i18n="[title]Fade in streamed text when it appears, instead of it just popping in">
<input id="stream_fade_in" type="checkbox" />
<small data-i18n="Stream Fade-In">Stream Fade-In</small>
<i class="fa-solid fa-flask" data-i18n="[title]Experimental feature. May not work for all backends." title="Experimental feature. May not work for all backends."></i>
</label>
<label for="play_message_sound" class="checkbox_label" title="Play a sound when a message generation finishes." data-i18n="[title]Play a sound when a message generation finishes">
<input id="play_message_sound" type="checkbox" />
@@ -5339,15 +5281,18 @@
</div>
</div>
</div>
<div id="logo_block" class="drawer">
<div id="site_logo" class="drawer-toggle drawer-header" title="Change Background Image" data-i18n="[title]Change Background Image">
<div id="backgrounds-button" class="drawer">
<div id="backgrounds-drawer-toggle" class="drawer-toggle drawer-header" title="Change Background Image" data-i18n="[title]Change Background Image">
<div class="drawer-icon fa-solid fa-panorama fa-fw closedIcon"></div>
</div>
<div id="Backgrounds" class="drawer-content closedDrawer bg-drawer-layout">
<div id="bg-header-fixed">
<div class="flex-container alignItemsBaseline wide100p">
<h3 id="bg-header-title" class="margin0" data-i18n="Backgrounds">Backgrounds</h3>
<input id="bg-filter" class="text_pole flex1" type="search" data-i18n="[placeholder]Search" placeholder="Search" />
<div class="bg-header-row-1">
<label for="add_bg_button" id="add_background_button_top" class="menu_button menu_button_icon" data-i18n="[title]Add a new background" title="Add a new background">
<i class="fa-solid fa-plus"></i>
<span data-i18n="Add Background">Add Background</span>
</label>
<span class="expander"></span>
<select id="background_fitting" class="text_pole" data-i18n="[title]Background Fitting" title="Background Fitting">
<option value="classic" data-i18n="Classic">Classic</option>
<option value="cover" data-i18n="Cover">Cover</option>
@@ -5359,16 +5304,25 @@
<i class="fa-solid fa-wand-magic"></i>
<span data-i18n="Auto-select">Auto-select</span>
</div>
<label for="add_bg_button" id="add_background_button_top" class="menu_button menu_button_icon interactable" title="Add a new background">
<i class="fa-solid fa-plus"></i>
<span data-i18n="Add Background">Add Background</span>
</label>
</div>
<div class="bg-header-row-2">
<input id="bg-filter" class="text_pole" type="search" data-i18n="[placeholder]Search..." placeholder="Search..." />
</div>
</div>
<div id="bg-scrollable-content">
<h3 data-i18n="System Backgrounds" class="wide100p textAlignCenter">
System Backgrounds
</h3>
<div class="heading-container-with-controls">
<h3 data-i18n="System Backgrounds" class="wide100p textAlignCenter heading-text">
System Backgrounds
</h3>
<div class="heading-controls">
<button id="bg_thumb_zoom_out" class="menu_button menu_button_icon" title="Make thumbnails smaller" data-i18n="[title]Make thumbnails smaller">
<i class="fa-solid fa-minus"></i>
</button>
<button id="bg_thumb_zoom_in" class="menu_button menu_button_icon" title="Make thumbnails larger" data-i18n="[title]Make thumbnails larger">
<i class="fa-solid fa-plus"></i>
</button>
</div>
</div>
<div id="bg_menu_content" class="bg_list">
</div>
<h3 data-i18n="Chat Backgrounds" class="wide100p textAlignCenter">
@@ -5381,8 +5335,11 @@
</div>
</div>
<form id="form_bg_upload" style="display: none;">
<input type="file" id="add_bg_button" name="avatar" accept="image/jpeg,image/png,image/gif,image/bmp,image/svg+xml,video/*">
<input type="file" id="add_bg_button" name="avatar" accept="image/jpeg,image/png,image/gif,image/bmp,image/svg+xml,video/*">
</form>
<button id="bg-scroll-top" type="button" class="menu_button menu_button_icon" title="Scroll backgrounds to top" data-i18n="[title]Scroll backgrounds to top">
<i class="fa-solid fa-chevron-up" aria-hidden="true"></i>
</button>
</div>
</div>
<div id="extensions-settings-button" class="drawer">
@@ -5540,7 +5497,10 @@
</div>
</div>
<h4 data-i18n="Persona Description">Persona Description</h4>
<h4 class="flex-container alignItemsBaseline">
<span data-i18n="Persona Description">Persona Description</span>
<i class="editor_maximize fa-solid fa-maximize right_menu_button" data-for="persona_description" title="Expand the editor" data-i18n="[title]Expand the editor"></i>
</h4>
<textarea id="persona_description" name="persona_description" data-i18n="[placeholder]Example: [{{user}} is a 28-year-old Romanian cat girl.]" placeholder="Example:&#10;[{{user}} is a 28-year-old Romanian cat girl.]" class="text_pole textarea_compact" value="" autocomplete="off" rows="8"></textarea>
<div class="flex-container justifySpaceBetween">
@@ -6291,7 +6251,7 @@
<div name="selectChatPopupHeader" class="flex-container alignitemscenter justifySpaceBetween flexGap10">
<div id="select_chat_import"> <!-- import chat popup header -->
<form id="form_import_chat" action="javascript:void(null);" method="post" enctype="multipart/form-data" style="display: none;">
<input type="file" id="chat_import_file" accept=".json, .jsonl" name="avatar">
<input type="file" id="chat_import_file" accept=".json, .jsonl" multiple name="avatar">
<input id="chat_import_file_type" name="file_type" class="text_pole" value="" autocomplete="off" style="display: none;">
<input id="chat_import_avatar_url" name="avatar_url" class="text_pole" value="" autocomplete="off" style="display: none;">
<input id="chat_import_character_name" name="character_name" class="text_pole" value="" autocomplete="off" style="display: none;">
@@ -6322,10 +6282,9 @@
<i class="fa-solid fa-ellipsis-vertical"></i>
</div>
<div class="jg-menu">
<div data-action="copy" class="jg-button jg-copy fa-solid fa-file-arrow-up" data-i18n="[title]Copy to system backgrounds" title="Copy to system backgrounds"></div>
<!-- temporarily moved lock icon here (will be moved to header) -->
<div data-action="lock" class="jg-button jg-lock fa-solid fa-lock fa-fw pointer" data-i18n="[title]Lock" title="Lock"></div>
<div data-action="unlock" class="jg-button jg-unlock fa-solid fa-lock-open fa-fw pointer" data-i18n="[title]Unlock" title="Unlock"></div>
<div data-action="copy" class="jg-button jg-copy fa-solid fa-file-arrow-up" data-i18n="[title]Copy to system backgrounds" title="Copy to system backgrounds"></div>
<div data-action="edit" class="jg-button jg-edit fa-solid fa-pen-to-square fa-fw pointer" data-i18n="[title]Rename Background" title="Rename Background"></div>
<div data-action="delete" class="jg-button jg-delete fa-solid fa-trash-can fa-fw pointer" data-i18n="[title]Delete Background" title="Delete Background"></div>
</div>
@@ -6448,6 +6407,13 @@
</div>
</div>
<div name="perEntryOverridesBlock" class="flex-container wide100p alignitemscenter">
<div class="world_entry_form_control flex1" title="Set the outlet name for this WI entry.&#10;&#10;WI entries with position 'outlet' will not be added to the prompt automatically. Instead, they will be collected and can be used as a macro in the prompt.&#10;Add {{outlet::YourName}} to the prompt in any place you want to add all WI entries this specific outlet." data-i18n="[title]wi_outlet_name">
<small class="textAlignCenter">
<span data-i18n="Outlet Name">Outlet Name</span>
<div class="fa-solid fa-circle-info opacity50p"></div>
</small>
<input class="text_pole margin0" name="outletName" type="text" placeholder="Outlet Name" data-i18n="[placeholder]Outlet Name">
</div>
<div class="world_entry_form_control flex1">
<small class="textAlignCenter" data-i18n="Scan Depth">Scan Depth</small>
<input class="text_pole margin0" name="scanDepth" type="number" placeholder="Use global setting" data-i18n="[placeholder]Use global setting" max="1000">
@@ -6785,6 +6751,9 @@
<option value="4" data-role="2" data-i18n="at Depth AI">
@D 🤖
</option>
<option value="7" data-role="" data-i18n="Outlet">
➡️ Outlet
</option>
</select>
</div>
<div class="world_entry_form_control wi-enter-footer-text flex-container flexNoGap">
+69 -3
View File
@@ -139,9 +139,9 @@
return el;
},
getPageLinkTag: function(index) {
getPageLinkTag: function(text) {
var pageLink = attributes.pageLink;
return pageLink ? `<a href="${pageLink}">${index}</a>` : `<a>${index}</a>`;
return pageLink ? `<a href="${pageLink}">${text}</a>` : `<a>${text}</a>`;
},
// Generate HTML for page numbers
@@ -233,6 +233,8 @@
var prevText = attributes.prevText;
var nextText = attributes.nextText;
var firstText = attributes.firstText;
var lastText = attributes.lastText;
var goButtonText = attributes.goButtonText;
var classPrefix = attributes.classPrefix;
@@ -240,6 +242,8 @@
var ulClassName = attributes.ulClassName || '';
var prevClassName = attributes.prevClassName || '';
var nextClassName = attributes.nextClassName || '';
var firstClassName = attributes.firstClassName || '';
var lastClassName = attributes.lastClassName || '';
var html = '';
var sizeSelect = `<select class="J-paginationjs-size-select">`;
@@ -295,9 +299,11 @@
if (showPrevious) {
if (currentPage <= 1) {
if (!autoHidePrevious) {
html += `<li class="${classPrefix}-first ${disableClassName} ${firstClassName}"><a>${firstText}</a></li>`;
html += `<li class="${classPrefix}-prev ${disableClassName} ${prevClassName}"><a>${prevText}</a></li>`;
}
} else {
html += `<li class="${classPrefix}-first J-paginationjs-first ${firstClassName}" data-num="1" title="First page">${getPageLinkTag(firstText)}</li>`;
html += `<li class="${classPrefix}-prev J-paginationjs-previous ${prevClassName}" data-num="${currentPage - 1}" title="Previous page">${getPageLinkTag(prevText)}</li>`;
}
}
@@ -312,9 +318,11 @@
if (currentPage >= totalPage) {
if (!autoHideNext) {
html += `<li class="${classPrefix}-next ${disableClassName} ${nextClassName}"><a>${nextText}</a></li>`;
html += `<li class="${classPrefix}-last ${disableClassName} ${lastClassName}"><a>${lastText}</a></li>`;
}
} else {
html += `<li class="${classPrefix}-next J-paginationjs-next ${nextClassName}" data-num="${currentPage + 1}" title="Next page">${getPageLinkTag(nextText)}</li>`;
html += `<li class="${classPrefix}-last J-paginationjs-last ${lastClassName}" data-num="${totalPage}" title="Last page">${getPageLinkTag(lastText)}</li>`;
}
}
html += `</ul></div>`;
@@ -542,6 +550,14 @@
this.go(this.model.pageNumber + 1, callback);
},
first: function(callback) {
this.go(1, callback);
},
last: function(callback) {
this.go(this.model.totalPage, callback);
},
disable: function() {
var self = this;
var source = self.isAsync ? 'async' : 'sync';
@@ -774,6 +790,38 @@
if (!attributes.pageLink) return false;
});
// First button click listener
el.on('click', '.J-paginationjs-first', function(event) {
var current = $(event.currentTarget);
var pageNumber = current.attr('data-num').trim();
if (!pageNumber || current.hasClass(attributes.disableClassName)) return;
if (self.callHook('beforeFirstOnClick', event, pageNumber) === false) return false;
self.go(pageNumber);
self.callHook('afterFirstOnClick', event, pageNumber);
if (!attributes.pageLink) return false;
});
// Last button click listener
el.on('click', '.J-paginationjs-last', function(event) {
var current = $(event.currentTarget);
var pageNumber = current.attr('data-num').trim();
if (!pageNumber || current.hasClass(attributes.disableClassName)) return;
if (self.callHook('beforeLastOnClick', event, pageNumber) === false) return false;
self.go(pageNumber);
self.callHook('afterLastOnClick', event, pageNumber);
if (!attributes.pageLink) return false;
});
// Go button click listener
el.on('click', '.J-paginationjs-go-button', function(event) {
var pageNumber = $('.J-paginationjs-go-pagenumber', el).val();
@@ -833,6 +881,16 @@
self.next(done);
});
// First page
container.on(eventPrefix + 'first', function(event, done) {
self.first(done);
});
// Last page
container.on(eventPrefix + 'last', function(event, done) {
self.last(done);
});
// Disable
container.on(eventPrefix + 'disable', function() {
self.disable();
@@ -892,6 +950,8 @@
switch (options) {
case 'previous':
case 'next':
case 'first':
case 'last':
case 'go':
case 'disable':
case 'enable':
@@ -991,6 +1051,12 @@
// 'Next' text
nextText: '&rsaquo;',
// 'First' text
firstText: '&laquo;',
// 'Last' text
lastText: '&raquo;',
// Ellipsis text
ellipsisText: '...',
@@ -1149,7 +1215,7 @@
// uninstall plugin
function uninstallPlugin(target) {
var events = ['go', 'previous', 'next', 'disable', 'enable', 'refresh', 'show', 'hide', 'destroy'];
var events = ['go', 'previous', 'next', 'first', 'last', 'disable', 'enable', 'refresh', 'show', 'hide', 'destroy'];
// off all events
$.each(events, function(index, value) {
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "وحدة تحكم المطور في Anthropic",
"Claude Model": "نموذج Claude",
"Window AI Model": "نموذج Window AI",
"Model Order": "فرز نموذج OpenRouter",
"OpenRouter Model Sorting": "فرز نموذج OpenRouter",
"Alphabetically": "أبجديا",
"Price": "السعر (الأرخص)",
"Context Size": "حجم السياق",
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "Anthropics Entwicklerkonsole",
"Claude Model": "Claude-Modell",
"Window AI Model": "Fenster AI-Modell",
"Model Order": "Sortierung des OpenRouter-Modells",
"OpenRouter Model Sorting": "Sortierung des OpenRouter-Modells",
"Alphabetically": "Alphabetisch",
"Price": "Preis (am günstigsten)",
"Context Size": "Kontextgröße",
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "la consola de desarrolladores de Anthropic",
"Claude Model": "Modelo de Claude",
"Window AI Model": "Modelo de Window AI",
"Model Order": "Clasificación de modelos de OpenRouter",
"OpenRouter Model Sorting": "Clasificación de modelos de OpenRouter",
"Alphabetically": "Alfabéticamente",
"Price": "Precio (más barato)",
"Context Size": "Tamaño del contexto",
+2 -2
View File
@@ -348,7 +348,7 @@
"Anthropic's developer console": "Console de développement d'Anthropic",
"Claude Model": "Modèle Claude",
"Window AI Model": "Modèle Window AI",
"Model Order": "Tri des modèles OpenRouter",
"OpenRouter Model Sorting": "Tri des modèles OpenRouter",
"Alphabetically": "Alphabétiquement",
"Price": "Prix ​​(le moins cher)",
"Context Size": "Taille du contexte",
@@ -1566,7 +1566,7 @@
"These files are available for all characters in the current chat.": "Ces fichiers sont disponibles pour tous les personnages du chat actuel.",
"Image Captioning": "Légende des images",
"Local": "Local",
"Multimodal (OpenAI / Anthropic / llama / Google)": "Multimodal (OpenAI / Anthropic / llama / Google)",
"Multimodal": "Multimodal",
"Extras": "Extras",
"Horde": "Horde",
"API": "API",
+1 -1
View File
@@ -367,7 +367,7 @@
"Anthropic's developer console": "Uppbyggingaraðilar Forritara stjórnborð",
"Claude Model": "Claude módel",
"Window AI Model": "Vindauga AI módel",
"Model Order": "OpenRouter líkanaflokkun",
"OpenRouter Model Sorting": "OpenRouter líkanaflokkun",
"Alphabetically": "Stafrófsröð",
"Price": "Verð (ódýrast)",
"Context Size": "Samhengisstærð",
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "Console dello sviluppatore di Anthropic",
"Claude Model": "Modello Claude",
"Window AI Model": "Modello AI di Window",
"Model Order": "Ordinamento dei modelli OpenRouter",
"OpenRouter Model Sorting": "Ordinamento dei modelli OpenRouter",
"Alphabetically": "In ordine alfabetico",
"Price": "Prezzo (il più economico)",
"Context Size": "Dimensione del contesto",
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "Anthropicの開発者コンソール",
"Claude Model": "Claudeモデル",
"Window AI Model": "Window AIモデル",
"Model Order": "OpenRouter モデルのソート",
"OpenRouter Model Sorting": "OpenRouter モデルのソート",
"Alphabetically": "アルファベット順",
"Price": "価格(最安値)",
"Context Size": "コンテキストサイズ",
+1 -1
View File
@@ -374,7 +374,7 @@
"Slack and Poe cookies will not work here, do not bother trying.": "Slack과 Poe 쿠키는 여기서 작동하지 않습니다. 시도하지 마세요.",
"Claude Model": "Claude 모델",
"Window AI Model": "Window AI 모델",
"Model Order": "OpenRouter 모델 정렬",
"OpenRouter Model Sorting": "OpenRouter 모델 정렬",
"Alphabetically": "알파벳순",
"Price": "가격(가장 저렴)",
"Context Size": "컨텍스트 크기",
+1 -1
View File
@@ -367,7 +367,7 @@
"Anthropic's developer console": "Anthropic's ontwikkelaarsconsole",
"Claude Model": "Claude-model",
"Window AI Model": "Window AI-model",
"Model Order": "Sorteren van OpenRouter-modellen",
"OpenRouter Model Sorting": "Sorteren van OpenRouter-modellen",
"Alphabetically": "Alfabetisch",
"Price": "Prijs (goedkoopste)",
"Context Size": "Contextgrootte",
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "console de desenvolvedor da Anthropic",
"Claude Model": "Modelo Claude",
"Window AI Model": "Modelo Window AI",
"Model Order": "Classificação de modelo OpenRouter",
"OpenRouter Model Sorting": "Classificação de modelo OpenRouter",
"Alphabetically": "Alfabeticamente",
"Price": "Preço (mais barato)",
"Context Size": "Tamanho do contexto",
+121 -29
View File
@@ -24,7 +24,7 @@
"Mirostat_Tau_desc": "Целевая перплексия.",
"Mirostat_Eta_desc": "Скорость обучения Mirostat.",
"Temperature Last": "Температура последней",
"LLaMA / Mistral / Yi models only": "Только для моделей LLaMA / Mistral / Yi. Перед этим обязательно выберите подходящий токенизатор.\nПоследовательности, которых не должно быть на выходе.\nОдна на строку. Текст или [идентификаторы токенов].\nМногие токены имеют пробел впереди. Используйте счетчик токенов, если не уверены, что правильно их определяете.",
"LLaMA / Mistral / Yi models only": "Только для моделей LLaMA / Mistral / Yi. Перед этим обязательно выберите подходящий токенизатор.\nПоследовательности, которых не должно быть на выходе.\nОдна на строку. Текст или [идентификаторы токенов].\nМногие токены имеют пробел впереди. Используйте счётчик токенов, если не уверены, что правильно их определяете.",
"Example: some text [42, 69, 1337]": "Пример:\nкакой-то текст\n[42, 69, 1337]",
"Classifier Free Guidance. More helpful tip coming soon": "Classifier Free Guidance. Чуть позже опишем более подробно",
"Scale": "Scale",
@@ -91,7 +91,7 @@
"Impersonation prompt": "Промпт для перевоплощения",
"Prompt that is used for Impersonation function": "Промпт, применяемый при генерации действий от лица пользователя",
"Logit Bias": "Смещение логитов",
"Helps to ban or reenforce the usage of certain words": "Запрещает или поощряет использование определенных слов",
"Helps to ban or reenforce the usage of certain words": "Запрещает или поощряет использование определенных слов.",
"View / Edit bias preset": "Просмотр / Редактирование пресета смещения",
"Add bias entry": "Добавить правило смещения",
"Connect": "Подключиться",
@@ -201,8 +201,8 @@
"Bubbles": "Пузыри",
"No Blur Effect": "Отключить размытие",
"No Text Shadows": "Отключить тень текста",
"Waifu Mode": "Режим вайфу",
"Message Timer": "Таймер сообщений",
"Waifu Mode": "Режим визуальной новеллы",
"Message Timer": "Длительность генерации сообщений",
"Model Icon": "Значки моделей",
"Advanced Character Search": "Расширенный поиск по персонажам",
"Allow {{char}}: in bot messages": "Показывать {{char}}: в ответах",
@@ -211,12 +211,12 @@
"Lorebook Import Dialog": "Показывать окно импорта лорбука",
"MUI Preset": "Пресет MUI:",
"If set in the advanced character definitions, this field will be displayed in the characters list.": "Если это поле задано в расширенных параметрах персонажа, оно будет отображаться в списке персонажей.",
"Relaxed API URLS": "Смягчённые адреса API",
"Relaxed API URLS": "\"Ленивые\" адреса API",
"Custom CSS": "Пользовательский CSS",
"Mancer Model": "Модель Mancer",
"API Type": "Тип API",
"Aphrodite API key": "Ключ от API Aphrodite",
"Relax message trim in Groups": "Мягкая обрезка сообщений в группах",
"Relax message trim in Groups": "Смягчить требования к сообщениям ИИ в группах",
"Characters Hotswap": "HotSwap (смена персонажей на лету)",
"Request token probabilities": "Запрашивать вероятность токена",
"Movable UI Panels": "Подвижные панели UI",
@@ -229,10 +229,10 @@
"Text Shadow Width": "Размер теней текста",
"Swipes": "Свайпы",
"Miscellaneous": "Разное",
"Background Sound Only": "Только фоновый звук",
"Background Sound Only": "Только фоновые звуки",
"Auto-load Last Chat": "Автозагрузка последнего чата",
"Auto-save Message Edits": "Автоматически сохранять отредактированные сообщения",
"Auto-fix Markdown": "Автоисправление разметки",
"Auto-fix Markdown": "Автоисправление разметки Markdown",
"Auto-scroll Chat": "Автоматическая прокрутка чата",
"Send on Enter": "Отправка на Enter",
"Debug Menu": "Меню отладки",
@@ -329,7 +329,7 @@
"Global Lore First": "Сначала глобальный лор",
"Recursive Scan": "Рекурсивное сканирование",
"Case Sensitive": "Учитывать регистр",
"Alert On Overflow": "Оповещение о переполнении",
"Alert On Overflow": "Оповещение о превышении бюджета",
"Use Probability": "Использовать вероятность",
"Exclude from recursion": "Исключить из рекурсии",
"Entry Title/Memo": "Название или заметка о записи",
@@ -354,7 +354,7 @@
"Chat Background": "Фон чата",
"UI Background": "Фон UI",
"Mad Lab Mode": "Режим безумца",
"Show Message Token Count": "Счетчик токенов сообщения",
"Show Message Token Count": "Показывать кол-во токенов в сообщении",
"Compact Input Area (Mobile)": "Компактная зона ввода",
"Zen Sliders": "Дзен слайдеры",
"UI Border": "Границы UI",
@@ -363,7 +363,7 @@
"Tags as Folders": "Теги как папки",
"Streaming FPS": "FPS для стриминга",
"Gestures": "Жесты",
"Message IDs": "ID сообщений",
"Message IDs": "Номера сообщений",
"Prefer Character Card Prompt": "Приоритет промпту из карточки персонажа",
"Prefer Character Card Jailbreak": "Приоритет джейлбрейку из карточки персонажа",
"Press Send to continue": "Кнопка отправки продолжает сообщение",
@@ -372,7 +372,7 @@
"Never resize avatars": "Не менять размер аватарок",
"Show avatar filenames": "Показывать названия файлов аватарок",
"Import Card Tags": "Импортировать теги карточки",
"Confirm message deletion": "Подтверждение удаления сообщений",
"Confirm message deletion": "Спрашивать при удалении сообщений",
"Spoiler Free Mode": "Режим без спойлеров",
"Auto-swipe": "Автоматические свайпы",
"Minimum generated message length": "Минимальная длина сгенерированных сообщений",
@@ -392,11 +392,11 @@
"Always show the full list of the Message Actions context items for chat messages, instead of hiding them behind '...'": "Всегда показывать полный список действий с сообщением, а не прятать их за '...'.",
"Alternative UI for numeric sampling parameters with fewer steps": "Уменьшить кол-во шагов для параметров, регулируемых слайдерами.",
"Entirely unrestrict all numeric sampling parameters": "Снять ограничения со всех числовых сэмплеров.",
"Time the AI's message generation, and show the duration in the chat log": "Время генерации сообщений ИИ и его показ в журнале чата.",
"Time the AI's message generation, and show the duration in the chat log": "Засекать время, за которое было сгенерировано сообщение, и отображать эту информацию в чате.",
"Show a timestamp for each message in the chat log": "Показывать временную метку для каждого сообщения в журнале чата.",
"Show an icon for the API that generated the message": "Показать значок API, сгенерировавшего сообщение.",
"Show sequential message numbers in the chat log": "Показывать порядковые номера сообщений в журнале чата.",
"Show the number of tokens in each message in the chat log": "Показать количество токенов в каждом сообщении в журнале чата.",
"Show an icon for the API that generated the message": "Показывать значок API, сгенерировавшего сообщение.",
"Show sequential message numbers in the chat log": "Показывать порядковые номера сообщений в чате.",
"Show the number of tokens in each message in the chat log": "Показывать количество токенов в каждом сообщении в чате.",
"Single-row message input area. Mobile only, no effect on PC": "Однорядная область ввода сообщений. Только для мобильных устройств, на ПК не работает.",
"In the Character Management panel, show quick selection buttons for favorited characters": "На панели управления персонажами будут отображены кнопки быстрого выбора для избранных персонажей.",
"Show tagged character folders in the character list": "Отобразить теговые папки с персонажами в списке персонажей.",
@@ -404,7 +404,7 @@
"Only play a sound when ST's browser tab is unfocused": "Воспроизводить звук только тогда, когда вкладка браузера ST не выбрана.",
"Reduce the formatting requirements on API URLs": "Снижение требований к форматированию URL-адресов API.",
"Ask to import the World Info/Lorebook for every new character with embedded lorebook. If unchecked, a brief message will be shown instead": "Спрашивать разрешение на импорт лорбука для всех персонажей со встроенным лорбуком. При выключенной опции вместо этого будет показываться короткое сообщение",
"Restore unsaved user input on page refresh": "Восстановление несохраненного пользовательского запроса при обновлении страницы.",
"Restore unsaved user input on page refresh": "Восстановление несохраненного пользовательского сообщения при обновлении страницы.",
"Allow repositioning certain UI elements by dragging them. PC only, no effect on mobile": "Позволяет перемещать некоторые элементы интерфейса путем их перетаскивания. Только для ПК, на телефонах не работает.",
"MovingUI preset. Predefined/saved draggable positions": "Пресет для MovingUI. Предопределенные/сохраненные позиции для перетаскивания.",
"Save movingUI changes to a new file": "Сохранение изменений MovingUI в новый файл.",
@@ -419,7 +419,7 @@
"Show arrow buttons on the last in-chat message to generate alternative AI responses. Both PC and mobile": "Показывать кнопки со стрелками на последнем сообщении в чате, чтобы генерировать альтернативные ответы ИИ. Как для ПК, так и для мобильных устройств.",
"Allow using swiping gestures on the last in-chat message to trigger swipe generation. Mobile only, no effect on PC": "Позволяет использовать жесты смахивания на последнем сообщении в чате, чтобы вызвать альтернативную генерацию. Только для мобильных устройств, на ПК не работает.",
"Save edits to messages without confirmation as you type": "Сохранять правки в сообщениях без подтверждения по мере ввода текста.",
"Skip encoding and characters in message text, allowing a subset of HTML markup as well as Markdown": "Не кодировать символы < и > в тексте сообщения, что позволяет использовать подмножество HTML-разметки, а также Markdown.",
"Skip encoding and characters in message text, allowing a subset of HTML markup as well as Markdown": "Не кодировать символы < и > в тексте сообщения, что позволяет использовать часть возможностей HTML-разметки, а также разметку Markdown.",
"Allow AI messages in groups to contain lines spoken by other group members": "Разрешить ИИ в группах генерировать строчки за других участников группы в своих сообщениях.",
"Requests logprobs from the API for the Token Probabilities feature": "Запросить логпробы из API для функции Token Probabilities.",
"Automatically reject and re-generate AI message based on configurable criteria": "Автоматическое отклонение и повторная генерация сообщений AI на основе настраиваемых критериев.",
@@ -549,7 +549,7 @@
"Character Management": "Управление персонажами",
"Locked = Character Management panel will stay open": "Закреплено = Панель управление персонажами останется открытой",
"Select/Create Characters": "Выбрать/Создать персонажа",
"Token counts may be inaccurate and provided just for reference.": "Счетчик токенов может быть неточным, используйте как ориентир",
"Token counts may be inaccurate and provided just for reference.": "Счётчик токенов может быть неточным, используйте как ориентир",
"Click to select a new avatar for this character": "Нажмите чтобы выбрать новый аватар для этого персонажа",
"Example: [{{user}} is a 28-year-old Romanian cat girl.]": "Пример:\n [{{user}} is a 28-year-old Romanian cat girl.]",
"Toggle grid view": "Сменить вид сетки",
@@ -718,7 +718,7 @@
"Google Model": "Модель Google",
"Cohere API Key": "Ключ от API Cohere",
"Cohere Model": "Модель Cohere",
"Model Order": "Сортировка моделей OpenRouter",
"OpenRouter Model Sorting": "Сортировка моделей OpenRouter",
"Alphabetically": "По алфавиту",
"Price": "По цене (наиболее низкая)",
"Context Size": "По размеру контекста",
@@ -1024,10 +1024,10 @@
"image_inlining_hint_2": ". Также это можно сделать через меню",
"image_inlining_hint_3": ".",
"Contest Winners": "Победители конкурса",
"Rename background": "Переименовать фон",
"Rename Background": "Переименовать фон",
"Lock": "Закрепить",
"Unlock": "Открепить",
"Delete background": "Удалить фон",
"Delete Background": "Удалить фон",
"Export all": "Экспортировать всё",
"Export all your prompts to a file": "Экспортировать все промпты в виде файла",
"Don't add character names.": "Не добавлять имя персонажа",
@@ -1621,7 +1621,7 @@
"Auxiliary": "Вспомогательный",
"Post-History Instructions": "Инструкции после истории",
"Current persona updated": "Текущая персона изменена",
"Your messages will now be sent as ${0}": "Ваши сообщения будут отправляться от лица ${0}",
"Your messages will now be sent as ${0}": "Теперь вы будете подписываться как ${0}",
"Copied!": "Скопировано!",
"Are you sure you want to delete this message?": "Вы точно хотите удалить это сообщение?",
"Delete Message": "Удалить сообщение",
@@ -1977,7 +1977,7 @@
"Importing Tags": "Импорт тегов",
"Couldn't import tags:": "Не удалось импортировать теги:",
"Allow fallback models": "Разрешить резервные модели",
"Allow fallback providers": "Разрешить fallback-провайдеров",
"Allow fallback providers": "Разрешить резервных провайдеров",
"To use instruct formatting, switch to OpenRouter under Text Completion API.": "Переключитесь на OpenRouter в Text Completion API, чтобы использовать форматирование Instruct-режима.",
"Select providers. No selection = all providers.": "Выберите провайдера. Нет выбранного = выбраны все.",
"Model Providers": "Провайдеры моделей",
@@ -2406,7 +2406,7 @@
"${0} is a system assistant. Choose another character.": "Персонаж ${0} выбран в качестве системного помощника. Выберите другого.",
"Set ${0} as your assistant.": "Персонаж ${0} установлен в качестве помощника.",
"${0} is no longer your assistant.": "Персонаж ${0} снят с роли помощника.",
"Manage API keys": "Управление ключами",
"Manage API keys": "Менеджер ключей",
"Key:": "Ключ:",
"No secrets saved.": "Ключей нет.",
"Add Secret": "Добавить ключ",
@@ -2433,7 +2433,7 @@
"prompt_post_processing_semi_tools": "Semi-strict (чередовать роли, функции включены)",
"prompt_post_processing_strict_tools": "Strict (чередовать роли, сначала пользователь; функции включены)",
"prompt_post_processing_single": "Только одно сообщение пользователя (функции отключены)",
"prompt_post_processing_merge_tools": "Объединять идущие подряд сообщение с одной ролью (функции включены)",
"prompt_post_processing_merge_tools": "Объединять идущие подряд сообщения с одной ролью (функции включены)",
"completions note prefix": "Постфикс ",
"suffix will be added automatically.": "будет добавлен автоматически.",
"Tabby Model": "Модель Tabby",
@@ -2548,7 +2548,7 @@
"Default (top of context)": "По умолчанию (наверху контекста)",
"Bind Model to Templates": "Связать модель с шаблоном",
"Persona Auto Selected": "Персона автоматически изменена",
"Auto-selected persona based on ${0} connection.<br />Your messages will now be sent as ${1}.": "Персона выбрана автоматически на основе следующего критерия: ${0}<br />Ваши сообщения будут отправляться от лица ${1}",
"Auto-selected persona based on ${0} connection.<br />Your messages will now be sent as ${1}.": "Персона выбрана автоматически на основе следующего критерия: ${0}<br />Теперь вы будете подписываться как ${1}",
"Filter to specific generation types.": "Применять промпт только при определённых типах генерации.",
"Quiet": "Тихая",
"Swipe": "Свайп",
@@ -2601,7 +2601,7 @@
"sd_snap_txt": "Корректировать автоматически выбранное разрешение",
"sd_snap": "Подгонять картинки с фиксированным соотношением сторон (фоны, портреты) к ближайшему известному разрешению (рекомендуется для SDXL)",
"Source": "API",
"Hint: Save an API key in AI Horde API settings to use it here.": "Подсказка: сохраните ключ от API в настройках API на сайте AI Horde, чтобы использовать его автоматически.",
"Hint: Save an API key in AI Horde API settings to use it here.": "Совет: сохраните ключ от API в настройках API AI Horde, чтобы автоматически подтянуть его сюда.",
"Sanitize prompts (recommended)": "Прогонять промпты через санитайзер (рекомендуется)",
"Sampling method": "Метод сэмплинга",
"Resolution": "Целевое разрешение",
@@ -2652,5 +2652,97 @@
"sd_auto_auth_warning_1": " запускайте Stable Diffusion с флагом",
"sd_auto_auth_warning_2": "! Адрес SD должен быть доступен с сервера SillyTavern.",
"Upscale by": "Множитель апскейлинга",
"Hires steps (2nd pass)": "Кол-во шагов Hires (на втором проходе)"
"Hires steps (2nd pass)": "Кол-во шагов Hires (на втором проходе)",
"Disallow embedded media from other domains in chat messages": "Запретить медиафайлы со сторонних доменов в сообщениях чата.",
"Add Background": "Добавить фон",
"Add a new background": "Добавить новый фон",
"Backgrounds": "Фоны",
"ext_regex_debugger_desc": "Дополнительные инструменты отладки",
"ext_regex_debugger": "Отладка",
"ext_regex_presets": "Пресеты",
"ext_regex_presets_desc": "Переключайтесь между разными группами активных рег. выражений.",
"ext_regex_preset_create": "Создать новый пресет",
"ext_regex_preset_update": "Обновить текущий пресет",
"ext_regex_preset_apply": "Перезагрузить текущий пресет",
"ext_regex_preset_delete": "Удалить текущий пресет",
"[No presets saved]": "[Пресет не выбран]",
"Enter a name for the new regex preset:": "Введите имя нового пресета:",
"ext_regex_debugger_active_rules": "Активные скрипты",
"No regex rules found.": "Скриптов не найдено.",
"ext_regex_debugger_testing_area": "Зона тестирования",
"ext_regex_debugger_run_test": "Протестировать",
"ext_regex_debugger_display_replace": "Заменить",
"ext_regex_debugger_display_highlight": "Посдветить",
"ext_regex_debugger_render_text": "Отображать как текст",
"ext_regex_debugger_render_message": "Отображать как сообщение",
"ext_regex_debugger_save_order": "Сохранить порядок",
"ext_regex_debugger_save_order_help": "Сохранить текущий порядок скриптов",
"Regex script order saved!": "Порядок сохранён!",
"ext_regex_debugger_raw_input": "Исходный текст",
"ext_regex_debugger_step_by_step": "Пошаговая трансформация",
"ext_regex_debugger_final_output": "Итоговый результат",
"Expand view": "Развернуть",
"Global Rules": "Глобальные скрипты",
"Scoped Rules": "Локальные скрипты",
"Edit Rule": "Редактировать скрипт",
"Global": "Глобальный",
"Scoped": "Локальный",
"Captured:": "Зафиксировано:",
"Added:": "Добавлено:",
"Removed:": "Удалено:",
"Total Captured:": "Всего зафиксировано:",
"Total Added:": "Всего добавлено:",
"Total Removed:": "Всего удалено:",
"ext_regex_debugger_run_test_help": "Прогнать текст через данный набор скриптов",
"After:": "После:",
"Are you sure you want to delete this regex preset?": "Точно хотите удалить этот пресет?",
"Regex preset updated": "Пресет обновлён",
"Regex preset saved": "Пресет сохранён",
"Regex preset deleted": "Пресет удалён",
"Enhance": "Улучшить",
"Enables prompt enhancing (passes prompts through an LLM to add detail).": "Включить улучшение промпта (дополнительно прогоняет промпт через LLM, чтобы добавить больше деталей)",
"Use ADetailer (Face)": "Использовать ADetailer (для лиц)",
"You can find your API key in the Stability AI dashboard.": "Ключ от API можно найти на дашборде на сайте Stability AI",
"sd_stability_style_preset": "Стиль",
"Avoid spending Anlas": "Стараться не тратить Anlas",
"Automatically adjust generation parameters to ensure free image generations.": "Автоматически подгонять параметры таким образом, чтобы генерация получалась бесплатной.",
"View my Anlas": "Узнать баланс Anlas",
"Hint: Save an API key in the NovelAI API settings to use it here.": "Совет: сохраните API-ключ в настройках API NovelAI, чтобы автоматически подтянуть его сюда.",
"Hint: Save an API key in the Hugging Face (Text Completion) API settings to use it here.": "Совет: сохраните API-ключ в настройках API HuggingFace (раздел Text Completion), чтобы автоматически подтянуть его сюда.",
"Model ID": "Идентификатор модели",
"<Enter Model ID above>": "<Введите идентификатор в поле выше>",
"Hint: Save an API key in the NanoGPT (Chat Completion) API settings to use it here.": "Совет: сохраните API-ключ в настройках API NanoGPT (раздел Chat Completion), чтобы автоматически подтянуть его сюда.",
"Hint: Save an API key in the Electron Hub (Chat Completion) API settings to use it here.": "Совет: сохраните API-ключ в настройках API Electron Hub (раздел Chat Completion), чтобы автоматически подтянуть его сюда.",
"sd_drawthings_auth_txt": " запускайте DrawThings только со включенным в UI флажком HTTP API! Сервер должен быть доступен с хоста, на котором запущена SillyTavern.",
"Send me a picture of:": "Пришли мне...",
"sd_Yourself": "Свою фотографию",
"sd_Your_Face": "Своё лицо",
"sd_Me": "Мою фотографию",
"sd_The_Whole_Story": "Изображение всей истории",
"sd_The_Last_Message": "Изображение посл. сообщения",
"sd_Raw_Last_Message": "Изображение посл. сообщения до обработки",
"sd_Background": "Фотографию фона",
"ext_regex_title": "Регулярные выражения",
"ext_sum_title": "Саммари (пересказ)",
"Image Generation": "Генерация изображений",
"ext_translate_title": "Перевод чата",
"Select TTS Provider": "Выберите TTS-движок",
"tts_enabled": "Включить",
"Narrate user messages": "Озвучивать сообщения пользователя",
"Auto Generation": "Автоматическая генерация",
"Narrate by paragraphs (when streaming)": "Озвучивать по параграфу за раз (при вкл. стриминге)",
"Narrate by paragraphs (when not streaming)": "Озвучивать по параграфу за раз (при выкл. стриминге)",
"Only narrate quotes": "Озвучивать только текст \"в кавычках\"",
"Ignore text, even quotes, inside asterisk": "Не озвучивать *текст, даже \"в кавычках\", если он внутри звёздочек*",
"Narrate only the translated text": "Озвучивать только переведённый текст",
"Skip codeblocks": "Пропускать блоки кода",
"Skip tagged blocks": "Пропускать блоки с <тегами>",
"Pass Asterisks to TTS Engine": "Передавать звёздочки TTS-движку",
"Different voices for quotes and text inside asterisks": "Разные голоса для \"кавычек\", *звёздочек* и остального текста.",
"Requires auto generation to be enabled.": "Работает только при включенной функции \"Автоматическая генерация\"",
"tts_refresh": "Обновить",
"Uses the voices provided by your operating system": "Используем стандартные голоса вашей ОС",
"Your browser or operating system doesn't support speech synthesis": "Ваш браузер либо ОС не поддерживают синтез речи",
"Works best when: Pass Asterisks to TTS Engine is enabled, and both Only narrate quotes and Ignore *text, even 'quotes', inside asterisks* are disabled.": "Работает лучше всего, когда: одновременно включена опция \"Передавать звёздочки TTS-движку\", а также отключены обе опции: \"Не озвучивать *текст, даже \"в кавычках\", если он внутри звёздочек*\", и \"Озвучивать только текст \"в кавычках\"\"",
"Available voices": "Доступные голоса"
}
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "консолі розробника Anthropic",
"Claude Model": "Модель Claude",
"Window AI Model": "Модель Window AI",
"Model Order": "Сортування моделі OpenRouter",
"OpenRouter Model Sorting": "Сортування моделі OpenRouter",
"Alphabetically": "За алфавітом",
"Price": "Ціна (найдешевша)",
"Context Size": "Розмір контексту",
+1 -1
View File
@@ -369,7 +369,7 @@
"Anthropic's developer console": "developer console của Anthropic",
"Claude Model": "Model Claude",
"Window AI Model": "Model Window AI",
"Model Order": "Sắp xếp model OpenRouter",
"OpenRouter Model Sorting": "Sắp xếp model OpenRouter",
"Alphabetically": "Theo thứ tự bảng chữ cái",
"Price": "Giá (rẻ nhất)",
"Context Size": "Kích thước bối cảnh",
+19 -7
View File
@@ -452,7 +452,7 @@
"Claude Model": "Claude 模型",
"Allow fallback routes Description": "如果所选模型无法响应您的请求,则自动选择备用模型。",
"Allow fallback models": "允许后备模型",
"Model Order": "OpenRouter 模型顺序",
"OpenRouter Model Sorting": "OpenRouter 模型顺序",
"Alphabetically": "按字母顺序",
"Price": "价格(最便宜)",
"Context Size": "上下文长度",
@@ -1479,7 +1479,7 @@
"Image Captioning": "图像描述",
"Source": "来源",
"Local": "本地",
"Multimodal (OpenAI / Anthropic / llama / Google)": "多模态(OpenAI / Anthropic / llama / Google)",
"Multimodal": "多模态",
"Extras": "更多",
"Horde": "Horde",
"API": "API",
@@ -1646,8 +1646,9 @@
"macro for manual injection)": "宏用于手动注入)",
"Color": "颜色",
"Only apply color as accent": "仅应用颜色作为强调",
"ext_regex_new_global_script_desc": "新增「全局」正规表达式",
"ext_regex_new_scoped_script_desc": "新增「局部」正规表达式",
"ext_regex_new_global_script_desc": "新增「全局」正则表达式",
"ext_regex_new_scoped_script_desc": "新增「局部」正则表达式",
"ext_regex_new_preset_script_desc": "新增「预设」正则表达式",
"ext_regex_debugger_active_rules": "激活的规则",
"ext_regex_debugger_save_order": "保存此顺序",
"ext_regex_debugger_testing_area": "测试区域",
@@ -1668,6 +1669,7 @@
"ext_regex_preset_delete": "删除当前预设",
"ext_regex_new_global_script": "新建全局正则",
"ext_regex_new_scoped_script": "新建局部正则",
"ext_regex_new_preset_script": "新建预设正则",
"ext_regex_import_script": "导入正则",
"ext_regex_bulk_edit": "批量编辑",
"ext_regex_debugger_desc": "高级正则调试工具",
@@ -1677,9 +1679,13 @@
"ext_regex_global_scripts_desc": "影响所有角色,保存在本地设定中",
"No scripts found": "没有找到脚本",
"ext_regex_scoped_scripts": "局部正则脚本",
"ext_regex_scoped_scripts_desc": "只影响当前角色,保存在角色卡片中",
"ext_regex_preset_scripts": "预设正则脚本",
"ext_regex_preset_scripts_desc": "只影响当前预设,保存在预设中",
"ext_regex_disallow_scoped": "不允许使用局部正则",
"ext_regex_allow_scoped": "允许使用局部正则",
"ext_regex_scoped_scripts_desc": "只影响当前角色,保存在角色卡片中",
"ext_regex_disallow_preset": "不允许使用预设正则",
"ext_regex_allow_preset": "允许使用预设正则",
"Regex Editor": "正则表达式编辑器",
"Test Mode": "测试模式",
"ext_regex_desc": "“正则”是一个使用“正则表达式”来查找/替换字符串的工具。如果您想了解更多信息,请点击标题旁边的“?”。",
@@ -1728,10 +1734,16 @@
"ext_regex_disable_script": "禁用脚本",
"ext_regex_enable_script": "启用脚本",
"ext_regex_edit_script": "编辑脚本",
"ext_regex_move_to_global": "移至全局脚本",
"ext_regex_move_to_scoped": "移至作用域脚本",
"ext_regex_move_to_global": "移至全局",
"ext_regex_move_to_scoped": "移至局部",
"ext_regex_move_to_preset": "移至预设",
"ext_regex_export_script": "导出脚本",
"ext_regex_delete_script": "删除脚本",
"This preset has embedded regex script(s).": "此预设包含内置正则脚本。",
"Preset '${0}' contains enabled regex scripts": "预设 '${0}' 包含被启用的正则脚本",
"Reload the chat for regex to take effect": "重新加载聊天以使正则生效",
"Click here to reload immediately": "点击此处立即重新加载",
"If you want to do it later, select \"Regex\" from the extensions menu.": "您可稍后从扩展菜单中的(Regex)启用。",
"Trigger Stable Diffusion": "触发Stable Diffusion",
"Abort current image generation task": "中止当前图像生成",
"Stop Image Generation": "停止图像生成",
+2 -2
View File
@@ -368,7 +368,7 @@
"Anthropic's developer console": "Anthropic 的開發者控制台",
"Claude Model": "Claude 模型",
"Window AI Model": "Window AI 模型",
"Model Order": "模型順序",
"OpenRouter Model Sorting": "模型順序",
"Alphabetically": "按字母順序",
"Price": "價格(最便宜的)",
"Context Size": "上下文長度",
@@ -1674,7 +1674,7 @@
"Message Template": "訊息範本",
"Model ID": "模型 ID",
"mui_reset": "重設",
"Multimodal (OpenAI / Anthropic / llama / Google)": "多模態(OpenAI/Anthropic/llama/Google)",
"Multimodal": "多模態",
"must be set in Tabby's config.yml to switch models.": "須在 Tabby's config.yml 中設定以切換模型。",
"Names as Stop Strings": "將名稱用作停止字串",
"Never": "從不",
+10
View File
@@ -25,6 +25,16 @@
"src": "img/apple-icon-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "img/apple-icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "img/apple-icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+390 -277
View File
File diff suppressed because it is too large Load Diff
+39 -36
View File
@@ -766,44 +766,47 @@ export function initRossMods() {
}
});
// read the state of right Nav Lock and apply to rightnav classlist
$(RPanelPin).prop('checked', accountStorage.getItem('NavLockOn') == 'true');
if (accountStorage.getItem('NavLockOn') == 'true') {
//console.log('setting pin class via local var');
$(RightNavPanel).addClass('pinnedOpen');
$(RightNavDrawerIcon).addClass('drawerPinnedOpen');
}
if ($(RPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(RightNavPanel).addClass('pinnedOpen');
$(RightNavDrawerIcon).addClass('drawerPinnedOpen');
}
// read the state of left Nav Lock and apply to leftnav classlist
$(LPanelPin).prop('checked', accountStorage.getItem('LNavLockOn') === 'true');
if (accountStorage.getItem('LNavLockOn') == 'true') {
//console.log('setting pin class via local var');
$(LeftNavPanel).addClass('pinnedOpen');
$(LeftNavDrawerIcon).addClass('drawerPinnedOpen');
}
if ($(LPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(LeftNavPanel).addClass('pinnedOpen');
$(LeftNavDrawerIcon).addClass('drawerPinnedOpen');
if (!isMobile()) { //only read/set pin states on non-mobile devices
// read the state of right Nav Lock and apply to rightnav classlist
$(RPanelPin).prop('checked', accountStorage.getItem('NavLockOn') == 'true');
if (accountStorage.getItem('NavLockOn') == 'true') {
//console.log('setting pin class via local var');
$(RightNavPanel).addClass('pinnedOpen');
$(RightNavDrawerIcon).addClass('drawerPinnedOpen');
}
if ($(RPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(RightNavPanel).addClass('pinnedOpen');
$(RightNavDrawerIcon).addClass('drawerPinnedOpen');
}
// read the state of left Nav Lock and apply to leftnav classlist
$(LPanelPin).prop('checked', accountStorage.getItem('LNavLockOn') === 'true');
if (accountStorage.getItem('LNavLockOn') == 'true') {
//console.log('setting pin class via local var');
$(LeftNavPanel).addClass('pinnedOpen');
$(LeftNavDrawerIcon).addClass('drawerPinnedOpen');
}
if ($(LPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(LeftNavPanel).addClass('pinnedOpen');
$(LeftNavDrawerIcon).addClass('drawerPinnedOpen');
}
// read the state of left Nav Lock and apply to leftnav classlist
$(WIPanelPin).prop('checked', accountStorage.getItem('WINavLockOn') === 'true');
if (accountStorage.getItem('WINavLockOn') == 'true') {
//console.log('setting pin class via local var');
$(WorldInfo).addClass('pinnedOpen');
$(WIDrawerIcon).addClass('drawerPinnedOpen');
}
if ($(WIPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(WorldInfo).addClass('pinnedOpen');
$(WIDrawerIcon).addClass('drawerPinnedOpen');
}
}
// read the state of left Nav Lock and apply to leftnav classlist
$(WIPanelPin).prop('checked', accountStorage.getItem('WINavLockOn') === 'true');
if (accountStorage.getItem('WINavLockOn') == 'true') {
//console.log('setting pin class via local var');
$(WorldInfo).addClass('pinnedOpen');
$(WIDrawerIcon).addClass('drawerPinnedOpen');
}
if ($(WIPanelPin).prop('checked')) {
console.debug('setting pin class via checkbox state');
$(WorldInfo).addClass('pinnedOpen');
$(WIDrawerIcon).addClass('drawerPinnedOpen');
}
//save state of Right nav being open or closed
$('#rightNavDrawerIcon').on('click', function () {
+243 -173
View File
@@ -3,7 +3,8 @@ import { chat_metadata, eventSource, event_types, generateQuietPrompt, getCurren
import { openThirdPartyExtensionMenu, saveMetadataDebounced } from './extensions.js';
import { SlashCommand } from './slash-commands/SlashCommand.js';
import { SlashCommandParser } from './slash-commands/SlashCommandParser.js';
import { createThumbnail, flashHighlight, getBase64Async, stringFormat } from './utils.js';
import { createThumbnail, flashHighlight, getBase64Async, stringFormat, debounce, setupScrollToTop } from './utils.js';
import { debounce_timeout } from './constants.js';
import { t } from './i18n.js';
import { Popup } from './popup.js';
@@ -15,6 +16,11 @@ const PNG_PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkY
const PNG_PIXEL_BLOB = new Blob([Uint8Array.from(atob(PNG_PIXEL), c => c.charCodeAt(0))], { type: 'image/png' });
const PLACEHOLDER_IMAGE = `url('data:image/png;base64,${PNG_PIXEL}')`;
const THUMBNAIL_COLUMNS_MIN = 2;
const THUMBNAIL_COLUMNS_MAX = 8;
const THUMBNAIL_COLUMNS_DEFAULT_DESKTOP = 5;
const THUMBNAIL_COLUMNS_DEFAULT_MOBILE = 3;
/**
* Storage for frontend-generated background thumbnails.
* This is used to store thumbnails for backgrounds that cannot be generated on the server.
@@ -45,6 +51,53 @@ export let background_settings = {
animation: false,
};
/**
* Creates a single thumbnail DOM element. The CSS now handles all sizing.
* @param {object} imageData - Data for the image (filename, isCustom).
* @returns {HTMLElement} The created thumbnail element.
*/
function createThumbnailElement(imageData) {
const bg = imageData.filename;
const isCustom = imageData.isCustom;
const thumbnail = $('#background_template .bg_example').clone();
const clipper = document.createElement('div');
clipper.className = 'thumbnail-clipper lazy-load-background';
clipper.style.backgroundImage = PLACEHOLDER_IMAGE;
const titleElement = thumbnail.find('.BGSampleTitle');
clipper.appendChild(titleElement.get(0));
thumbnail.append(clipper);
const url = generateUrlParameter(bg, isCustom);
const title = isCustom ? bg.split('/').pop() : bg;
const friendlyTitle = title.slice(0, title.lastIndexOf('.'));
thumbnail.attr('title', title);
thumbnail.attr('bgfile', bg);
thumbnail.attr('custom', String(isCustom));
thumbnail.data('url', url);
titleElement.text(friendlyTitle);
return thumbnail.get(0);
}
/**
* Applies the thumbnail column count to the CSS and updates button states.
* @param {number} count - The number of columns to display.
*/
function applyThumbnailColumns(count) {
const newCount = Math.max(THUMBNAIL_COLUMNS_MIN, Math.min(count, THUMBNAIL_COLUMNS_MAX));
background_settings.thumbnailColumns = newCount;
document.documentElement.style.setProperty('--bg-thumb-columns', newCount.toString());
$('#bg_thumb_zoom_in').prop('disabled', newCount <= THUMBNAIL_COLUMNS_MIN);
$('#bg_thumb_zoom_out').prop('disabled', newCount >= THUMBNAIL_COLUMNS_MAX);
saveSettingsDebounced();
}
export function loadBackgroundSettings(settings) {
let backgroundSettings = settings.background;
if (!backgroundSettings || !backgroundSettings.name || !backgroundSettings.url) {
@@ -56,10 +109,21 @@ export function loadBackgroundSettings(settings) {
if (!Object.hasOwn(backgroundSettings, 'animation')) {
backgroundSettings.animation = false;
}
// If a value is already saved, use it. Otherwise, determine default based on screen size.
let columns = backgroundSettings.thumbnailColumns;
if (!columns) {
const isNarrowScreen = window.matchMedia('(max-width: 480px)').matches;
columns = isNarrowScreen ? THUMBNAIL_COLUMNS_DEFAULT_MOBILE : THUMBNAIL_COLUMNS_DEFAULT_DESKTOP;
}
background_settings.thumbnailColumns = columns;
applyThumbnailColumns(background_settings.thumbnailColumns);
setBackground(backgroundSettings.name, backgroundSettings.url);
setFittingClass(backgroundSettings.fitting);
$('#background_fitting').val(backgroundSettings.fitting);
$('#background_thumbnails_animation').prop('checked', background_settings.animation);
highlightSelectedBackground();
}
/**
@@ -68,46 +132,26 @@ export function loadBackgroundSettings(settings) {
*/
async function forceSetBackground(backgroundInfo) {
saveBackgroundMetadata(backgroundInfo.url);
setCustomBackground();
$('#bg1').css('background-image', backgroundInfo.url);
const list = chat_metadata[LIST_METADATA_KEY] || [];
const bg = backgroundInfo.path;
list.push(bg);
chat_metadata[LIST_METADATA_KEY] = list;
saveMetadataDebounced();
await getChatBackgroundsList();
renderChatBackgrounds();
highlightNewBackground(bg);
highlightLockedBackground();
}
async function onChatChanged() {
if (hasCustomBackground()) {
setCustomBackground();
}
else {
unsetCustomBackground();
}
const lockedUrl = chat_metadata[BG_METADATA_KEY];
await getChatBackgroundsList();
$('#bg1').css('background-image', lockedUrl || background_settings.url);
renderChatBackgrounds();
highlightLockedBackground();
}
async function getChatBackgroundsList() {
const list = chat_metadata[LIST_METADATA_KEY];
const listEmpty = !Array.isArray(list) || list.length === 0;
$('#bg_custom_content').empty();
$('#bg_chat_hint').toggle(listEmpty);
if (listEmpty) {
return;
}
for (const bg of list) {
const template = await getBackgroundFromTemplate(bg, true);
$('#bg_custom_content').append(template);
}
activateLazyLoader();
highlightSelectedBackground();
}
function getBackgroundPath(fileUrl) {
@@ -115,59 +159,53 @@ function getBackgroundPath(fileUrl) {
}
function highlightLockedBackground() {
$('.bg_example').removeClass('locked');
$('.bg_example.locked-background').removeClass('locked-background');
const lockedBackground = chat_metadata[BG_METADATA_KEY];
const lockedBackgroundUrl = chat_metadata[BG_METADATA_KEY];
if (!lockedBackground) {
if (lockedBackgroundUrl) {
$('.bg_example').filter(function () {
return $(this).data('url') === lockedBackgroundUrl;
}).addClass('locked-background');
}
}
/**
* Locks the background for the current chat
* @param {Event|null} event
*/
function onLockBackgroundClick(event = null) {
if (!getCurrentChatId()) {
toastr.warning(t`Select a chat to lock the background for it`);
return;
}
$('.bg_example').each(function () {
const url = $(this).data('url');
if (url === lockedBackground) {
$(this).addClass('locked');
}
});
}
// Take the global background's URL and save it to the chat's metadata.
const urlToLock = event ? $(event.target).closest('.bg_example').data('url') : background_settings.url;
saveBackgroundMetadata(urlToLock);
$('#bg1').css('background-image', urlToLock);
/**
* Locks the background for the current chat
* @param {Event} e Click event
* @returns {string} Empty string
*/
function onLockBackgroundClick(e) {
e?.stopPropagation();
const chatName = getCurrentChatId();
if (!chatName) {
toastr.warning('Select a chat to lock the background for it');
return '';
}
const relativeBgImage = getUrlParameter(this) ?? background_settings.url;
saveBackgroundMetadata(relativeBgImage);
setCustomBackground();
// Update UI states to reflect the new lock.
highlightLockedBackground();
return '';
}
/**
* Locks the background for the current chat
* @param {Event} e Click event
* @returns {string} Empty string
* Unlocks the background for the current chat
* @param {Event|null} _event
*/
function onUnlockBackgroundClick(e) {
e?.stopPropagation();
function onUnlockBackgroundClick(_event = null) {
// Delete the lock from the chat's metadata.
removeBackgroundMetadata();
unsetCustomBackground();
// Revert the view to the current global background.
$('#bg1').css('background-image', background_settings.url);
// Update UI states to reflect the removal of the lock.
highlightLockedBackground();
return '';
highlightSelectedBackground();
}
function hasCustomBackground() {
function isChatBackgroundLocked() {
return chat_metadata[BG_METADATA_KEY];
}
@@ -181,54 +219,22 @@ function removeBackgroundMetadata() {
saveMetadataDebounced();
}
function setCustomBackground() {
const file = chat_metadata[BG_METADATA_KEY];
// bg already set
if (document.getElementById('bg_custom').style.backgroundImage == file) {
return;
}
$('#bg_custom').css('background-image', file);
}
function unsetCustomBackground() {
$('#bg_custom').css('background-image', 'none');
}
function onSelectBackgroundClick() {
const isCustom = $(this).attr('custom') === 'true';
const relativeBgImage = getUrlParameter(this);
// if clicked on upload button
if (!relativeBgImage) {
return;
}
// Automatically lock the background if it's custom or other background is locked
if (hasCustomBackground() || isCustom) {
saveBackgroundMetadata(relativeBgImage);
setCustomBackground();
highlightLockedBackground();
}
highlightLockedBackground();
const customBg = window.getComputedStyle(document.getElementById('bg_custom')).backgroundImage;
// Custom background is set. Do not override the layer below
if (customBg !== 'none') {
return;
}
const bgFile = $(this).attr('bgfile');
const backgroundUrl = getBackgroundPath(bgFile);
const backgroundCssUrl = getUrlParameter(this);
// Fetching to browser memory to reduce flicker
fetch(backgroundUrl).then(() => {
setBackground(bgFile, relativeBgImage);
}).catch(() => {
console.log('Background could not be set: ' + backgroundUrl);
});
if (isChatBackgroundLocked()) {
// If a background is locked, update the locked background directly
saveBackgroundMetadata(backgroundCssUrl);
$('#bg1').css('background-image', backgroundCssUrl);
highlightLockedBackground();
} else {
// Otherwise, update the global background setting
setBackground(bgFile, backgroundCssUrl);
}
// Update UI highlights to reflect the changes.
highlightSelectedBackground();
}
async function onCopyToSystemBackgroundClick(e) {
@@ -257,7 +263,7 @@ async function onCopyToSystemBackgroundClick(e) {
const index = list.indexOf(bgNames.oldBg);
list.splice(index, 1);
saveMetadataDebounced();
await getChatBackgroundsList();
renderChatBackgrounds();
}
/**
@@ -382,29 +388,32 @@ async function onDeleteBackgroundClick(e) {
list.splice(index, 1);
}
const siblingSelector = '.bg_example:not(#form_bg_download)';
const nextBg = bgToDelete.next(siblingSelector);
const prevBg = bgToDelete.prev(siblingSelector);
const anyBg = $(siblingSelector);
if (bg === background_settings.name) {
const siblingSelector = '.bg_example';
const nextBg = bgToDelete.next(siblingSelector);
const prevBg = bgToDelete.prev(siblingSelector);
if (nextBg.length > 0) {
nextBg.trigger('click');
} else if (prevBg.length > 0) {
prevBg.trigger('click');
} else {
$(anyBg[Math.floor(Math.random() * anyBg.length)]).trigger('click');
if (nextBg.length > 0) {
nextBg.trigger('click');
} else if (prevBg.length > 0) {
prevBg.trigger('click');
} else {
const anyOtherBg = $('.bg_example').not(bgToDelete).first();
if (anyOtherBg.length > 0) {
anyOtherBg.trigger('click');
}
}
}
bgToDelete.remove();
if (url === chat_metadata[BG_METADATA_KEY]) {
removeBackgroundMetadata();
unsetCustomBackground();
highlightLockedBackground();
}
if (isCustom) {
await getChatBackgroundsList();
renderChatBackgrounds();
saveMetadataDebounced();
}
}
@@ -445,6 +454,47 @@ async function autoBackgroundCommand() {
return '';
}
/**
* Renders the system backgrounds gallery.
* @param {string[]} [backgrounds] - Optional filtered list of backgrounds.
*/
function renderSystemBackgrounds(backgrounds) {
const sourceList = backgrounds || [];
const container = $('#bg_menu_content');
container.empty();
if (sourceList.length === 0) return;
sourceList.forEach(bg => {
const imageData = { filename: bg, isCustom: false };
const thumbnail = createThumbnailElement(imageData);
container.append(thumbnail);
});
activateLazyLoader();
}
/**
* Renders the chat-specific (custom) backgrounds gallery.
* @param {string[]} [backgrounds] - Optional filtered list of backgrounds.
*/
function renderChatBackgrounds(backgrounds) {
const sourceList = backgrounds ?? (chat_metadata[LIST_METADATA_KEY] || []);
const container = $('#bg_custom_content');
container.empty();
$('#bg_chat_hint').toggle(!sourceList.length);
if (sourceList.length === 0) return;
sourceList.forEach(bg => {
const imageData = { filename: bg, isCustom: true };
const thumbnail = createThumbnailElement(imageData);
container.append(thumbnail);
});
activateLazyLoader();
}
export async function getBackgrounds() {
const response = await fetch('/api/backgrounds/all', {
method: 'POST',
@@ -454,12 +504,9 @@ export async function getBackgrounds() {
if (response.ok) {
const { images, config } = await response.json();
Object.assign(THUMBNAIL_CONFIG, config);
$('#bg_menu_content').children('div').remove();
for (const bg of images) {
const template = await getBackgroundFromTemplate(bg, false);
$('#bg_menu_content').append(template);
}
activateLazyLoader();
renderSystemBackgrounds(images);
highlightSelectedBackground();
}
}
@@ -481,14 +528,19 @@ function activateLazyLoader() {
lazyLoadObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.target instanceof HTMLElement && entry.isIntersecting) {
const target = entry.target;
const bg = target.getAttribute('bgfile');
const isCustom = target.getAttribute('custom') === 'true';
resolveImageUrl(bg, isCustom)
.then(url => { target.style.backgroundImage = url; })
.catch(() => { target.style.backgroundImage = PLACEHOLDER_IMAGE; });
target.classList.remove('lazy-load-background');
observer.unobserve(target);
const clipper = entry.target;
const parentThumbnail = clipper.closest('.bg_example');
if (parentThumbnail) {
const bg = parentThumbnail.getAttribute('bgfile');
const isCustom = parentThumbnail.getAttribute('custom') === 'true';
resolveImageUrl(bg, isCustom)
.then(url => { clipper.style.backgroundImage = url; })
.catch(() => { clipper.style.backgroundImage = PLACEHOLDER_IMAGE; });
}
clipper.classList.remove('lazy-load-background');
observer.unobserve(clipper);
}
});
}, options);
@@ -529,30 +581,11 @@ async function resolveImageUrl(bg, isCustom) {
return `url("${thumbnailUrl}")`;
}
/**
* Instantiates a background template
* @param {string} bg Path to background
* @param {boolean} isCustom Whether the background is custom
* @returns {Promise<JQuery<HTMLElement>>} Background template
*/
async function getBackgroundFromTemplate(bg, isCustom) {
const template = $('#background_template .bg_example').clone();
const url = generateUrlParameter(bg, isCustom);
const title = isCustom ? bg.split('/').pop() : bg;
const friendlyTitle = title.slice(0, title.lastIndexOf('.'));
template.attr('title', title);
template.attr('bgfile', bg);
template.attr('custom', String(isCustom));
template.data('url', url);
template.addClass('lazy-load-background');
template.css('background-image', PLACEHOLDER_IMAGE);
template.find('.BGSampleTitle').text(friendlyTitle);
return template;
}
async function setBackground(bg, url) {
$('#bg1').css('background-image', url);
// Only change the visual background if one is not locked for the current chat.
if (!isChatBackgroundLocked()) {
$('#bg1').css('background-image', url);
}
background_settings.name = bg;
background_settings.url = url;
saveSettingsDebounced();
@@ -680,25 +713,39 @@ function highlightNewBackground(bg) {
* @param {string} fitting Fitting type
*/
function setFittingClass(fitting) {
const backgrounds = $('#bg1, #bg_custom');
const backgrounds = $('#bg1');
for (const option of ['cover', 'contain', 'stretch', 'center']) {
backgrounds.toggleClass(option, option === fitting);
}
background_settings.fitting = fitting;
}
function highlightSelectedBackground() {
$('.bg_example.selected-background').removeClass('selected-background');
// The "selected" highlight should always reflect the global background setting.
const activeUrl = background_settings.url;
if (activeUrl) {
// Find the thumbnail whose data-url attribute matches the active URL
$('.bg_example').filter(function () {
return $(this).data('url') === activeUrl;
}).addClass('selected-background');
}
}
function onBackgroundFilterInput() {
const filterValue = String($(this).val()).toLowerCase();
$('#bg_menu_content > div').each(function () {
const $bgContent = $(this);
if ($bgContent.attr('title').toLowerCase().includes(filterValue)) {
$bgContent.show();
} else {
$bgContent.hide();
}
const filterValue = String($('#bg-filter').val()).toLowerCase();
$('#bg_menu_content > .bg_example, #bg_custom_content > .bg_example').each(function () {
const $bg = $(this);
const title = $bg.attr('title') || '';
const hasMatch = title.toLowerCase().includes(filterValue);
$bg.toggle(hasMatch);
});
}
const debouncedOnBackgroundFilterInput = debounce(onBackgroundFilterInput, debounce_timeout.standard);
export function initBackgrounds() {
eventSource.on(event_types.CHAT_CHANGED, onChatChanged);
eventSource.on(event_types.FORCE_SET_BACKGROUND, forceSetBackground);
@@ -715,6 +762,11 @@ export function initBackgrounds() {
$context.addClass('mobile-menu-open');
}
})
.off('blur', '.bg_example.mobile-menu-open').on('blur', '.bg_example.mobile-menu-open', function () {
if (!$(this).is(':focus-within')) {
$(this).removeClass('mobile-menu-open');
}
})
.off('click', '.jg-button').on('click', '.jg-button', function (e) {
e.stopPropagation();
const action = $(this).data('action');
@@ -738,18 +790,30 @@ export function initBackgrounds() {
}
});
$('#bg_thumb_zoom_in').on('click', () => {
applyThumbnailColumns(background_settings.thumbnailColumns - 1);
});
$('#bg_thumb_zoom_out').on('click', () => {
applyThumbnailColumns(background_settings.thumbnailColumns + 1);
});
$('#auto_background').on('click', autoBackgroundCommand);
$('#add_bg_button').on('change', onBackgroundUploadSelected);
$('#bg-filter').on('input', onBackgroundFilterInput);
$('#bg-filter').on('input', () => debouncedOnBackgroundFilterInput());
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'lockbg',
callback: () => onLockBackgroundClick(new CustomEvent('click')),
callback: () => {
onLockBackgroundClick();
return '';
},
aliases: ['bglock'],
helpString: 'Locks a background for the currently selected chat',
}));
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'unlockbg',
callback: () => onUnlockBackgroundClick(new CustomEvent('click')),
callback: () => {
onUnlockBackgroundClick();
return '';
},
aliases: ['bgunlock'],
helpString: 'Unlocks a background for the currently selected chat',
}));
@@ -774,4 +838,10 @@ export function initBackgrounds() {
await getBackgrounds();
await onChatChanged();
});
setupScrollToTop({
scrollContainerId: 'bg-scrollable-content',
buttonId: 'bg-scroll-top',
drawerId: 'Backgrounds',
});
}
+2 -3
View File
@@ -750,10 +750,9 @@ function getStyleContentsFromMarkdown(text) {
return '';
}
const div = document.createElement('div');
const html = converter.makeHtml(substituteParams(text));
div.innerHTML = html;
const styleElements = Array.from(div.querySelectorAll('style'));
const parsedDocument = new DOMParser().parseFromString(html, 'text/html');
const styleElements = Array.from(parsedDocument.querySelectorAll('style'));
return styleElements
.filter(s => s.textContent.trim().length > 0)
.map(s => s.textContent.trim())
+1
View File
@@ -51,6 +51,7 @@ export const inject_ids = {
DEPTH_PROMPT_INDEX: (index) => `DEPTH_PROMPT_${index}`,
CUSTOM_WI_DEPTH: 'customDepthWI',
CUSTOM_WI_DEPTH_ROLE: (depth, role) => `customDepthWI_${depth}_${role}`,
CUSTOM_WI_OUTLET: (key) => `customWIOutlet_${key}`,
};
export const COMETAPI_IGNORE_PATTERNS = [
+3 -1
View File
@@ -49,6 +49,7 @@ import EventSourceStream from './sse-stream.js';
* @property {string} [custom_url] - Optional custom URL
* @property {string} [reverse_proxy] - Optional reverse proxy URL
* @property {string} [proxy_password] - Optional proxy password
* @property {string} [custom_prompt_post_processing] - Optional custom prompt post-processing
*/
/** @typedef {Record<string, any> & ChatCompletionPayloadBase} ChatCompletionPayload */
@@ -414,7 +415,7 @@ export class ChatCompletionService {
* @param {ChatCompletionPayload} custom
* @returns {ChatCompletionPayload}
*/
static createRequestData({ stream = false, messages, model, chat_completion_source, max_tokens, temperature, custom_url, reverse_proxy, proxy_password, ...props }) {
static createRequestData({ stream = false, messages, model, chat_completion_source, max_tokens, temperature, custom_url, reverse_proxy, proxy_password, custom_prompt_post_processing, ...props }) {
const payload = {
stream,
messages,
@@ -425,6 +426,7 @@ export class ChatCompletionService {
custom_url,
reverse_proxy,
proxy_password,
custom_prompt_post_processing,
use_makersuite_sysprompt: true,
claude_use_sysprompt: true,
...props,
+66
View File
@@ -0,0 +1,66 @@
import { throttle } from './utils.js';
export function initDomHandlers() {
handleInputWheel();
}
/**
* Trap mouse wheel inside of focused number inputs to prevent scrolling their containers.
* Instead of firing wheel events, manually update both slider and input values.
* This also makes wheel work inside Firefox.
*/
function handleInputWheel() {
const minInterval = 25; // ms
/**
* Update input and slider values based on wheel delta
* @param {HTMLInputElement} input The number input element
* @param {HTMLInputElement|null} slider The associated range input element, if any
* @param {number} deltaY The wheel deltaY value
*/
function updateValue(input, slider, deltaY) {
const currentValue = parseFloat(input.value);
const step = parseFloat(input.step);
const min = parseFloat(input.min);
const max = parseFloat(input.max);
// Sanity checks before trying to calculate new value
if (isNaN(currentValue) || isNaN(step) || step <= 0 || deltaY === 0) return;
// Calculate new value based on wheel movement delta (negative = up, positive = down)
let newValue = currentValue + (deltaY > 0 ? -step : step);
// Ensure it's a multiple of step
newValue = Math.round(newValue / step) * step;
// Ensure it's within the min and max range (NaN-aware)
newValue = !isNaN(min) ? Math.max(newValue, min) : newValue;
newValue = !isNaN(max) ? Math.min(newValue, max) : newValue;
// Simple fix for floating point precision issues
newValue = Math.round(newValue * 1e10) / 1e10;
// Update both input and slider values
input.value = newValue.toString();
if (slider) slider.value = newValue.toString();
// Trigger input event (just ONE) to update any listeners
const inputEvent = new Event('input', { bubbles: true });
input.dispatchEvent(inputEvent);
}
const updateValueThrottled = throttle(updateValue, minInterval);
document.addEventListener('wheel', (e) => {
// Try to carefully narrow down if we even need to fire this handler
const input = document.activeElement instanceof HTMLInputElement ? document.activeElement : null;
if (input && input.type === 'number' && input.hasAttribute('step')) {
const parent = input.closest('.range-block-range-and-counter') ?? input.closest('div') ?? input.parentElement;
const slider = /** @type {HTMLInputElement} */ (parent?.querySelector('input[type="range"]'));
// Stop propagation for either target
if (e.target === input || (slider && e.target === slider)) {
e.stopPropagation();
e.preventDefault();
updateValueThrottled(input, slider, e.deltaY);
}
}
}, { passive: false });
}
+4
View File
@@ -12,6 +12,7 @@ export const event_types = {
MESSAGE_FILE_EMBEDDED: 'message_file_embedded',
MESSAGE_REASONING_EDITED: 'message_reasoning_edited',
MESSAGE_REASONING_DELETED: 'message_reasoning_deleted',
MESSAGE_SWIPE_DELETED: 'message_swipe_deleted',
MORE_MESSAGES_LOADED: 'more_messages_loaded',
IMPERSONATE_READY: 'impersonate_ready',
CHAT_CHANGED: 'chat_id_changed',
@@ -36,6 +37,7 @@ export const event_types = {
OAI_PRESET_IMPORT_READY: 'oai_preset_import_ready',
WORLDINFO_SETTINGS_UPDATED: 'worldinfo_settings_updated',
WORLDINFO_UPDATED: 'worldinfo_updated',
CHARACTER_EDITOR_OPENED: 'character_editor_opened',
CHARACTER_EDITED: 'character_edited',
CHARACTER_PAGE_LOADED: 'character_page_loaded',
CHARACTER_GROUP_OVERLAY_STATE_CHANGE_BEFORE: 'character_group_overlay_state_change_before',
@@ -85,6 +87,8 @@ export const event_types = {
SECRET_EDITED: 'secret_edited',
PRESET_CHANGED: 'preset_changed',
PRESET_DELETED: 'preset_deleted',
PRESET_RENAMED: 'preset_renamed',
PRESET_RENAMED_BEFORE: 'preset_renamed_before',
MAIN_API_CHANGED: 'main_api_changed',
WORLDINFO_ENTRIES_LOADED: 'worldinfo_entries_loaded',
};
+3
View File
@@ -190,7 +190,10 @@ export const extension_settings = {
regex: [],
/** @type {import('./extensions/regex/index.js').RegexPreset[]} */
regex_presets: [],
/** @type {string[]} */
character_allowed_regex: [],
/** @type {Record<string, string[]>} */
preset_allowed_regex: {},
tts: {},
sd: {
prompts: {},
+37 -3
View File
@@ -10,7 +10,7 @@ import { POPUP_TYPE, Popup, callGenericPopup } from '../../popup.js';
import { executeSlashCommandsWithOptions } from '../../slash-commands.js';
import { accountStorage } from '../../util/AccountStorage.js';
import { flashHighlight, getStringHash, isValidUrl } from '../../utils.js';
import { t } from '../../i18n.js';
import { t, translate } from '../../i18n.js';
export { MODULE_NAME };
const MODULE_NAME = 'assets';
@@ -60,6 +60,36 @@ const KNOWN_TYPES = {
'blip': t`Blip sounds`,
};
const EMPTY_AUTHOR = {
name: '',
url: '',
};
/**
* Extracts the repository author from a given URL.
* @param {string} url - The URL of the repository.
* @returns {{name: string, url: string}} Object containing the author's name and URL, or empty strings if not found.
*/
function getAuthorFromUrl(url) {
const result = structuredClone(EMPTY_AUTHOR);
try {
const parsedUrl = new URL(url);
const pathSegments = parsedUrl.pathname.split('/').filter(s => s.length > 0);
// TODO: Handle non-GitHub URLs if needed
if (parsedUrl.host === 'github.com' && pathSegments.length >= 2) {
result.name = pathSegments[0];
result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`;
}
}
catch (error) {
console.debug(DEBUG_PREFIX, 'Error parsing URL:', error);
}
return result;
}
async function downloadAssetsList(url) {
updateCurrentAssets().then(async function () {
fetch(url, { cache: 'no-cache' })
@@ -88,7 +118,8 @@ async function downloadAssetsList(url) {
$('#assets_type_select').append($('<option />', { value: '', text: t`All` }));
for (const type of assetTypes) {
const option = $('<option />', { value: type, text: t([KNOWN_TYPES[type] || type]) });
const text = translate(KNOWN_TYPES[type] || type);
const option = $('<option />', { value: type, text: text });
$('#assets_type_select').append(option);
}
@@ -184,10 +215,11 @@ async function downloadAssetsList(url) {
const title = assetType === 'extension' ? t`Extension repo/guide:` + ` ${url}` : t`Preview in browser`;
const previewIcon = (assetType === 'extension' || assetType === 'character') ? 'fa-arrow-up-right-from-square' : 'fa-headphones-simple';
const toolTag = assetType === 'extension' && asset['tool'];
const author = url && assetType === 'extension' ? getAuthorFromUrl(url) : EMPTY_AUTHOR;
const assetBlock = $('<i></i>')
.append(element)
.append(`<div class="flex-container flexFlowColumn flexNoGap">
.append(`<div class="flex-container flexFlowColumn flexNoGap wide100p overflowHidden">
<span class="asset-name flex-container alignitemscenter">
<b>${displayName}</b>
<a class="asset_preview" href="${url}" target="_blank" title="${title}">
@@ -195,6 +227,8 @@ async function downloadAssetsList(url) {
</a>` +
(toolTag ? '<span class="tag" title="' + t`Adds a function tool` + '"><i class="fa-solid fa-sm fa-wrench"></i> ' +
t`Tool` + '</span>' : '') +
'<span class="expander"></span>' +
(author.name ? `<a href="${author.url}" target="_blank" class="asset-author-info"><i class="fa-solid fa-at fa-xs"></i><span>${author.name}</span></a>` : '') +
`</span>
<small class="asset-description">
${description}
+27 -2
View File
@@ -35,14 +35,15 @@
color: inherit;
}
.assets-list-div > i {
.assets-list-div>i {
display: flex;
flex-direction: row;
align-items: center;
justify-content: left;
padding: 5px;
padding: 10px 5px;
font-style: normal;
gap: 5px;
border-bottom: 1px solid var(--SmartThemeBorderColor);
}
.assets-list-div i span:first-of-type {
@@ -173,3 +174,27 @@
opacity: 0.9;
margin-left: 2px;
}
.asset-name .asset-author-info {
display: flex;
align-items: baseline;
gap: 2px;
opacity: 0.7;
font-size: 0.85em;
overflow: hidden;
}
.asset-name .asset-author-info>span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.asset-name .asset-author-info:hover {
opacity: 1;
transition: opacity var(--animation-duration) ease-in-out;
}
.asset-name>b {
font-weight: 600;
}
+9 -1
View File
@@ -1,6 +1,6 @@
import { ensureImageFormatSupported, getBase64Async, getFileExtension, isTrueBoolean, saveBase64AsFile } from '../../utils.js';
import { getContext, getApiUrl, doExtrasFetch, extension_settings, modules, renderExtensionTemplateAsync } from '../../extensions.js';
import { appendMediaToMessage, eventSource, event_types, getRequestHeaders, saveChatConditional, saveSettingsDebounced, substituteParamsExtended } from '../../../script.js';
import { appendMediaToMessage, chat_metadata, eventSource, event_types, getRequestHeaders, saveChatConditional, saveSettingsDebounced, substituteParamsExtended } from '../../../script.js';
import { getMessageTimeStamp } from '../../RossAscends-mods.js';
import { SECRET_KEYS, secret_state } from '../../secrets.js';
import { getMultimodalCaption } from '../shared.js';
@@ -174,6 +174,7 @@ async function sendCaptionedMessage(caption, image) {
inline_image: !!extension_settings.caption.show_in_chat,
},
};
chat_metadata['tainted'] = true;
context.chat.push(message);
const messageId = context.chat.length - 1;
await eventSource.emit(event_types.MESSAGE_SENT, messageId);
@@ -549,6 +550,8 @@ jQuery(async function () {
await processEndpoint('pollinations', '/api/backends/chat-completions/multimodal-models/pollinations');
await processEndpoint('nanogpt', '/api/backends/chat-completions/multimodal-models/nanogpt');
await processEndpoint('electronhub', '/api/backends/chat-completions/multimodal-models/electronhub');
await processEndpoint('mistral', '/api/backends/chat-completions/multimodal-models/mistral');
await processEndpoint('xai', '/api/backends/chat-completions/multimodal-models/xai');
}
await addSettings();
@@ -626,6 +629,11 @@ jQuery(async function () {
extension_settings.caption.ollama_custom_model = String($('#caption_ollama_custom_model').val()).trim();
saveSettingsDebounced();
});
$('#caption_refresh_models').on('click', async () => {
extension_settings.caption.multimodal_model = '';
await switchMultimodalBlocks();
saveSettingsDebounced();
});
const onMessageEvent = async (index) => {
if (!extension_settings.caption.auto_mode) {
+24 -45
View File
@@ -9,7 +9,7 @@
<label for="caption_source" data-i18n="Source">Source</label>
<select id="caption_source" class="text_pole">
<option value="local" data-i18n="Local">Local</option>
<option value="multimodal" data-i18n="Multimodal (OpenAI / Anthropic / llama / Google)">Multimodal (OpenAI / Anthropic / llama / Google)</option>
<option value="multimodal" data-i18n="Multimodal">Multimodal</option>
<option value="extras" data-i18n="Extras">Extras (deprecated)</option>
<option value="horde" data-i18n="Horde">Horde</option>
</select>
@@ -18,7 +18,7 @@
<label for="caption_multimodal_api" data-i18n="API">API</label>
<select id="caption_multimodal_api" class="flex1 text_pole">
<option value="aimlapi">AI/ML API</option>
<option value="anthropic">Anthropic</option>
<option value="anthropic">Claude</option>
<option value="cohere">Cohere</option>
<option value="custom" data-i18n="Custom (OpenAI-compatible)">Custom (OpenAI-compatible)</option>
<option value="electronhub">Electron Hub</option>
@@ -40,23 +40,17 @@
</select>
</div>
<div class="flex1 flex-container flexFlowColumn flexNoGap">
<label for="caption_multimodal_model" data-i18n="Model">Model</label>
<label for="caption_multimodal_model" class="flex-container justifySpaceBetween">
<span data-i18n="Model">Model</span>
<div id="caption_refresh_models" class="right_menu_button margin0 padding0" title="Refresh model list" data-i18n="[title]Refresh model list">
<i class="fa-solid fa-sync"></i>
</div>
</label>
<select id="caption_multimodal_model" class="flex1 text_pole">
<!-- AI/ML API, OpenRouter, Pollinations, NanoGPT are added externally by JavaScript -->
<!-- AI/ML API, OpenRouter, Pollinations, NanoGPT, Mistral, xAI are added externally by JavaScript -->
<option data-type="cohere" value="c4ai-aya-vision-8b">c4ai-aya-vision-8b</option>
<option data-type="cohere" value="c4ai-aya-vision-32b">c4ai-aya-vision-32b</option>
<option data-type="cohere" value="command-a-vision-07-2025">command-a-vision-07-2025</option>
<option data-type="mistral" value="pixtral-12b-latest">pixtral-12b-latest</option>
<option data-type="mistral" value="pixtral-12b-2409">pixtral-12b-2409</option>
<option data-type="mistral" value="pixtral-large-latest">pixtral-large-latest</option>
<option data-type="mistral" value="pixtral-large-2411">pixtral-large-2411</option>
<option data-type="mistral" value="mistral-large-pixtral-2411">mistral-large-pixtral-2411</option>
<option data-type="mistral" value="mistral-small-2503">mistral-small-2503</option>
<option data-type="mistral" value="mistral-small-2506">mistral-small-2506</option>
<option data-type="mistral" value="mistral-small-latest">mistral-small-latest</option>
<option data-type="mistral" value="mistral-medium-latest">mistral-medium-latest</option>
<option data-type="mistral" value="mistral-medium-2505">mistral-medium-2505</option>
<option data-type="mistral" value="mistral-medium-2508">mistral-medium-2508</option>
<option data-type="moonshot" value="moonshot-v1-8k-vision-preview">moonshot-v1-8k-vision-preview</option>
<option data-type="moonshot" value="moonshot-v1-32k-vision-preview">moonshot-v1-32k-vision-preview</option>
<option data-type="moonshot" value="moonshot-v1-128k-vision-preview">moonshot-v1-128k-vision-preview</option>
@@ -87,6 +81,10 @@
<option data-type="openai" value="o4-mini-2025-04-16">o4-mini-2025-04-16</option>
<option data-type="openai" value="gpt-4.5-preview">gpt-4.5-preview</option>
<option data-type="openai" value="gpt-4.5-preview-2025-02-27">gpt-4.5-preview-2025-02-27</option>
<option data-type="anthropic" value="claude-sonnet-4-5">claude-sonnet-4-5</option>
<option data-type="anthropic" value="claude-sonnet-4-5-20250929">claude-sonnet-4-5-20250929</option>
<option data-type="anthropic" value="claude-haiku-4-5">claude-haiku-4-5</option>
<option data-type="anthropic" value="claude-haiku-4-5-20251001">claude-haiku-4-5-20251001</option>
<option data-type="anthropic" value="claude-opus-4-1">claude-opus-4-1</option>
<option data-type="anthropic" value="claude-opus-4-1-20250805">claude-opus-4-1-20250805</option>
<option data-type="anthropic" value="claude-opus-4-0">claude-opus-4-0</option>
@@ -106,49 +104,33 @@
<option data-type="google" value="gemini-2.5-pro-preview-06-05">gemini-2.5-pro-preview-06-05</option>
<option data-type="google" value="gemini-2.5-pro-preview-05-06">gemini-2.5-pro-preview-05-06</option>
<option data-type="google" value="gemini-2.5-pro-preview-03-25">gemini-2.5-pro-preview-03-25</option>
<option data-type="google" value="gemini-2.5-pro-exp-03-25">gemini-2.5-pro-exp-03-25</option>
<option data-type="google" value="gemini-2.5-flash">gemini-2.5-flash</option>
<option data-type="google" value="gemini-2.5-flash-preview-09-2025">gemini-2.5-flash-preview-09-2025</option>
<option data-type="google" value="gemini-2.5-flash-preview-05-20">gemini-2.5-flash-preview-05-20</option>
<option data-type="google" value="gemini-2.5-flash-preview-04-17">gemini-2.5-flash-preview-04-17</option>
<option data-type="google" value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
<option data-type="google" value="gemini-2.5-flash-lite-preview-09-2025">gemini-2.5-flash-lite-preview-09-2025</option>
<option data-type="google" value="gemini-2.5-flash-lite-preview-06-17">gemini-2.5-flash-lite-preview-06-17</option>
<option data-type="google" value="gemini-2.5-flash-image">gemini-2.5-flash-image</option>
<option data-type="google" value="gemini-2.5-flash-image-preview">gemini-2.5-flash-image-preview</option>
<option data-type="google" value="gemini-2.0-pro-exp-02-05">gemini-2.0-pro-exp-02-05 → 2.5-pro-exp-03-25</option>
<option data-type="google" value="gemini-2.0-pro-exp">gemini-2.0-pro-exp → 2.5-pro-exp-03-25</option>
<option data-type="google" value="gemini-exp-1206">gemini-exp-1206 → 2.5-pro-exp-03-25</option>
<option data-type="google" value="gemini-2.0-pro-exp-02-05">gemini-2.0-pro-exp-02-05 → 2.5-exp-03-25</option>
<option data-type="google" value="gemini-2.0-pro-exp">gemini-2.0-pro-exp → 2.5-exp-03-25</option>
<option data-type="google" value="gemini-exp-1206">gemini-exp-1206 → 2.5-exp-03-25</option>
<option data-type="google" value="gemini-2.0-flash-001">gemini-2.0-flash-001</option>
<option data-type="google" value="gemini-2.0-flash-exp-image-generation">gemini-2.0-flash-exp-image-generation</option>
<option data-type="google" value="gemini-2.0-flash-exp">gemini-2.0-flash-exp</option>
<option data-type="google" value="gemini-2.0-flash">gemini-2.0-flash</option>
<option data-type="google" value="gemini-2.0-flash-thinking-exp-01-21">gemini-2.0-flash-thinking-exp-01-21 → 2.5-flash-preview-04-17</option>
<option data-type="google" value="gemini-2.0-flash-thinking-exp-1219">gemini-2.0-flash-thinking-exp-1219 → 2.5-flash-preview-04-17</option>
<option data-type="google" value="gemini-2.0-flash-thinking-exp">gemini-2.0-flash-thinking-exp → 2.5-flash-preview-04-17</option>
<option data-type="google" value="gemini-2.0-flash-thinking-exp-01-21">gemini-2.0-flash-thinking-exp-01-21 → 2.5-flash-preview-5-20</option>
<option data-type="google" value="gemini-2.0-flash-thinking-exp-1219">gemini-2.0-flash-thinking-exp-1219 → 2.5-flash-preview-05-20</option>
<option data-type="google" value="gemini-2.0-flash-thinking-exp">gemini-2.0-flash-thinking-exp → 2.5-flash-preview-05-20</option>
<option data-type="google" value="gemini-2.0-flash-lite-001">gemini-2.0-flash-lite-001</option>
<option data-type="google" value="gemini-2.0-flash-lite-preview-02-05">gemini-2.0-flash-lite-preview-02-05</option>
<option data-type="google" value="gemini-2.0-flash-lite-preview">gemini-2.0-flash-lite-preview</option>
<option data-type="google" value="gemini-1.5-pro-latest">gemini-1.5-pro-latest</option>
<option data-type="google" value="gemini-1.5-pro-002">gemini-1.5-pro-002</option>
<option data-type="google" value="gemini-1.5-pro-001">gemini-1.5-pro-001</option>
<option data-type="google" value="gemini-1.5-pro">gemini-1.5-pro</option>
<option data-type="google" value="gemini-1.5-flash-latest">gemini-1.5-flash-latest</option>
<option data-type="google" value="gemini-1.5-flash-002">gemini-1.5-flash-002</option>
<option data-type="google" value="gemini-1.5-flash-001">gemini-1.5-flash-001</option>
<option data-type="google" value="gemini-1.5-flash">gemini-1.5-flash</option>
<option data-type="google" value="gemini-1.5-flash-8b-latest">gemini-1.5-flash-8b-latest</option>
<option data-type="google" value="gemini-1.5-flash-8b-001">gemini-1.5-flash-8b-001</option>
<option data-type="google" value="gemini-1.5-flash-8b-exp-0924">gemini-1.5-flash-8b-exp-0924</option>
<option data-type="google" value="gemini-1.5-flash-8b-exp-0827">gemini-1.5-flash-8b-exp-0827</option>
<option data-type="google" value="learnlm-2.0-flash-experimental">learnlm-2.0-flash-experimental</option>
<option data-type="google" value="learnlm-1.5-pro-experimental">learnlm-1.5-pro-experimental</option>
<option data-type="google" value="gemini-robotics-er-1.5-preview">gemini-robotics-er-1.5-preview</option>
<option data-type="vertexai" value="gemini-2.5-pro">gemini-2.5-pro</option>
<option data-type="vertexai" value="gemini-2.5-pro-preview-06-05">gemini-2.5-pro-preview-06-05</option>
<option data-type="vertexai" value="gemini-2.5-pro-preview-05-06">gemini-2.5-pro-preview-05-06</option>
<option data-type="vertexai" value="gemini-2.5-pro-preview-03-25">gemini-2.5-pro-preview-03-25</option>
<option data-type="vertexai" value="gemini-2.5-flash">gemini-2.5-flash</option>
<option data-type="vertexai" value="gemini-2.5-flash-preview-05-20">gemini-2.5-flash-preview-05-20</option>
<option data-type="vertexai" value="gemini-2.5-flash-preview-04-17">gemini-2.5-flash-preview-04-17</option>
<option data-type="vertexai" value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
<option data-type="vertexai" value="gemini-2.5-flash-lite-preview-06-17">gemini-2.5-flash-lite-preview-06-17</option>
<option data-type="vertexai" value="gemini-2.5-flash-image">gemini-2.5-flash-image</option>
<option data-type="vertexai" value="gemini-2.5-flash-image-preview">gemini-2.5-flash-image-preview</option>
<option data-type="vertexai" value="gemini-2.0-flash-001">gemini-2.0-flash-001</option>
<option data-type="vertexai" value="gemini-2.0-flash-lite-001">gemini-2.0-flash-lite-001</option>
@@ -174,9 +156,6 @@
<option data-type="koboldcpp" value="koboldcpp_current" data-i18n="currently_loaded">[Currently loaded]</option>
<option data-type="vllm" value="vllm_current" data-i18n="currently_selected">[Currently selected]</option>
<option data-type="custom" value="custom_current" data-i18n="currently_selected">[Currently selected]</option>
<option data-type="xai" value="grok-4-0709">grok-4-0709</option>
<option data-type="xai" value="grok-2-vision-1212">grok-2-vision-1212</option>
<option data-type="xai" value="grok-vision-beta">grok-vision-beta</option>
</select>
</div>
<div data-type="ollama">
@@ -1,6 +1,6 @@
import { DOMPurify, Fuse } from '../../../lib.js';
import { event_types, eventSource, main_api, saveSettingsDebounced } from '../../../script.js';
import { event_types, eventSource, main_api, online_status, saveSettingsDebounced } from '../../../script.js';
import { extension_settings, renderExtensionTemplateAsync } from '../../extensions.js';
import { callGenericPopup, Popup, POPUP_RESULT, POPUP_TYPE } from '../../popup.js';
import { SlashCommand } from '../../slash-commands/SlashCommand.js';
@@ -11,7 +11,7 @@ import { SlashCommandDebugController } from '../../slash-commands/SlashCommandDe
import { enumTypes, SlashCommandEnumValue } from '../../slash-commands/SlashCommandEnumValue.js';
import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
import { SlashCommandScope } from '../../slash-commands/SlashCommandScope.js';
import { collapseSpaces, getUniqueName, isFalseBoolean, uuidv4 } from '../../utils.js';
import { collapseSpaces, getUniqueName, isFalseBoolean, uuidv4, waitUntilCondition } from '../../utils.js';
import { t } from '../../i18n.js';
import { getSecretLabelById } from '../../secrets.js';
@@ -167,6 +167,12 @@ const profilesProvider = () => [
* @property {string} [stop-strings] Custom Stopping Strings
* @property {string} [start-reply-with] Start Reply With
* @property {string} [reasoning-template] Reasoning Template
* @property {string} [prompt-post-processing] Prompt Post-Processing
* @property {string} [sysprompt] System Prompt Name
* @property {string} [sysprompt-state] Use System Prompt
* @property {string} [api-url] Server URL
* @property {string} [secret-id] Secret ID
* @property {string} [regex-preset] Regex Preset ID
* @property {string[]} [exclude] Commands to exclude
*/
@@ -684,6 +690,13 @@ async function renderDetailsContent(detailsContent) {
defaultValue: 'true',
enumList: commonEnumProviders.boolean('trueFalse')(),
}),
SlashCommandNamedArgument.fromProps({
name: 'timeout',
description: 'Maximum time to wait for the API connection to be established, in milliseconds. Set to 0 to disable. Only applies when await=true.',
isRequired: false,
typeList: [ARGUMENT_TYPE.NUMBER],
defaultValue: '2000',
}),
],
callback: async (args, value) => {
if (!value || typeof value !== 'string') {
@@ -715,6 +728,13 @@ async function renderDetailsContent(detailsContent) {
if (shouldAwait) {
await awaitPromise;
// We should also await the connection to be established
const parsedTimeout = parseInt(args?.timeout?.toString());
const timeout = !isNaN(parsedTimeout) ? Math.max(0, parsedTimeout) : 2000;
if (timeout > 0) {
await waitUntilCondition(() => online_status !== 'no_connection', timeout, 100, { rejectOnTimeout: false });
}
}
return profile.name;
+1 -1
View File
@@ -993,7 +993,7 @@ function doPopout(e) {
originalElement.empty();
originalElement.html('<div class="flex-container alignitemscenter justifyCenter wide100p"><small>Currently popped out</small></div>');
newElement.append(controlBarHtml).append(originalHTMLClone);
$('body').append(newElement);
$('#movingDivs').append(newElement);
newElement.transition({ opacity: 1, duration: animation_duration, easing: animation_easing });
$('#summaryExtensionDrawerContents').addClass('scrollableInnerFull');
setMemoryContext(prevSummaryBoxContents, false); //paste prev summary box contents into popout box
@@ -11,6 +11,7 @@
<button
id="regex_debugger_save_order"
class="menu_button menu_button_icon interactable"
data-i18n="[title]ext_regex_debugger_save_order_help"
title="Save current rule order"
tabindex="0"
>
@@ -53,6 +54,7 @@
<button
id="regex_debugger_run_test"
class="menu_button menu_button_icon interactable"
data-i18n="[title]ext_regex_debugger_run_test_help"
title="Run the test pipeline"
tabindex="0"
>
@@ -115,6 +117,7 @@
<div
id="regex_debugger_expand_steps"
class="menu_button menu_button_icon"
data-i18n="[title]Expand view"
title="Expand view"
>
<i class="fa-solid fa-expand"></i>
@@ -132,6 +135,7 @@
<div
id="regex_debugger_expand_final"
class="menu_button menu_button_icon"
data-i18n="[title]Expand view"
title="Expand view"
>
<i class="fa-solid fa-expand"></i>
@@ -158,7 +162,7 @@
<code class="rule-regex"></code>
<small class="rule-scope"></small>
</div>
<div class="menu_button menu_button_icon edit_rule" title="Edit Rule">
<div class="menu_button menu_button_icon edit_rule" data-i18n="[title]Edit Rule" title="Edit Rule">
<i class="fa-solid fa-pencil"></i>
</div>
</li>
+35 -3
View File
@@ -16,6 +16,10 @@
<i class="fa-solid fa-address-card"></i>
<small data-i18n="ext_regex_new_scoped_script">+ Scoped</small>
</div>
<div id="open_preset_editor" class="menu_button menu_button_icon" data-i18n="[title]ext_regex_new_preset_script_desc" title="New preset regex script">
<i class="fa-solid fa-sliders"></i>
<small data-i18n="ext_regex_new_preset_script">+ Preset</small>
</div>
<div id="import_regex" class="menu_button menu_button_icon">
<i class="fa-solid fa-file-import"></i>
<small data-i18n="ext_regex_import_script">Import</small>
@@ -31,7 +35,8 @@
<small data-i18n="ext_regex_debugger">Debugger</small>
</div>
</div>
<div class="regex_bulk_operations flex-container justifyCenter">
<hr class="regex_bulk_operations_hr" />
<div class="regex_bulk_operations flex-container">
<div id="bulk_select_all_toggle" class="menu_button menu_button_icon" title="Toggle Select All">
<i class="fa-solid fa-check-double"></i>
</div>
@@ -43,6 +48,18 @@
<i class="fa-solid fa-toggle-off"></i>
<small data-i18n="Disable">Disable</small>
</div>
<div id="bulk_regex_move_to_global" class="menu_button menu_button_icon" hidden>
<i class="fa-solid fa-globe"></i>
<small data-i18n="ext_regex_move_to_global">Move to global scripts</small>
</div>
<div id="bulk_regex_move_to_scoped" class="menu_button menu_button_icon" hidden>
<i class="fa-solid fa-address-card"></i>
<small data-i18n="ext_regex_move_to_scoped">Move to scoped scripts</small>
</div>
<div id="bulk_regex_move_to_preset" class="menu_button menu_button_icon" hidden>
<i class="fa-solid fa-sliders"></i>
<small data-i18n="ext_regex_move_to_preset">Move to preset scripts</small>
</div>
<div id="bulk_export_regex" class="menu_button menu_button_icon">
<i class="fa-solid fa-file-export"></i>
<small data-i18n="Export">Export</small>
@@ -69,7 +86,7 @@
</div>
</div>
<hr />
<div id="global_scripts_block" class="padding5">
<div id="global_scripts_block">
<div>
<strong data-i18n="ext_regex_global_scripts">Global Scripts</strong>
</div>
@@ -79,7 +96,7 @@
<div id="saved_regex_scripts" no-scripts-text="No scripts found" data-i18n="[no-scripts-text]No scripts found" class="flex-container regex-script-container flexFlowColumn"></div>
</div>
<hr />
<div id="scoped_scripts_block" class="padding5">
<div id="scoped_scripts_block">
<div class="flex-container alignItemsBaseline">
<strong class="flex1" data-i18n="ext_regex_scoped_scripts">Scoped Scripts</strong>
<label id="toggle_scoped_regex" class="checkbox flex-container" for="regex_scoped_toggle">
@@ -93,6 +110,21 @@
</small>
<div id="saved_scoped_scripts" no-scripts-text="No scripts found" data-i18n="[no-scripts-text]No scripts found" class="flex-container regex-script-container flexFlowColumn"></div>
</div>
<hr />
<div id="preset_scripts_block">
<div class="flex-container alignItemsBaseline">
<strong class="flex1" data-i18n="ext_regex_preset_scripts">Preset Scripts</strong>
<label id="toggle_preset_regex" class="checkbox flex-container" for="regex_preset_toggle">
<input type="checkbox" id="regex_preset_toggle" class="enable_scoped" />
<span class="regex-toggle-on fa-solid fa-toggle-on fa-lg" data-i18n="[title]ext_regex_disallow_preset" title="Disallow using preset regex"></span>
<span class="regex-toggle-off fa-solid fa-toggle-off fa-lg" data-i18n="[title]ext_regex_allow_preset" title="Allow using preset regex"></span>
</label>
</div>
<small data-i18n="ext_regex_preset_scripts_desc">
Only available for this preset. Saved to the preset data.
</small>
<div id="saved_preset_scripts" class="flex-container regex-script-container flexFlowColumn"></div>
</div>
</div>
</div>
</div>
+228 -28
View File
@@ -1,16 +1,228 @@
import { characters, substituteParams, substituteParamsExtended, this_chid } from '../../../script.js';
import { extension_settings } from '../../extensions.js';
import { characters, saveSettingsDebounced, substituteParams, substituteParamsExtended, this_chid } from '../../../script.js';
import { extension_settings, writeExtensionField } from '../../extensions.js';
import { getPresetManager } from '../../preset-manager.js';
import { regexFromString } from '../../utils.js';
export {
regex_placement,
getRegexedString,
runRegexScript,
import { lodash } from '../../../lib.js';
/**
* @enum {number} Regex scripts types
* @readonly
*/
export const SCRIPT_TYPES = {
GLOBAL: 0,
SCOPED: 1,
PRESET: 2,
};
/**
* @enum {number} Where the regex script should be applied
* Special type for unknown/invalid script types.
*/
const regex_placement = {
export const SCRIPT_TYPE_UNKNOWN = -1;
/**
* @typedef {import('../../char-data.js').RegexScriptData} RegexScript
*/
/**
* @typedef {object} GetRegexScriptsOptions
* @property {boolean} allowedOnly Only return allowed scripts
*/
/**
* @type {Readonly<GetRegexScriptsOptions>}
*/
const DEFAULT_GET_REGEX_SCRIPTS_OPTIONS = Object.freeze({ allowedOnly: false });
/**
* Retrieves the list of regex scripts by combining the scripts from the extension settings and the character data
*
* @param {GetRegexScriptsOptions} options Options for retrieving the regex scripts
* @returns {RegexScript[]} An array of regex scripts, where each script is an object containing the necessary information.
*/
export function getRegexScripts(options = DEFAULT_GET_REGEX_SCRIPTS_OPTIONS) {
return [...Object.values(SCRIPT_TYPES).flatMap(type => getScriptsByType(type, options))];
}
/**
* Retrieves the regex scripts for a specific type.
* @param {SCRIPT_TYPES} scriptType The type of regex scripts to retrieve.
* @param {GetRegexScriptsOptions} options Options for retrieving the regex scripts
* @returns {RegexScript[]} An array of regex scripts for the specified type.
*/
export function getScriptsByType(scriptType, { allowedOnly } = DEFAULT_GET_REGEX_SCRIPTS_OPTIONS) {
switch (scriptType) {
case SCRIPT_TYPE_UNKNOWN:
return [];
case SCRIPT_TYPES.GLOBAL:
return extension_settings.regex ?? [];
case SCRIPT_TYPES.SCOPED: {
if (allowedOnly && !extension_settings?.character_allowed_regex?.includes(characters?.[this_chid]?.avatar)) {
return [];
}
const scopedScripts = characters[this_chid]?.data?.extensions?.regex_scripts;
return Array.isArray(scopedScripts) ? scopedScripts : [];
}
case SCRIPT_TYPES.PRESET: {
if (allowedOnly && !extension_settings?.preset_allowed_regex?.[getCurrentPresetAPI()]?.includes(getCurrentPresetName())) {
return [];
}
const presetManager = getPresetManager();
const presetScripts = presetManager?.readPresetExtensionField({ path: 'regex_scripts' });
return Array.isArray(presetScripts) ? presetScripts : [];
}
default:
console.warn(`getScriptsByType: Invalid script type ${scriptType}`);
return [];
}
}
/**
* Saves an array of regex scripts for a specific type.
* @param {RegexScript[]} scripts An array of regex scripts to save.
* @param {SCRIPT_TYPES} scriptType The type of regex scripts to save.
* @returns {Promise<void>}
*/
export async function saveScriptsByType(scripts, scriptType) {
switch (scriptType) {
case SCRIPT_TYPES.GLOBAL:
extension_settings.regex = scripts;
saveSettingsDebounced();
break;
case SCRIPT_TYPES.SCOPED:
await writeExtensionField(this_chid, 'regex_scripts', scripts);
break;
case SCRIPT_TYPES.PRESET: {
const presetManager = getPresetManager();
await presetManager.writePresetExtensionField({ path: 'regex_scripts', value: scripts });
break;
}
default:
console.warn(`saveScriptsByType: Invalid script type ${scriptType}`);
break;
}
}
/**
* Check if character's regexes are allowed to be used; if character is undefined, returns false
* @param {import('../../char-data.js').v1CharData|undefined} character
* @returns {boolean}
*/
export function isScopedScriptsAllowed(character) {
return !!extension_settings?.character_allowed_regex?.includes(character?.avatar);
}
/**
* Allow character's regexes to be used; if character is undefined, do nothing
* @param {import('../../char-data.js').v1CharData|undefined} character
* @returns {void}
*/
export function allowScopedScripts(character) {
const avatar = character?.avatar;
if (!avatar) {
return;
}
if (!Array.isArray(extension_settings?.character_allowed_regex)) {
extension_settings.character_allowed_regex = [];
}
if (!extension_settings.character_allowed_regex.includes(avatar)) {
extension_settings.character_allowed_regex.push(avatar);
saveSettingsDebounced();
}
}
/**
* Disallow character's regexes to be used; if character is undefined, do nothing
* @param {import('../../char-data.js').v1CharData|undefined} character
* @returns {void}
*/
export function disallowScopedScripts(character) {
const avatar = character?.avatar;
if (!avatar) {
return;
}
if (!Array.isArray(extension_settings?.character_allowed_regex)) {
return;
}
const index = extension_settings.character_allowed_regex.indexOf(avatar);
if (index !== -1) {
extension_settings.character_allowed_regex.splice(index, 1);
saveSettingsDebounced();
}
}
/**
* Check if preset's regexes are allowed to be used
* @param {string} apiId API ID
* @param {string} presetName Preset name
* @returns {boolean} True if allowed, false if not
*/
export function isPresetScriptsAllowed(apiId, presetName) {
if (!apiId || !presetName) {
return false;
}
return !!extension_settings?.preset_allowed_regex?.[apiId]?.includes(presetName);
}
/**
* Allow preset's regexes to be used
* @param {string} apiId API ID
* @param {string} presetName Preset name
* @returns {void}
*/
export function allowPresetScripts(apiId, presetName) {
if (!apiId || !presetName) {
return;
}
if (!Array.isArray(extension_settings?.preset_allowed_regex?.[apiId])) {
lodash.set(extension_settings, ['preset_allowed_regex', apiId], []);
}
if (!extension_settings.preset_allowed_regex[apiId].includes(presetName)) {
extension_settings.preset_allowed_regex[apiId].push(presetName);
saveSettingsDebounced();
}
}
/**
* Disallow preset's regexes to be used
* @param {string} apiId API ID
* @param {string} presetName Preset name
* @returns {void}
*/
export function disallowPresetScripts(apiId, presetName) {
if (!apiId || !presetName) {
return;
}
if (!Array.isArray(extension_settings?.preset_allowed_regex?.[apiId])) {
return;
}
const index = extension_settings.preset_allowed_regex[apiId].indexOf(presetName);
if (index !== -1) {
extension_settings.preset_allowed_regex[apiId].splice(index, 1);
saveSettingsDebounced();
}
}
/**
* Gets the current API ID from the preset manager.
* @returns {string|null} Current API ID, or null if no preset manager
*/
export function getCurrentPresetAPI() {
return getPresetManager()?.apiId ?? null;
}
/**
* Gets the name of the currently selected preset.
* @returns {string|null} The name of the currently selected preset, or null if no preset manager
*/
export function getCurrentPresetName() {
return getPresetManager()?.getSelectedPresetName() ?? null;
}
/**
* @enum {number} Where the regex script should be applied
* @readonly
*/
export const regex_placement = {
/**
* @deprecated MD Display is deprecated. Do not use.
*/
@@ -23,6 +235,10 @@ const regex_placement = {
REASONING: 6,
};
/**
* @enum {number} How to substitute parameters in the find regex
* @readonly
*/
export const substitute_find_regex = {
NONE: 0,
RAW: 1,
@@ -51,22 +267,6 @@ function sanitizeRegexMacro(x) {
}) : x;
}
function getScopedRegex() {
const isAllowed = extension_settings?.character_allowed_regex?.includes(characters?.[this_chid]?.avatar);
if (!isAllowed) {
return [];
}
const scripts = characters[this_chid]?.data?.extensions?.regex_scripts;
if (!Array.isArray(scripts)) {
return [];
}
return scripts;
}
/**
* Parent function to fetch a regexed version of a raw string
* @param {string} rawString The raw string to be regexed
@@ -75,7 +275,7 @@ function getScopedRegex() {
* @returns {string} The regexed string
* @typedef {{characterOverride?: string, isMarkdown?: boolean, isPrompt?: boolean, isEdit?: boolean, depth?: number }} RegexParams The parameters to use for the regex script
*/
function getRegexedString(rawString, placement, { characterOverride, isMarkdown, isPrompt, isEdit, depth } = {}) {
export function getRegexedString(rawString, placement, { characterOverride, isMarkdown, isPrompt, isEdit, depth } = {}) {
// WTF have you passed me?
if (typeof rawString !== 'string') {
console.warn('getRegexedString: rawString is not a string. Returning empty string.');
@@ -87,7 +287,7 @@ function getRegexedString(rawString, placement, { characterOverride, isMarkdown,
return finalString;
}
const allRegex = [...(extension_settings.regex ?? []), ...(getScopedRegex() ?? [])];
const allRegex = getRegexScripts({ allowedOnly: true });
allRegex.forEach((script) => {
if (
// Script applies to Markdown and input is Markdown
@@ -126,13 +326,13 @@ function getRegexedString(rawString, placement, { characterOverride, isMarkdown,
/**
* Runs the provided regex script on the given string
* @param {import('./index.js').RegexScript} regexScript The regex script to run
* @param {RegexScript} regexScript The regex script to run
* @param {string} rawString The string to run the regex script on
* @param {RegexScriptParams} params The parameters to use for the regex script
* @returns {string} The new string
* @typedef {{characterOverride?: string}} RegexScriptParams The parameters to use for the regex script
*/
function runRegexScript(regexScript, rawString, { characterOverride } = {}) {
export function runRegexScript(regexScript, rawString, { characterOverride } = {}) {
let newString = rawString;
if (!regexScript || !!(regexScript.disabled) || !regexScript?.findRegex || !rawString) {
return newString;
@@ -15,5 +15,11 @@
Scoped Scripts
</span>
</label>
<label for="regex_import_target_preset">
<input type="radio" name="regex_import_target" id="regex_import_target_preset" value="preset" />
<span data-i18n="ext_regex_preset_scripts">
Preset Scripts
</span>
</label>
</div>
</div>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,5 @@
<div>
<h3 data-i18n="This preset has embedded regex script(s).">This preset has embedded regex script(s).</h3>
<h3 data-i18n="Would you like to allow using them?">Would you like to allow using them?</h3>
<div class="m-b-1" data-i18n="If you want to do it later, select 'Regex' from the extensions menu.">If you want to do it later, select "Regex" from the extensions menu.</div>
</div>
@@ -1,25 +1,34 @@
<div class="regex-script-label flex-container flexnowrap">
<input type="checkbox" class="regex_bulk_checkbox" />
<span class="drag-handle menu-handle">&#9776;</span>
<div class="regex_script_name flexGrow overflow-hidden"></div>
<div class="regex_script_name flex1 overflow-hidden"></div>
<div class="flex-container flexnowrap">
<label class="checkbox flex-container" for="regex_disable">
<label class="checkbox flex-container margin-r5" for="regex_disable">
<input type="checkbox" name="regex_disable" class="disable_regex" />
<span class="regex-toggle-on fa-solid fa-toggle-on" data-i18n="[title]ext_regex_disable_script" title="Disable script"></span>
<span class="regex-toggle-off fa-solid fa-toggle-off" data-i18n="[title]ext_regex_enable_script" title="Enable script"></span>
</label>
<label class="menu_button regex_script_expand" title="Show more options" data-i18n="[title]Show more options">
<input type="checkbox" name="regex_expand" />
<span class="fa-solid fa-ellipsis"></span>
</label>
<div class="flex-container regex_script_buttons">
<div class="move_to_global menu_button" data-i18n="[title]ext_regex_move_to_global" title="Move to global scripts">
<i class="fa-solid fa-globe"></i>
</div>
<div class="move_to_scoped menu_button" data-i18n="[title]ext_regex_move_to_scoped" title="Move to scoped scripts">
<i class="fa-solid fa-address-card"></i>
</div>
<div class="move_to_preset menu_button" data-i18n="[title]ext_regex_move_to_preset" title="Move to preset scripts">
<i class="fa-solid fa-sliders"></i>
</div>
<div class="export_regex menu_button" data-i18n="[title]ext_regex_export_script" title="Export script">
<i class="fa-solid fa-file-export"></i>
</div>
</div>
<div class="edit_existing_regex menu_button" data-i18n="[title]ext_regex_edit_script" title="Edit script">
<i class="fa-solid fa-pencil"></i>
</div>
<div class="move_to_global menu_button" data-i18n="[title]ext_regex_move_to_global" title="Move to global scripts">
<i class="fa-solid fa-arrow-up"></i>
</div>
<div class="move_to_scoped menu_button" data-i18n="[title]ext_regex_move_to_scoped" title="Move to scoped scripts">
<i class="fa-solid fa-arrow-down"></i>
</div>
<div class="export_regex menu_button" data-i18n="[title]ext_regex_export_script" title="Export script">
<i class="fa-solid fa-file-export"></i>
</div>
<div class="delete_regex menu_button" data-i18n="[title]ext_regex_delete_script" title="Delete script">
<i class="fa-solid fa-trash"></i>
</div>
+38 -29
View File
@@ -24,39 +24,33 @@
text-align: center;
}
#scoped_scripts_block {
#scoped_scripts_block,
#preset_scripts_block {
opacity: 1;
transition: opacity var(--animation-duration-2x) ease-in-out;
}
#scoped_scripts_block .move_to_scoped {
#scoped_scripts_block .move_to_scoped,
#global_scripts_block .move_to_global,
#preset_scripts_block .move_to_preset {
display: none;
}
#global_scripts_block .move_to_global {
display: none;
}
#scoped_scripts_block:not(:has(#regex_scoped_toggle:checked)) {
#scoped_scripts_block:not(:has(#regex_scoped_toggle:checked)),
#preset_scripts_block:not(:has(#regex_preset_toggle:checked)) {
opacity: 0.5;
}
.enable_scoped:checked~.regex-toggle-on {
display: block;
}
.enable_scoped:checked~.regex-toggle-off {
display: none;
}
.enable_scoped:not(:checked)~.regex-toggle-on {
display: none;
}
.enable_scoped:checked~.regex-toggle-on,
.enable_scoped:not(:checked)~.regex-toggle-off {
display: block;
}
.enable_scoped:checked~.regex-toggle-off,
.enable_scoped:not(:checked)~.regex-toggle-on {
display: none;
}
.regex-script-label {
align-items: baseline;
border: 1px solid var(--SmartThemeBorderColor);
@@ -92,19 +86,13 @@ input.enable_scoped {
cursor: pointer;
}
.disable_regex:checked~.regex-toggle-off {
display: block;
}
.disable_regex:checked~.regex-toggle-on {
display: none;
}
.disable_regex:checked~.regex-toggle-on,
.disable_regex:not(:checked)~.regex-toggle-off {
display: none;
}
.disable_regex:not(:checked)~.regex-toggle-on {
.disable_regex:not(:checked)~.regex-toggle-on,
.disable_regex:checked~.regex-toggle-off {
display: block;
}
@@ -139,7 +127,8 @@ input.enable_scoped {
}
.regex_settings .regex_bulk_operations,
.regex_settings .regex_bulk_checkbox {
.regex_settings .regex_bulk_checkbox,
.regex_settings .regex_bulk_operations_hr {
display: none;
}
@@ -147,6 +136,26 @@ input.enable_scoped {
display: flex;
}
.regex_settings:has(#regex_bulk_edit:checked) .regex_bulk_operations_hr {
display: block;
}
.regex_settings:has(#regex_bulk_edit:checked) .regex_bulk_checkbox {
display: inline-grid;
}
@supports not selector(:has(*)) {
.regex-script-label label.regex_script_expand {
display: none;
}
.regex-script-label .regex_script_buttons {
display: flex;
}
}
.regex-script-label label.regex_script_expand input[name="regex_expand"],
.regex-script-label:has(input[name="regex_expand"]:checked) label.regex_script_expand,
.regex-script-label:not(:has(input[name="regex_expand"]:checked)) .regex_script_buttons {
display: none;
}
+1
View File
@@ -410,6 +410,7 @@ export class ConnectionManagerRequestService {
custom_url: profile['api-url'],
reverse_proxy: proxyPreset?.url,
proxy_password: proxyPreset?.password,
custom_prompt_post_processing: profile['prompt-post-processing'],
...overridePayload,
}, {
presetName: includePreset ? profile.preset : undefined,
@@ -1,6 +1,6 @@
<div id="sd_dropdown">
<ul class="list-group">
<span>Send me a picture of:</span>
<span data-i18n="Send me a picture of:">Send me a picture of:</span>
<li class="list-group-item" id="sd_you" data-value="you" data-i18n="sd_Yourself">Yourself</li>
<li class="list-group-item" id="sd_face" data-value="face" data-i18n="sd_Your_Face">Your Face</li>
<li class="list-group-item" id="sd_me" data-value="me" data-i18n="sd_Me">Me</li>
@@ -1705,7 +1705,7 @@ async function loadModels() {
models = await loadStabilityModels();
break;
case sources.huggingface:
models = [{ value: '', text: '<Enter Model ID above>' }];
models = [{ value: '', text: t`<Enter Model ID above>` }];
break;
case sources.electronhub:
models = await loadElectronHubModels();
@@ -90,15 +90,15 @@
<i><b data-i18n="Important:">Important:</b></i><i data-i18n="sd_drawthings_auth_txt"> run DrawThings app with HTTP API switch enabled in the UI! The server must be accessible from the SillyTavern host machine.</i>
</div>
<div data-sd-source="huggingface">
<i>Hint: Save an API key in the Hugging Face (Text Completion) API settings to use it here.</i>
<i data-i18n="Hint: Save an API key in the Hugging Face (Text Completion) API settings to use it here.">Hint: Save an API key in the Hugging Face (Text Completion) API settings to use it here.</i>
<label for="sd_huggingface_model_id" data-i18n="Model ID">Model ID</label>
<input id="sd_huggingface_model_id" type="text" class="text_pole" data-i18n="[placeholder]e.g. black-forest-labs/FLUX.1-dev" placeholder="e.g. black-forest-labs/FLUX.1-dev" value="" />
</div>
<div data-sd-source="electronhub">
<i>Hint: Save an API key in the Electron Hub (Chat Completion) API settings to use it here.</i>
<i data-i18n="Hint: Save an API key in the Electron Hub (Chat Completion) API settings to use it here.">Hint: Save an API key in the Electron Hub (Chat Completion) API settings to use it here.</i>
</div>
<div data-sd-source="nanogpt">
<i>Hint: Save an API key in the NanoGPT (Chat Completion) API settings to use it here.</i>
<i data-i18n="Hint: Save an API key in the NanoGPT (Chat Completion) API settings to use it here.">Hint: Save an API key in the NanoGPT (Chat Completion) API settings to use it here.</i>
</div>
<div data-sd-source="vlad">
<label for="sd_vlad_url">SD.Next API URL</label>
@@ -143,7 +143,7 @@
View my Anlas
</div>
</div>
<i>Hint: Save an API key in the NovelAI API settings to use it here.</i>
<i data-i18n="Hint: Save an API key in the NovelAI API settings to use it here.">Hint: Save an API key in the NovelAI API settings to use it here.</i>
</div>
<div data-sd-source="aimlapi">
<div class="flex-container flexnowrap alignItemsBaseline marginBot5">
@@ -204,7 +204,7 @@
<a href="https://pollinations.ai">Pollinations.ai</a>
</p>
<div class="flex-container">
<label class="flex1 checkbox_label" for="sd_pollinations_enhance" title="Enables prompt enhancing (passes prompts through an LLM to add detail).">
<label class="flex1 checkbox_label" for="sd_pollinations_enhance" data-i18n="[title]Enables prompt enhancing (passes prompts through an LLM to add detail)." title="Enables prompt enhancing (passes prompts through an LLM to add detail).">
<input id="sd_pollinations_enhance" type="checkbox" />
<span data-i18n="Enhance">
Enhance
@@ -297,7 +297,7 @@
</div>
</div>
<div class="flex-container">
<label class="flex1 checkbox_label" for="sd_google_enhance" title="Enables prompt enhancing (passes prompts through an LLM to add detail).">
<label class="flex1 checkbox_label" for="sd_google_enhance" data-i18n="[title]Enables prompt enhancing (passes prompts through an LLM to add detail)." title="Enables prompt enhancing (passes prompts through an LLM to add detail).">
<input id="sd_google_enhance" type="checkbox" />
<span data-i18n="Enhance">
Enhance
@@ -1,3 +1,8 @@
.minimax_tts_settings>.tts_block {
gap: 5px;
margin: 5px 0;
}
.minimax-custom-item {
display: flex;
justify-content: space-between;
@@ -0,0 +1,455 @@
import { event_types, eventSource, getRequestHeaders } from '../../../script.js';
import { SECRET_KEYS, secret_state } from '../../secrets.js';
import { getPreviewString, saveTtsProviderSettings, initVoiceMap } from './index.js';
export { ElectronHubTtsProvider };
class ElectronHubTtsProvider {
settings;
voices = [];
models = [];
separator = ' . ';
audioElement = document.createElement('audio');
defaultSettings = {
voiceMap: {},
model: 'tts-1',
speed: 1,
temperature: 1,
top_p: 1,
// GPT-4o Mini TTS
instructions: '',
// Dia
speaker_transcript: '',
cfg_filter_top_k: 25,
cfg_scale: 3,
// Microsoft TTS
speech_rate: 0,
pitch_adjustment: 0,
emotional_style: '',
};
get settingsHtml() {
let html = `
<div>Electron Hub unified TTS API.</div>
<div class="flex-container alignItemsCenter">
<div class="flex1"></div>
<div id="electronhub_tts_key" class="menu_button menu_button_icon manage-api-keys" data-key="api_key_electronhub">
<i class="fa-solid fa-key"></i>
<span>API Key</span>
</div>
</div>
<div class="flex-container flexGap10 wrap">
<div class="flex1">
<label for="electronhub_tts_model">Model</label>
<select id="electronhub_tts_model" class="text_pole"></select>
</div>
<div>
<label for="electronhub_tts_speed">Speed <span id="electronhub_tts_speed_output"></span></label>
<input type="range" id="electronhub_tts_speed" value="1" min="0.25" max="4" step="0.05">
</div>
<div>
<label for="electronhub_tts_temperature">Temperature</label>
<input id="electronhub_tts_temperature" class="text_pole" type="number" min="0" max="2" step="0.1" value="1" />
</div>
<div id="electronhub_block_top_p" style="display:none;">
<label for="electronhub_tts_top_p">Top-p</label>
<input id="electronhub_tts_top_p" class="text_pole" type="number" min="0" max="1" step="0.01" value="1" />
</div>
</div>
<div id="electronhub_block_instructions" style="display:none;">
<label for="electronhub_tts_instructions">Instructions (GPT-4o Mini TTS):</label>
<textarea id="electronhub_tts_instructions" class="textarea_compact autoSetHeight" placeholder="e.g., 'Speak cheerfully and energetically'"></textarea>
</div>
<div id="electronhub_block_dia" style="display:none;">
<label for="electronhub_tts_speaker_transcript">Speaker transcript (Dia):</label>
<textarea id="electronhub_tts_speaker_transcript" class="textarea_compact autoSetHeight" maxlength="1000"></textarea>
<label for="electronhub_tts_cfg_scale">CFG scale (1-5):</label>
<input id="electronhub_tts_cfg_scale" type="number" min="1" max="5" step="1" />
<label for="electronhub_tts_cfg_topk">CFG filter top_k (15-50):</label>
<input id="electronhub_tts_cfg_topk" type="number" min="15" max="50" step="1" />
</div>
<div id="electronhub_block_msft" style="display:none;">
<div class="flex-container flexGap10 wrap">
<div>
<label for="electronhub_tts_speech_rate">Speech rate (-100..100)</label>
<input id="electronhub_tts_speech_rate" class="text_pole" type="number" min="-100" max="100" step="1" style="width:120px;" />
</div>
<div>
<label for="electronhub_tts_pitch_adjustment">Pitch adjustment (-100..100)</label>
<input id="electronhub_tts_pitch_adjustment" class="text_pole" type="number" min="-100" max="100" step="1" style="width:120px;" />
</div>
</div>
<div class="flex-container flexGap10">
<div class="flex1">
<label for="electronhub_tts_emotional_style">Emotional style</label>
<input id="electronhub_tts_emotional_style" class="text_pole" type="text" placeholder="cheerful, sad, angry, gentle..." />
</div>
</div>
</div>
<div id="electronhub_dynamic_params" class="flex-container flexGap10 wrap" style="display:none;"></div>`;
return html;
}
constructor() {
this.handler = async function (/** @type {string} */ key) {
if (key !== SECRET_KEYS.ELECTRONHUB) return;
$('#electronhub_tts_key').toggleClass('success', !!secret_state[SECRET_KEYS.ELECTRONHUB]);
await this.onRefreshClick();
}.bind(this);
}
dispose() {
[event_types.SECRET_WRITTEN, event_types.SECRET_DELETED, event_types.SECRET_ROTATED].forEach(event => {
eventSource.removeListener(event, this.handler);
});
}
async loadSettings(settings) {
if (Object.keys(settings).length == 0) {
console.info('Using default Electron Hub TTS settings');
}
this.settings = { ...this.defaultSettings, ...settings };
await this.loadModels();
this.populateModelSelect();
$('#electronhub_tts_model').val(this.settings.model);
$('#electronhub_tts_model').on('change', () => { this.onSettingsChange(); });
$('#electronhub_tts_speed').val(this.settings.speed);
$('#electronhub_tts_speed_output').text(this.settings.speed);
$('#electronhub_tts_speed').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_temperature').val(this.settings.temperature);
$('#electronhub_tts_temperature').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_top_p').val(this.settings.top_p);
$('#electronhub_tts_top_p').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_instructions').val(this.settings.instructions);
$('#electronhub_tts_instructions').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_speaker_transcript').val(this.settings.speaker_transcript);
$('#electronhub_tts_speaker_transcript').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_cfg_scale').val(this.settings.cfg_scale);
$('#electronhub_tts_cfg_scale').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_cfg_topk').val(this.settings.cfg_filter_top_k);
$('#electronhub_tts_cfg_topk').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_speech_rate').val(this.settings.speech_rate);
$('#electronhub_tts_speech_rate').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_pitch_adjustment').val(this.settings.pitch_adjustment);
$('#electronhub_tts_pitch_adjustment').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_emotional_style').val(this.settings.emotional_style);
$('#electronhub_tts_emotional_style').on('input', () => { this.onSettingsChange(); });
$('#electronhub_tts_key').toggleClass('success', !!secret_state[SECRET_KEYS.ELECTRONHUB]);
[event_types.SECRET_WRITTEN, event_types.SECRET_DELETED, event_types.SECRET_ROTATED].forEach(event => {
eventSource.on(event, this.handler);
});
await this.checkReady();
this.updateConditionalBlocks();
this.renderDynamicParams();
console.debug('Electron Hub TTS: Settings loaded');
}
async onSettingsChange() {
const previousModel = this.settings.model;
this.settings.model = String($('#electronhub_tts_model').find(':selected').val() || this.settings.model);
this.settings.speed = Number($('#electronhub_tts_speed').val());
$('#electronhub_tts_speed_output').text(this.settings.speed);
this.settings.temperature = Number($('#electronhub_tts_temperature').val());
this.settings.top_p = Number($('#electronhub_tts_top_p').val());
this.settings.instructions = String($('#electronhub_tts_instructions').val() || '');
this.settings.speaker_transcript = String($('#electronhub_tts_speaker_transcript').val() || '');
this.settings.cfg_scale = Number($('#electronhub_tts_cfg_scale').val());
this.settings.cfg_filter_top_k = Number($('#electronhub_tts_cfg_topk').val());
this.settings.speech_rate = Number($('#electronhub_tts_speech_rate').val());
this.settings.pitch_adjustment = Number($('#electronhub_tts_pitch_adjustment').val());
this.settings.emotional_style = String($('#electronhub_tts_emotional_style').val() || '');
this.updateConditionalBlocks();
this.renderDynamicParams();
saveTtsProviderSettings();
if (previousModel !== this.settings.model) {
this.voices = await this.fetchTtsVoiceObjects();
await initVoiceMap();
}
}
async loadModels() {
try {
const response = await fetch('/api/openai/electronhub/models', {
method: 'POST',
headers: getRequestHeaders(),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
/** @type {Array<any>} */
const data = await response.json();
const allModels = Array.isArray(data) ? data : [];
const ttsModels = allModels.filter(m => {
const eps = Array.isArray(m?.endpoints) ? m.endpoints : [];
return eps.some(ep => {
if (typeof ep !== 'string') return false;
return ep === '/v1/audio/speech' || ep.endsWith('/audio/speech') || ep === 'audio/speech';
});
});
this.models = ttsModels;
if (this.models.length > 0 && !this.models.find(m => m.id === this.settings.model)) {
this.settings.model = this.models[0].id;
saveTtsProviderSettings();
}
} catch (err) {
console.warn('Electron Hub models fetch failed', err);
this.models = [];
}
}
populateModelSelect() {
const select = $('#electronhub_tts_model');
select.empty();
const groups = this.groupByVendor(this.models);
for (const [vendor, models] of groups.entries()) {
const optgroup = document.createElement('optgroup');
optgroup.label = vendor;
for (const m of models) {
const opt = document.createElement('option');
opt.value = m.id;
opt.text = m.name || m.id;
optgroup.appendChild(opt);
}
select.append(optgroup);
}
if (this.models.find(x => x.id === this.settings.model)) {
select.val(this.settings.model);
}
}
/**
* Group models by vendor prefix from name before ':'
* @param {Array<any>} array
* @returns {Map<string, any[]>}
*/
groupByVendor(array) {
return array.reduce((acc, curr) => {
const name = String(curr?.name || curr?.id || 'Other');
const vendor = name.split(':')[0].trim() || 'Other';
if (!acc.has(vendor)) acc.set(vendor, []);
acc.get(vendor).push(curr);
return acc;
}, new Map());
}
updateConditionalBlocks() {
const modelId = this.settings.model;
const model = this.models.find(m => m.id === modelId);
const params = model?.parameters || {};
const vendorName = String(model?.name || '').split(':')[0].trim().toLowerCase();
const hasInstructions = 'instructions' in params || modelId === 'gpt-4o-mini-tts';
const hasDia = 'speaker_transcript' in params || 'cfg_scale' in params || 'cfg_filter_top_k' in params || modelId.includes('dia');
const hasMsft = 'speech_rate' in params || 'pitch_adjustment' in params || 'emotional_style' in params || vendorName === 'microsoft' || modelId === 'microsoft-tts';
const hasTopP = 'top_p' in params;
$('#electronhub_block_instructions').toggle(!!hasInstructions);
$('#electronhub_block_dia').toggle(!!hasDia);
$('#electronhub_block_msft').toggle(!!hasMsft);
$('#electronhub_block_top_p').toggle(!!hasTopP);
}
/**
* Build UI for additional model parameters dynamically
*/
renderDynamicParams() {
const container = $('#electronhub_dynamic_params');
container.empty();
const model = this.models.find(m => m.id === this.settings.model);
const params = model?.parameters || {};
const modelHasVoices = Array.isArray(model?.voices) && model.voices.length > 0;
const exclude = new Set(['input', 'response_format', 'model', 'speed', 'temperature', 'top_p', 'instructions', 'speaker_transcript', 'cfg_scale', 'cfg_filter_top_k', 'speech_rate', 'pitch_adjustment', 'emotional_style']);
if (modelHasVoices) exclude.add('voice');
const entries = Object.entries(params).filter(([k]) => !exclude.has(k));
container.toggle(entries.length > 0);
if (entries.length === 0) return;
for (const [key, spec] of entries) {
const nice = key.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
const type = String(spec?.type || 'string');
const id = `electronhub_dyn_${key.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
if (Array.isArray(spec?.enum) && spec.enum.length) {
const select = $(`<div><label for="${id}">${nice}</label><select id="${id}" class="text_pole"></select></div>`);
container.append(select);
const el = select.find('select');
for (const opt of spec.enum) el.append(new Option(String(opt), String(opt)));
const val = this.settings[key] ?? spec.default ?? spec.enum[0];
el.val(String(val));
el.on('change', () => { this.settings[key] = String(el.val() || ''); saveTtsProviderSettings(); });
continue;
}
if (type === 'boolean') {
const block = $(`<label class="checkbox_label" for="${id}"><input type="checkbox" id="${id}"> <small>${nice}</small></label>`);
container.append(block);
const el = block.find('input');
el.prop('checked', !!(this.settings[key] ?? spec.default ?? false));
el.on('change', () => { this.settings[key] = !!el.is(':checked'); saveTtsProviderSettings(); });
continue;
}
if (type === 'number' || type === 'integer') {
const min = spec.minimum ?? undefined;
const max = spec.maximum ?? undefined;
const step = type === 'integer' ? 1 : (spec.step ?? 0.01);
const block = $(`<div><label for="${id}">${nice}${(min != null || max != null) ? ` (${min ?? ''}..${max ?? ''})` : ''}:</label><input id="${id}" type="number" class="text_pole" ${min != null ? `min="${min}"` : ''} ${max != null ? `max="${max}"` : ''} step="${step}"></div>`);
container.append(block);
const el = block.find('input');
const val = this.settings[key] ?? spec.default ?? '';
if (val !== '') el.val(val);
el.on('input', () => {
const raw = el.val();
this.settings[key] = (raw === '') ? '' : Number(raw);
saveTtsProviderSettings();
});
continue;
}
const isLong = /instructions|transcript|style|prompt|description/i.test(key);
if (isLong) {
const block = $(`<div><label for="${id}">${nice}</label><textarea id="${id}" class="textarea_compact autoSetHeight"></textarea></div>`);
container.append(block);
const el = block.find('textarea');
el.val(String(this.settings[key] ?? spec.default ?? ''));
el.on('input', () => { this.settings[key] = String(el.val() || ''); saveTtsProviderSettings(); });
} else {
const block = $(`<div><label for="${id}">${nice}</label><input id="${id}" type="text" class="text_pole" /></div>`);
container.append(block);
const el = block.find('input');
el.val(String(this.settings[key] ?? spec.default ?? ''));
el.on('input', () => { this.settings[key] = String(el.val() || ''); saveTtsProviderSettings(); });
}
}
}
async checkReady() {
this.voices = await this.fetchTtsVoiceObjects();
}
async onRefreshClick() {
await this.loadModels();
this.populateModelSelect();
this.voices = await this.fetchTtsVoiceObjects();
this.updateConditionalBlocks();
this.renderDynamicParams();
saveTtsProviderSettings();
}
async getVoice(voiceName) {
if (this.voices.length == 0) {
this.voices = await this.fetchTtsVoiceObjects();
}
const match = this.voices.filter(v => v.name == voiceName)[0];
if (!match) {
throw `TTS Voice name ${voiceName} not found`;
}
return match;
}
async generateTts(text, voiceId) {
const response = await this.fetchTtsGeneration(text, voiceId);
return response;
}
async fetchTtsVoiceObjects() {
const modelId = this.settings.model;
const model = this.models.find(m => m.id === modelId);
if (model && Array.isArray(model.voices) && model.voices.length) {
return model.voices.map(name => ({ name, voice_id: name, lang: 'en-US' }));
}
// Fallback to common OpenAI voices
const fallback = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'onyx', 'nova', 'sage', 'shimmer', 'verse'];
return fallback.map(name => ({ name, voice_id: name, lang: 'en-US' }));
}
async previewTtsVoice(voiceId) {
this.audioElement.pause();
this.audioElement.currentTime = 0;
const text = getPreviewString('en-US');
const response = await this.fetchTtsGeneration(text, voiceId);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const audio = await response.blob();
const url = URL.createObjectURL(audio);
this.audioElement.src = url;
this.audioElement.play();
this.audioElement.onended = () => URL.revokeObjectURL(url);
}
async fetchTtsGeneration(inputText, voiceId) {
console.info(`Generating Electron Hub TTS for voice_id ${voiceId}`);
const body = {
input: inputText,
voice: voiceId,
speed: this.settings.speed,
temperature: this.settings.temperature,
model: this.settings.model,
};
const model = (this.settings.model || '').toLowerCase();
if (model === 'gpt-4o-mini-tts') {
if (this.settings.instructions?.trim()) body.instructions = this.settings.instructions.trim();
}
if (model.includes('dia')) {
if (this.settings.speaker_transcript?.trim()) body.speaker_transcript = this.settings.speaker_transcript.trim();
if (Number.isFinite(this.settings.cfg_scale)) body.cfg_scale = Number(this.settings.cfg_scale);
if (Number.isFinite(this.settings.cfg_filter_top_k)) body.cfg_filter_top_k = Number(this.settings.cfg_filter_top_k);
}
if (model.includes('microsoft-tts')) {
if (Number.isFinite(this.settings.speech_rate)) body.speech_rate = Number(this.settings.speech_rate);
if (Number.isFinite(this.settings.pitch_adjustment)) body.pitch_adjustment = Number(this.settings.pitch_adjustment);
if ((this.settings.emotional_style || '').trim()) body.emotional_style = String(this.settings.emotional_style).trim();
}
if (Number.isFinite(this.settings.top_p)) {
body.top_p = Number(this.settings.top_p);
}
// add dynamic params based on schema
const modelObj = this.models.find(m => m.id === this.settings.model);
const params = modelObj?.parameters || {};
const modelHasVoices = Array.isArray(modelObj?.voices) && modelObj.voices.length > 0;
const exclude = new Set(['input', 'response_format', 'model', 'speed', 'temperature', 'top_p', 'instructions', 'speaker_transcript', 'cfg_scale', 'cfg_filter_top_k', 'speech_rate', 'pitch_adjustment', 'emotional_style']);
if (modelHasVoices) exclude.add('voice');
for (const key of Object.keys(params)) {
if (exclude.has(key)) continue;
const val = this.settings[key];
if (val === undefined || val === '') continue;
body[key] = val;
}
const response = await fetch('/api/openai/electronhub/generate-voice', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
return response;
}
}
@@ -92,10 +92,9 @@ class GptSovitsV2Provider {
}
// Set initial values from the settings
$('#tts_endpoint').val(this.settings.provider_endpoint);
$('#text_lang').val(this.settings.text_lang);
$('#prompt_lang').val(this.settings.prompt_lang);
$('#tts_endpoint').val(this.settings.provider_endpoint).on('change', this.onSettingsChange.bind(this));
$('#text_lang').val(this.settings.text_lang).on('change', this.onSettingsChange.bind(this));
$('#prompt_lang').val(this.settings.prompt_lang).on('change', this.onSettingsChange.bind(this));
await this.checkReady();
@@ -108,7 +107,7 @@ class GptSovitsV2Provider {
}
async onRefreshClick() {
return;
return await this.checkReady();
}
//#################//
+2
View File
@@ -33,6 +33,7 @@ import { KokoroTtsProvider } from './kokoro.js';
import { TtsWebuiProvider } from './tts-webui.js';
import { PollinationsTtsProvider } from './pollinations.js';
import { MiniMaxTtsProvider } from './minimax.js';
import { ElectronHubTtsProvider } from './electronhub.js';
const UPDATE_INTERVAL = 1000;
const wrapper = new ModuleWorkerWrapper(moduleWorker);
@@ -123,6 +124,7 @@ const ttsProviders = {
'CosyVoice (Unofficial)': CosyVoiceProvider,
Edge: EdgeTtsProvider,
ElevenLabs: ElevenLabsTtsProvider,
'Electron Hub': ElectronHubTtsProvider,
'Google Translate': GoogleTranslateTtsProvider,
'Google Gemini TTS': GoogleNativeTtsProvider,
GSVI: GSVITtsProvider,
+44 -16
View File
@@ -19,9 +19,9 @@ class MiniMaxTtsProvider {
apiHost: 'https://api.minimax.io',
model: 'speech-02-hd',
voiceMap: {},
speed: 1.0,
volume: 1.0,
pitch: 1.0,
speed: { default: 1.0, min: 0.5, max: 2.0, step: 0.1 },
volume: { default: 1.0, min: 0.0, max: 10.0, step: 0.1 },
pitch: { default: 0, min: -12, max: 12, step: 1 },
audioSampleRate: 32000,
bitrate: 128000,
format: 'mp3',
@@ -84,15 +84,15 @@ class MiniMaxTtsProvider {
<div class="tts_block">
<label for="minimax_tts_speed">Speed: <span id="minimax_tts_speed_output"></span></label>
<input id="minimax_tts_speed" type="range" value="${this.defaultSettings.speed}" min="0.5" max="2.0" step="0.1" />
<input id="minimax_tts_speed" type="range" value="${this.defaultSettings.speed.default}" min="${this.defaultSettings.speed.min}" max="${this.defaultSettings.speed.max}" step="${this.defaultSettings.speed.step}" />
</div>
<div class="tts_block">
<label for="minimax_tts_volume">Volume: <span id="minimax_tts_volume_output"></span></label>
<input id="minimax_tts_volume" type="range" value="${this.defaultSettings.volume}" min="0.1" max="2.0" step="0.1" />
<input id="minimax_tts_volume" type="range" value="${this.defaultSettings.volume.default}" min="${this.defaultSettings.volume.min}" max="${this.defaultSettings.volume.max}" step="${this.defaultSettings.volume.step}" />
</div>
<div class="tts_block">
<label for="minimax_tts_pitch">Pitch: <span id="minimax_tts_pitch_output"></span></label>
<input id="minimax_tts_pitch" type="range" value="${this.defaultSettings.pitch}" min="0.5" max="2.0" step="0.1" />
<input id="minimax_tts_pitch" type="range" value="${this.defaultSettings.pitch.default}" min="${this.defaultSettings.pitch.min}" max="${this.defaultSettings.pitch.max}" step="${this.defaultSettings.pitch.step}" />
</div>
<div class="tts_block">
<label for="minimax_tts_format">Audio Format</label>
@@ -190,14 +190,14 @@ class MiniMaxTtsProvider {
this.settings.apiHost = $('#minimax_tts_api_host').val();
this.settings.speed = parseFloat($('#minimax_tts_speed').val().toString());
this.settings.volume = parseFloat($('#minimax_tts_volume').val().toString());
this.settings.pitch = parseFloat($('#minimax_tts_pitch').val().toString());
this.settings.pitch = parseInt($('#minimax_tts_pitch').val().toString());
this.settings.model = $('#minimax_tts_model').find(':selected').val();
this.settings.format = $('#minimax_tts_format').find(':selected').val();
this.settings.customVoiceId = $('#minimax_tts_custom_voice_id').val();
$('#minimax_tts_speed_output').text(this.settings.speed.toFixed(1));
$('#minimax_tts_volume_output').text(this.settings.volume.toFixed(1));
$('#minimax_tts_pitch_output').text(this.settings.pitch.toFixed(1));
$('#minimax_tts_pitch_output').text(this.settings.pitch);
saveTtsProviderSettings();
}
@@ -458,6 +458,16 @@ class MiniMaxTtsProvider {
// Only accept keys defined in defaultSettings
this.settings = { ...this.defaultSettings };
// Flatten the settings fields with default/min/max definitions so the actual values are used
this.settings = Object.fromEntries(
Object.entries(this.defaultSettings).map(([key, value]) => {
if (value && typeof value === 'object' && 'default' in value) {
return [key, value.default];
}
return [key, value];
}),
);
for (const key in settings) {
if (key in this.settings) {
this.settings[key] = settings[key];
@@ -470,6 +480,21 @@ class MiniMaxTtsProvider {
if (!this.settings.customModels) this.settings.customModels = [];
if (!this.settings.customVoices) this.settings.customVoices = [];
// # Migrate settings
// Pitch value changed from float to int. If it's a float, let's try to extrapolate it to the new range
if (!Number.isInteger(this.settings.pitch)) {
const oldPitch = parseFloat(this.settings.pitch);
if (!isNaN(oldPitch)) {
// map old [0.5..1.0] to [-12..0], and [1.0..2.0] to [0..12] (old default was 1.0, new default is 0)
const newPitch = (oldPitch < 1.0) ? (oldPitch - 1.0) * 24 : (oldPitch - 1.0) * 12;
this.settings.pitch = Math.max(-12, Math.min(12, Math.round(newPitch)));
console.info(`MiniMax TTS: Migrated pitch from ${oldPitch} to ${this.settings.pitch}`);
} else {
this.settings.pitch = 0;
console.info(`MiniMax TTS: Migration reset pitch to default ${this.settings.pitch}`);
}
}
$('#minimax_tts_api_host').val(this.settings.apiHost || 'https://api.minimax.io');
$('#minimax_tts_model').val(this.settings.model);
$('#minimax_tts_speed').val(this.settings.speed);
@@ -546,7 +571,7 @@ class MiniMaxTtsProvider {
$('#minimax_tts_speed_output').text(this.settings.speed.toFixed(1));
$('#minimax_tts_volume_output').text(this.settings.volume.toFixed(1));
$('#minimax_tts_pitch_output').text(this.settings.pitch.toFixed(1));
$('#minimax_tts_pitch_output').text(this.settings.pitch);
// Initialize custom configuration display
this.updateCustomModelsDisplay();
@@ -756,17 +781,20 @@ class MiniMaxTtsProvider {
throw error;
}
/** @param {number} number @param {number} lower @param {number} upper @returns {number} */
const clamp = (number, lower, upper) => Math.min(Math.max(number, lower), upper);
const requestBody = {
text: inputText,
voiceId: voiceId,
apiHost: this.settings.apiHost,
model: this.settings.model || 'speech-02-hd',
speed: Number(this.settings.speed) || 1.0,
volume: Number(this.settings.volume) || 1.0,
pitch: Number(this.settings.pitch) || 1.0,
audioSampleRate: Number(this.settings.audioSampleRate) || 32000,
bitrate: Number(this.settings.bitrate) || 128000,
format: this.settings.format || 'mp3',
model: this.settings.model || this.defaultSettings.model,
speed: clamp(Number(this.settings.speed) || this.defaultSettings.speed.default, this.defaultSettings.speed.min, this.defaultSettings.speed.max),
volume: clamp(Number(this.settings.volume) || this.defaultSettings.volume.default, this.defaultSettings.volume.min, this.defaultSettings.volume.max),
pitch: clamp(Math.round(Number(this.settings.pitch)) || this.defaultSettings.pitch.default, this.defaultSettings.pitch.min, this.defaultSettings.pitch.max),
audioSampleRate: Number(this.settings.audioSampleRate) || this.defaultSettings.audioSampleRate,
bitrate: Number(this.settings.bitrate) || this.defaultSettings.bitrate,
format: this.settings.format || this.defaultSettings.format,
language: language,
};
+2 -2
View File
@@ -12,7 +12,7 @@
<div class="tts_block">
<select id="tts_provider" class="flex1">
</select>
<input id="tts_refresh" class="menu_button" type="submit" value="Reload" />
<input id="tts_refresh" data-i18n="[value]tts_refresh" class="menu_button" type="submit" value="Reload" />
</div>
<div>
<label class="checkbox_label" for="tts_enabled">
@@ -88,7 +88,7 @@
<form id="tts_provider_settings">
</form>
<div class="tts_buttons">
<input id="tts_voices" class="menu_button" type="submit" value="Available voices" />
<input id="tts_voices" class="menu_button" data-i18n="[value]Available voices" type="submit" value="Available voices" />
</div>
</div>
</div>
+5 -4
View File
@@ -2,6 +2,7 @@ import { isMobile } from '../../RossAscends-mods.js';
import { getPreviewString } from './index.js';
import { saveTtsProviderSettings } from './index.js';
export { SystemTtsProvider };
import { t } from '../../i18n.js';
/**
* Chunkify
@@ -96,13 +97,13 @@ class SystemTtsProvider {
get settingsHtml() {
if (!('speechSynthesis' in window)) {
return 'Your browser or operating system doesn\'t support speech synthesis';
return t`Your browser or operating system doesn't support speech synthesis`;
}
return `<p>Uses the voices provided by your operating system</p>
<label for="system_tts_rate">Rate: <span id="system_tts_rate_output"></span></label>
return '<p>' + t`Uses the voices provided by your operating system` + `</p>
<label for="system_tts_rate">` + t`Rate:` + ` <span id="system_tts_rate_output"></span></label>
<input id="system_tts_rate" type="range" value="${this.defaultSettings.rate}" min="0.1" max="2" step="0.01" />
<label for="system_tts_pitch">Pitch: <span id="system_tts_pitch_output"></span></label>
<label for="system_tts_pitch">` + t`Pitch:` + ` <span id="system_tts_pitch_output"></span></label>
<input id="system_tts_pitch" type="range" value="${this.defaultSettings.pitch}" min="0" max="2" step="0.01" />`;
}
+1 -1
View File
@@ -66,7 +66,7 @@ const settings = {
ollama_keep: false,
vllm_model: '',
webllm_model: '',
google_model: 'text-embedding-004',
google_model: 'text-embedding-005',
summarize: false,
summarize_sent: false,
summary_source: 'main',
@@ -140,6 +140,7 @@
<option value="gemini-embedding-001">gemini-embedding-001</option>
<option value="gemini-embedding-exp-03-07">gemini-embedding-exp-03-07</option>
<option value="text-embedding-004">text-embedding-004</option>
<option value="text-embedding-005">text-embedding-005</option>
<option value="embedding-001">embedding-001</option>
</select>
</div>
+57 -40
View File
@@ -76,6 +76,7 @@ import {
depth_prompt_role_default,
shouldAutoContinue,
unshallowCharacter,
chatElement,
} from '../script.js';
import { printTagList, createTagMapFromList, applyTagsOnCharacterSelect, tag_map, applyTagsOnGroupSelect } from './tags.js';
import { FILTER_TYPES, FilterHelper } from './filters.js';
@@ -236,37 +237,37 @@ export async function getGroupChat(groupId, reload = false) {
const chat_id = group.chat_id;
const data = await loadGroupChat(chat_id);
const metadata = group.chat_metadata ?? {};
let freshChat = false;
const freshChat = !metadata.tainted;
await loadItemizedPrompts(getCurrentChatId());
if (Array.isArray(data) && data.length) {
if (group && Array.isArray(group.members) && freshChat) {
chat.splice(0, chat.length);
chatElement.find('.mes').remove();
for (let member of group.members) {
const character = characters.find(x => x.avatar === member || x.name === member);
if (!character) {
continue;
}
const mes = await getFirstCharacterMessage(character);
// No first message
if (!(mes?.mes)) {
continue;
}
chat.push(mes);
await eventSource.emit(event_types.MESSAGE_RECEIVED, (chat.length - 1), 'first_message');
addOneMessage(mes);
await eventSource.emit(event_types.CHARACTER_MESSAGE_RENDERED, (chat.length - 1), 'first_message');
}
await saveGroupChat(groupId, false);
} else if (Array.isArray(data) && data.length) {
data[0].is_group = true;
chat.splice(0, chat.length, ...data);
chatElement.find('.mes').remove();
await printMessages();
} else {
freshChat = !metadata.tainted;
if (group && Array.isArray(group.members) && freshChat) {
for (let member of group.members) {
const character = characters.find(x => x.avatar === member || x.name === member);
if (!character) {
continue;
}
const mes = await getFirstCharacterMessage(character);
// No first message
if (!(mes?.mes)) {
continue;
}
chat.push(mes);
await eventSource.emit(event_types.MESSAGE_RECEIVED, (chat.length - 1), 'first_message');
addOneMessage(mes);
await eventSource.emit(event_types.CHARACTER_MESSAGE_RENDERED, (chat.length - 1), 'first_message');
}
await saveGroupChat(groupId, false);
}
}
updateChatMetadata(metadata, true);
@@ -2018,7 +2019,14 @@ export async function deleteGroupChatByName(groupId, chatName) {
await eventSource.emit(event_types.GROUP_CHAT_DELETED, chatName);
}
export async function deleteGroupChat(groupId, chatId) {
/**
* Deletes a group chat by name.
* @param {string} groupId The ID of the group containing the chat to delete.
* @param {string} chatId The id/name of the chat to delete.
* @param {object} [options={}] Options for the deletion.
* @param {boolean} [options.jumpToNewChat=true] Whether to jump to a new chat after deletion (existing one, or create a new one if none exists)
*/
export async function deleteGroupChat(groupId, chatId, { jumpToNewChat = true } = {}) {
const group = groups.find(x => x.id === groupId);
if (!group || !group.chats.includes(chatId)) {
@@ -2026,10 +2034,13 @@ export async function deleteGroupChat(groupId, chatId) {
}
group.chats.splice(group.chats.indexOf(chatId), 1);
group.chat_metadata = {};
group.chat_id = '';
delete group.past_metadata[chatId];
updateChatMetadata(group.chat_metadata, true);
if (group.chat_id === chatId) {
group.chat_id = '';
group.chat_metadata = {};
updateChatMetadata(group.chat_metadata, true);
}
const response = await fetch('/api/chats/group/delete', {
method: 'POST',
@@ -2038,10 +2049,12 @@ export async function deleteGroupChat(groupId, chatId) {
});
if (response.ok) {
if (group.chats.length) {
await openGroupChat(groupId, group.chats[group.chats.length - 1]);
} else {
await createNewGroupChat(groupId);
if (jumpToNewChat) {
if (group.chats.length) {
await openGroupChat(groupId, group.chats[group.chats.length - 1]);
} else {
await createNewGroupChat(groupId);
}
}
await eventSource.emit(event_types.GROUP_CHAT_DELETED, chatId);
@@ -2051,9 +2064,11 @@ export async function deleteGroupChat(groupId, chatId) {
/**
* Imports a group chat from a file and adds it to the group.
* @param {FormData} formData Form data to send to the server
* @param {EventTarget} eventTarget Element that triggered the import
* @param {object} [options={}] Options for the import
* @param {boolean} [options.refresh] Whether to refresh the group chat list after import
* @returns {Promise<string[]>} List of imported file names
*/
export async function importGroupChat(formData, eventTarget) {
export async function importGroupChat(formData, { refresh = true } = {}) {
const fetchResult = await fetch('/api/chats/group/import', {
method: 'POST',
headers: getRequestHeaders({ omitContentType: true }),
@@ -2070,14 +2085,16 @@ export async function importGroupChat(formData, eventTarget) {
if (group) {
group.chats.push(chatId);
await editGroup(selected_group, true, true);
await displayPastChats();
if (refresh) {
await displayPastChats();
}
}
}
return data?.fileNames || [];
}
if (eventTarget instanceof HTMLInputElement) {
eventTarget.value = '';
}
return [];
}
export async function saveGroupBookmarkChat(groupId, name, metadata, mesId) {
@@ -2147,7 +2164,7 @@ function doCurMemberListPopout() {
// Remove pagination from popout
newElement.find('.group_pagination').empty();
$('body').append(newElement);
$('#movingDivs').append(newElement);
loadMovingUIState();
$('#groupMemberListPopout').fadeIn(animation_duration);
dragElement(newElement);
+1 -1
View File
@@ -12,7 +12,7 @@ export function showLoader() {
loaderPopup = new Popup(`
<div id="loader">
<div id="load-spinner" class="fa-solid fa-gear fa-spin fa-3x"></div>
</div>`, POPUP_TYPE.DISPLAY, null, { transparent: true, animation: 'none' });
</div>`, POPUP_TYPE.DISPLAY, null, { transparent: true, animation: 'none', wide: true, large: true });
// No close button, loaders are not closable
loaderPopup.closeButton.style.display = 'none';
+31 -1
View File
@@ -1,10 +1,11 @@
import { Handlebars, moment, seedrandom, droll } from '../lib.js';
import { chat, chat_metadata, main_api, getMaxContextSize, getCurrentChatId, substituteParams, eventSource, event_types } from '../script.js';
import { chat, chat_metadata, main_api, getMaxContextSize, getCurrentChatId, substituteParams, eventSource, event_types, extension_prompts } from '../script.js';
import { timestampToMoment, isDigitsOnly, getStringHash, escapeRegex, uuidv4 } from './utils.js';
import { textgenerationwebui_banned_in_macros } from './textgen-settings.js';
import { getInstructMacros } from './instruct-mode.js';
import { getVariableMacros } from './variables.js';
import { isMobile } from './RossAscends-mods.js';
import { inject_ids } from './constants.js';
/**
* @typedef Macro
@@ -55,6 +56,24 @@ export class MacrosParser {
}
};
/**
* Access a macro by its name.
* @param {string} key Macro name (key)
* @returns {string|MacroFunction|undefined} The macro value
*/
static get(key) {
return MacrosParser.#macros.get(key);
}
/**
* Checks if a macro is registered.
* @param {string} key Macro name (key)
* @returns {boolean} True if the macro is registered, false otherwise
*/
static has(key) {
return MacrosParser.#macros.has(key);
}
/**
* Registers a global macro that can be used anywhere where substitution is allowed.
* @param {string} key Macro name (key)
@@ -458,6 +477,16 @@ function getTimeDiffMacro() {
return { regex: timeDiffPattern, replace: timeDiffReplace };
}
/**
* Returns the outlet prompt for a given outlet key.
* @param {string} key - The outlet key
* @returns {string} The outlet prompt
*/
function getOutletPrompt(key) {
const value = extension_prompts[inject_ids.CUSTOM_WI_OUTLET(key)]?.value;
return value || '';
}
/**
* Substitutes {{macro}} parameters in a string.
* @param {string} content - The string to substitute parameters in.
@@ -518,6 +547,7 @@ export function evaluateMacros(content, env, postProcessFn) {
{ regex: /{{datetimeformat +([^}]*)}}/gi, replace: (_, format) => moment().format(format) },
{ regex: /{{idle_duration}}/gi, replace: () => getTimeSinceLastMessage() },
{ regex: /{{time_UTC([-+]\d+)}}/gi, replace: (_, offset) => moment().utc().utcOffset(parseInt(offset, 10)).format('LT') },
{ regex: /{{outlet::(.+?)}}/gi, replace: (_, key) => getOutletPrompt(key.trim()) || '' },
getTimeDiffMacro(),
getBannedWordsMacro(),
getRandomReplaceMacro(),
+224 -127
View File
@@ -276,6 +276,8 @@ export const settingsToUpdate = {
perplexity_model: ['#model_perplexity_select', 'perplexity_model', false, true],
groq_model: ['#model_groq_select', 'groq_model', false, true],
electronhub_model: ['#model_electronhub_select', 'electronhub_model', false, true],
electronhub_sort_models: ['#electronhub_sort_models', 'electronhub_sort_models', false, true],
electronhub_group_models: ['#electronhub_group_models', 'electronhub_group_models', false, true],
nanogpt_model: ['#model_nanogpt_select', 'nanogpt_model', false, true],
deepseek_model: ['#model_deepseek_select', 'deepseek_model', false, true],
aimlapi_model: ['#model_aimlapi_select', 'aimlapi_model', false, true],
@@ -370,15 +372,17 @@ const default_settings = {
scenario_format: default_scenario_format,
personality_format: default_personality_format,
openai_model: 'gpt-4-turbo',
claude_model: 'claude-3-5-sonnet-20240620',
google_model: 'gemini-1.5-pro',
vertexai_model: 'gemini-2.0-flash-001',
claude_model: 'claude-sonnet-4-5',
google_model: 'gemini-2.5-pro',
vertexai_model: 'gemini-2.5-pro',
ai21_model: 'jamba-large',
mistralai_model: 'mistral-large-latest',
cohere_model: 'command-r-plus',
perplexity_model: 'sonar-pro',
groq_model: 'llama-3.3-70b-versatile',
electronhub_model: 'gpt-4o-mini',
electronhub_sort_models: 'alphabetically',
electronhub_group_models: false,
nanogpt_model: 'gpt-4o-mini',
deepseek_model: 'deepseek-chat',
aimlapi_model: 'gpt-4o-mini-2024-07-18',
@@ -464,15 +468,17 @@ const oai_settings = {
scenario_format: default_scenario_format,
personality_format: default_personality_format,
openai_model: 'gpt-4-turbo',
claude_model: 'claude-3-5-sonnet-20240620',
google_model: 'gemini-1.5-pro',
vertexai_model: 'gemini-2.0-flash-001',
claude_model: 'claude-sonnet-4-5',
google_model: 'gemini-2.5-pro',
vertexai_model: 'gemini-2.5-pro',
ai21_model: 'jamba-large',
mistralai_model: 'mistral-large-latest',
cohere_model: 'command-r-plus',
perplexity_model: 'sonar-pro',
groq_model: 'llama-3.1-70b-versatile',
electronhub_model: 'gpt-4o-mini',
electronhub_sort_models: 'alphabetically',
electronhub_group_models: false,
nanogpt_model: 'gpt-4o-mini',
deepseek_model: 'deepseek-chat',
aimlapi_model: 'gpt-4-turbo',
@@ -1710,6 +1716,59 @@ function calculateOpenRouterCost() {
$('#openrouter_max_prompt_cost').text(cost);
}
function getElectronHubModelTemplate(option) {
const model = model_list.find(x => x.id === option?.element?.value);
if (!option.id || !model) {
return option.text;
}
const inputPrice = model.pricing?.input;
const outputPrice = model.pricing?.output;
const price = inputPrice && outputPrice ? `$${inputPrice}/$${outputPrice} in/out Mtoken` : 'Unknown';
const visionIcon = model.metadata?.vision ? '<i class="fa-solid fa-eye fa-sm" title="This model supports vision"></i>' : '';
const reasoningIcon = model.metadata?.reasoning ? '<i class="fa-solid fa-brain fa-sm" title="This model supports reasoning"></i>' : '';
const toolCallsIcon = model.metadata?.function_call ? '<i class="fa-solid fa-wrench fa-sm" title="This model supports function tools"></i>' : '';
const premiumIcon = model?.premium_model ? '<i class="fa-solid fa-crown fa-sm" title="This model requires a subscription"></i>' : '';
const iconsContainer = document.createElement('span');
iconsContainer.insertAdjacentHTML('beforeend', visionIcon);
iconsContainer.insertAdjacentHTML('beforeend', reasoningIcon);
iconsContainer.insertAdjacentHTML('beforeend', toolCallsIcon);
iconsContainer.insertAdjacentHTML('beforeend', premiumIcon);
const capabilities = (iconsContainer.children.length) ? ` | ${iconsContainer.innerHTML}` : '';
return $((`
<div class="flex-container alignItemsBaseline" title="${DOMPurify.sanitize(model.id)}">
<strong>${DOMPurify.sanitize(model.name)}</strong> | ${model.tokens} ctx | <small>${price}</small>${capabilities}
</div>
`));
}
function calculateElectronHubCost() {
if (oai_settings.chat_completion_source !== chat_completion_sources.ELECTRONHUB) {
return;
}
let cost = 'Unknown';
const model = model_list.find(x => x.id === oai_settings.electronhub_model);
if (model?.pricing) {
const outputCost = Number(model.pricing.output / 1000000);
const inputCost = Number(model.pricing.input / 1000000);
const outputTokens = oai_settings.openai_max_tokens;
const inputTokens = (oai_settings.openai_max_context - outputTokens);
const totalCost = (outputCost * outputTokens) + (inputCost * inputTokens);
if (!isNaN(totalCost)) {
cost = '$' + totalCost.toFixed(4);
}
}
$('#electronhub_max_prompt_cost').text(cost);
}
function saveModelList(data) {
model_list = data.map((model) => ({ ...model }));
model_list.sort((a, b) => a?.id && b?.id && a.id.localeCompare(b.id));
@@ -1775,44 +1834,29 @@ function saveModelList(data) {
}
if (oai_settings.chat_completion_source == chat_completion_sources.MISTRALAI) {
/** @type {HTMLSelectElement} */
const mistralModelSelect = document.querySelector('#model_mistralai_select');
if (mistralModelSelect) {
const options = Array.from(mistralModelSelect.options);
options.forEach((option) => {
const existingModel = model_list.find(model => model.id === option.value);
if (!existingModel) {
option.remove();
}
});
$('#model_mistralai_select').empty();
const otherOptionsGroup = mistralModelSelect.querySelector('#mistralai_other_models');
for (const model of model_list.filter(model => model?.capabilities?.completion_chat)) {
if (!options.some(option => option.value === model.id) && otherOptionsGroup) {
otherOptionsGroup.append(new Option(model.id, model.id));
}
}
const selectedModel = model_list.find(model => model.id === oai_settings.mistralai_model);
if (!selectedModel) {
oai_settings.mistralai_model = model_list.find(model => model?.capabilities?.completion_chat)?.id;
}
$('#model_mistralai_select').val(oai_settings.mistralai_model).trigger('change');
for (const model of model_list.filter(model => model?.capabilities?.completion_chat)) {
$('#model_mistralai_select').append(new Option(model.id, model.id));
}
const selectedModel = model_list.find(model => model.id === oai_settings.mistralai_model);
if (!selectedModel) {
oai_settings.mistralai_model = model_list.find(model => model?.capabilities?.completion_chat)?.id;
}
$('#model_mistralai_select').val(oai_settings.mistralai_model).trigger('change');
}
if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB) {
model_list = model_list.filter(model => model?.endpoints?.includes('/v1/chat/completions'));
model_list = electronHubSortBy(model_list, oai_settings.electronhub_sort_models);
$('#model_electronhub_select').empty();
model_list.forEach((model) => {
if (model?.endpoints?.includes('/v1/chat/completions')) {
$('#model_electronhub_select').append(
$('<option>', {
value: model.id,
text: model.name,
}));
}
});
const groupedList = oai_settings.electronhub_group_models ? electronHubGroupByVendor(model_list) : model_list;
appendElectronHubOptions(groupedList, oai_settings.electronhub_group_models);
const selectedModel = model_list.find(model => model.id === oai_settings.electronhub_model);
if (model_list.length > 0 && (!selectedModel || !oai_settings.electronhub_model)) {
@@ -1877,7 +1921,7 @@ function saveModelList(data) {
}
if (oai_settings.chat_completion_source === chat_completion_sources.MAKERSUITE) {
// Clear only the "Other" optgroup for dynamic models
// Clear only the "Other" optgroup for dynamic models
$('#google_other_models').empty();
// Get static model options that are already in the HTML
@@ -1888,7 +1932,7 @@ function saveModelList(data) {
// Add dynamic models to the "Other" group
model_list.forEach((model) => {
// Only add if not already in static list
// Only add if not already in static list
if (!staticModels.includes(model.id)) {
$('#google_other_models').append(
$('<option>', {
@@ -1984,6 +2028,24 @@ function saveModelList(data) {
.append(new Option(modelId || 'None', modelId || '', true, true))
.trigger('change');
}
if (oai_settings.chat_completion_source == chat_completion_sources.XAI) {
$('#model_xai_select').empty();
model_list.forEach((model) => {
$('#model_xai_select').append(
$('<option>', {
value: model.id,
text: model.id,
}));
});
const selectedModel = model_list.find(model => model.id === oai_settings.xai_model);
if (model_list.length > 0 && (!selectedModel || !oai_settings.xai_model)) {
oai_settings.xai_model = model_list[0].id;
}
$('#model_xai_select').val(oai_settings.xai_model).trigger('change');
}
}
function appendOpenRouterOptions(model_list, groupModels = false, sort = false) {
@@ -2041,6 +2103,61 @@ function openRouterGroupByVendor(array) {
}, new Map());
}
function appendElectronHubOptions(model_list, groupModels = false) {
const appendOption = (model, parent = null) => {
(parent || $('#model_electronhub_select')).append(
$('<option>', {
value: model.id,
text: model.name,
}));
};
if (groupModels) {
model_list.forEach((models, vendor) => {
const optgroup = $('<optgroup>').attr('label', vendor);
models.forEach((model) => {
appendOption(model, optgroup);
});
$('#model_electronhub_select').append(optgroup);
});
} else {
model_list.forEach((model) => {
appendOption(model);
});
}
}
function electronHubSortBy(data, property = 'alphabetically') {
return data.sort((a, b) => {
if (property === 'context_length') {
return b.tokens - a.tokens;
} else if (property === 'pricing.input') {
return parseFloat(a.pricing.input) - parseFloat(b.pricing.input);
} else if (property === 'pricing.output') {
return parseFloat(a.pricing.output) - parseFloat(b.pricing.output);
} else {
return a?.name && b?.name && a.name.localeCompare(b.name);
}
});
}
function electronHubGroupByVendor(array) {
return array.reduce((acc, curr) => {
const vendor = String(curr?.name || curr?.id || 'Other').split(':')[0].trim() || 'Other';
if (!acc.has(vendor)) {
acc.set(vendor, []);
}
acc.get(vendor).push(curr);
return acc;
}, new Map());
}
function aimlapiGroupByVendor(array) {
return array.reduce((acc, curr) => {
const vendor = curr.info.developer;
@@ -2191,7 +2308,7 @@ async function sendOpenAIRequest(type, messages, signal, { jsonSchema = null } =
const useLogprobs = !!power_user.request_token_probabilities;
const canMultiSwipe = oai_settings.n > 1 && !isContinue && !isImpersonate && !isQuiet && (isOAI || isAzureOpenAI || isCustom || isXAI || isAimlapi || isMoonshot);
const logitBiasSources = [chat_completion_sources.OPENAI, chat_completion_sources.AZURE_OPENAI, chat_completion_sources.OPENROUTER, chat_completion_sources.CUSTOM];
const logitBiasSources = [chat_completion_sources.OPENAI, chat_completion_sources.AZURE_OPENAI, chat_completion_sources.OPENROUTER, chat_completion_sources.ELECTRONHUB, chat_completion_sources.CUSTOM];
if (oai_settings.bias_preset_selected
&& logitBiasSources.includes(oai_settings.chat_completion_source)
&& Array.isArray(oai_settings.bias_presets[oai_settings.bias_preset_selected])
@@ -2353,19 +2470,24 @@ async function sendOpenAIRequest(type, messages, signal, { jsonSchema = null } =
}
if (isXAI) {
if (generate_data.model.includes('grok-4')) {
const model = generate_data.model;
if (model.includes('grok-3-mini')) {
delete generate_data.presence_penalty;
delete generate_data.frequency_penalty;
delete generate_data.stop;
} else {
// As of 2025/09/21, only grok-3-mini accepts reasoning_effort
delete generate_data.reasoning_effort;
}
if (generate_data.model.includes('grok-3-mini')) {
if (model.includes('grok-4') || model.includes('grok-code')) {
delete generate_data.presence_penalty;
delete generate_data.frequency_penalty;
}
if (generate_data.model.includes('grok-vision')) {
delete generate_data.tools;
delete generate_data.tool_choice;
// grok-4-fast-non-reasoning accepts stop
if (!model.includes('grok-4-fast-non-reasoning')) {
delete generate_data.stop;
}
}
}
@@ -2559,7 +2681,7 @@ export function getStreamingReply(data, state, { chatCompletionSource = null, ov
state.reasoning += (data.choices?.filter(x => x?.delta?.reasoning)?.[0]?.delta?.reasoning || '');
}
return data.choices?.[0]?.delta?.content ?? data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? '';
} else if ([chat_completion_sources.CUSTOM, chat_completion_sources.POLLINATIONS, chat_completion_sources.AIMLAPI, chat_completion_sources.MOONSHOT, chat_completion_sources.COMETAPI, chat_completion_sources.ELECTRONHUB].includes(chat_completion_source)) {
} else if ([chat_completion_sources.CUSTOM, chat_completion_sources.POLLINATIONS, chat_completion_sources.AIMLAPI, chat_completion_sources.MOONSHOT, chat_completion_sources.COMETAPI, chat_completion_sources.ELECTRONHUB, chat_completion_sources.NANOGPT].includes(chat_completion_source)) {
if (show_thoughts) {
state.reasoning +=
data.choices?.filter(x => x?.delta?.reasoning_content)?.[0]?.delta?.reasoning_content ??
@@ -3523,6 +3645,8 @@ function loadOpenAISettings(data, settings) {
oai_settings.perplexity_model = settings.perplexity_model ?? default_settings.perplexity_model;
oai_settings.groq_model = settings.groq_model ?? default_settings.groq_model;
oai_settings.electronhub_model = settings.electronhub_model ?? default_settings.electronhub_model;
oai_settings.electronhub_sort_models = settings.electronhub_sort_models ?? default_settings.electronhub_sort_models;
oai_settings.electronhub_group_models = settings.electronhub_group_models ?? default_settings.electronhub_group_models;
oai_settings.nanogpt_model = settings.nanogpt_model ?? default_settings.nanogpt_model;
oai_settings.deepseek_model = settings.deepseek_model ?? default_settings.deepseek_model;
oai_settings.aimlapi_model = settings.aimlapi_model ?? default_settings.aimlapi_model;
@@ -3666,6 +3790,8 @@ function loadOpenAISettings(data, settings) {
$('#openrouter_allow_fallbacks').prop('checked', oai_settings.openrouter_allow_fallbacks);
$('#openrouter_providers_chat').val(oai_settings.openrouter_providers).trigger('change');
$('#openrouter_middleout').val(oai_settings.openrouter_middleout);
$('#electronhub_sort_models').val(oai_settings.electronhub_sort_models);
$('#electronhub_group_models').prop('checked', oai_settings.electronhub_group_models);
$('#squash_system_messages').prop('checked', oai_settings.squash_system_messages);
$('#continue_prefill').prop('checked', oai_settings.continue_prefill);
$('#openai_function_calling').prop('checked', oai_settings.function_calling);
@@ -3928,6 +4054,8 @@ async function saveOpenAIPreset(name, settings, triggerUi = true) {
pollinations_model: settings.pollinations_model,
aimlapi_model: settings.aimlapi_model,
electronhub_model: settings.electronhub_model,
electronhub_sort_models: settings.electronhub_sort_models,
electronhub_group_models: settings.electronhub_group_models,
moonshot_model: settings.moonshot_model,
fireworks_model: settings.fireworks_model,
cometapi_model: settings.cometapi_model,
@@ -4532,75 +4660,8 @@ function getMistralMaxContext(model, isUnlocked) {
}
}
const contextMap = {
'codestral-2405': 32768,
'codestral-2411-rc5': 262144,
'codestral-2412': 262144,
'codestral-2501': 262144,
'codestral-2508': 256000,
'codestral-latest': 256000,
'codestral-mamba-2407': 262144,
'codestral-mamba-latest': 262144,
'open-codestral-mamba': 262144,
'ministral-3b-2410': 131072,
'ministral-3b-latest': 131072,
'ministral-8b-2410': 131072,
'ministral-8b-latest': 131072,
'mistral-large-2407': 131072,
'mistral-large-2411': 131072,
'mistral-large-latest': 131072,
'mistral-large-pixtral-2411': 131072,
'mistral-tiny-2407': 131072,
'mistral-tiny-latest': 131072,
'open-mistral-nemo': 131072,
'open-mistral-nemo-2407': 131072,
'pixtral-12b': 131072,
'pixtral-12b-2409': 131072,
'pixtral-12b-latest': 131072,
'pixtral-large-2411': 131072,
'pixtral-large-latest': 131072,
'open-mixtral-8x22b': 65536,
'open-mixtral-8x22b-2404': 65536,
'mistral-embed': 32768,
'mistral-large-2402': 32768,
'mistral-medium': 131072,
'mistral-medium-2312': 32768,
'mistral-medium-2505': 131072,
'mistral-medium-2508': 262144,
'mistral-medium-latest': 262144,
'mistral-moderation-2411': 32768,
'mistral-moderation-latest': 32768,
'mistral-ocr-2503': 32768,
'mistral-ocr-latest': 32768,
'mistral-saba-2502': 32768,
'mistral-saba-latest': 32768,
'mistral-small': 32768,
'mistral-small-2312': 32768,
'mistral-small-2402': 32768,
'mistral-small-2409': 32768,
'mistral-small-2501': 32768,
'mistral-small-2503': 32768,
'mistral-small-2506': 131072,
'mistral-small-latest': 131072,
'mistral-tiny': 32768,
'mistral-tiny-2312': 32768,
'open-mistral-7b': 32768,
'open-mixtral-8x7b': 32768,
'devstral-small-2505': 131072,
'devstral-small-2507': 131072,
'devstral-small-latest': 131072,
'devstral-medium-latest': 131072,
'devstral-medium-2507': 131072,
'magistral-medium-latest': 40960,
'magistral-medium-2506': 40960,
'magistral-small-latest': 40960,
'magistral-small-2506': 40000,
'magistral-small-2507': 40960,
'magistral-medium-2507': 40960,
};
// Return context size if model found, otherwise default to 32k
return Object.entries(contextMap).find(([key]) => model.includes(key))?.[1] || 32768;
return max_32k;
}
/**
@@ -4878,6 +4939,10 @@ async function onModelChange() {
}
if ($(this).is('#model_xai_select')) {
if (!value) {
console.debug('Null XAI model selected. Ignoring.');
return;
}
console.log('XAI model changed to', value);
oai_settings.xai_model = value;
}
@@ -4916,17 +4981,15 @@ async function onModelChange() {
if ([chat_completion_sources.MAKERSUITE, chat_completion_sources.VERTEXAI].includes(oai_settings.chat_completion_source)) {
if (oai_settings.max_context_unlocked) {
$('#openai_max_context').attr('max', max_2mil);
} else if (value.includes('gemini-1.5-pro')) {
$('#openai_max_context').attr('max', max_2mil);
} else if (value.includes('gemini-2.5-flash-image-preview')) {
} else if (value.includes('gemini-2.5-flash-image')) {
$('#openai_max_context').attr('max', max_32k);
} else if (value.includes('gemini-1.5-flash') || value.includes('gemini-2.0-flash') || value.includes('gemini-2.0-pro') || value.includes('gemini-exp') || value.includes('gemini-2.5-flash') || value.includes('gemini-2.5-pro') || value.includes('learnlm-2.0-flash')) {
} else if (value.includes('gemini-2.0-flash') || value.includes('gemini-2.0-pro') || value.includes('gemini-exp') || value.includes('gemini-2.5-flash') || value.includes('gemini-2.5-pro') || value.includes('learnlm-2.0-flash') || value.includes('gemini-robotics')) {
$('#openai_max_context').attr('max', max_1mil);
} else if (value.includes('gemma-3-27b-it')) {
$('#openai_max_context').attr('max', max_128k);
} else if (value.includes('gemma-3n-e4b-it')) {
$('#openai_max_context').attr('max', max_8k);
} else if (value.includes('gemma-3') || value.includes('learnlm-1.5-pro-experimental')) {
} else if (value.includes('gemma-3')) {
$('#openai_max_context').attr('max', max_32k);
} else {
$('#openai_max_context').attr('max', max_32k);
@@ -4966,9 +5029,12 @@ async function onModelChange() {
if (oai_settings.chat_completion_source == chat_completion_sources.CLAUDE) {
if (oai_settings.max_context_unlocked) {
$('#openai_max_context').attr('max', max_200k);
$('#openai_max_context').attr('max', unlocked_max);
}
else if (value == 'claude-2.1' || value.startsWith('claude-3') || value.startsWith('claude-opus') || value.startsWith('claude-sonnet')) {
else if (value.startsWith('claude-sonnet-4-5')) {
$('#openai_max_context').attr('max', max_1mil);
}
else if (value == 'claude-2.1' || value.startsWith('claude-3') || value.startsWith('claude-opus') || value.startsWith('claude-haiku') || value.startsWith('claude-sonnet')) {
$('#openai_max_context').attr('max', max_200k);
}
else if (value.endsWith('100k') || value.startsWith('claude-2') || value === 'claude-instant-1.2') {
@@ -5093,6 +5159,8 @@ async function onModelChange() {
$('#openai_max_context').val(oai_settings.openai_max_context).trigger('input');
oai_settings.temp_openai = Math.min(oai_max_temp, oai_settings.temp_openai);
$('#temp_openai').attr('max', oai_max_temp).val(oai_settings.temp_openai).trigger('input');
calculateElectronHubCost();
}
if (oai_settings.chat_completion_source === chat_completion_sources.NANOGPT) {
@@ -5144,11 +5212,14 @@ async function onModelChange() {
$('#openai_max_context').attr('max', unlocked_max);
} else if (oai_settings.xai_model.includes('grok-2-vision')) {
$('#openai_max_context').attr('max', max_32k);
} else if (oai_settings.xai_model.includes('grok-vision')) {
$('#openai_max_context').attr('max', max_8k);
} else if (oai_settings.xai_model.includes('grok-4-fast')) {
$('#openai_max_context').attr('max', max_2mil);
} else if (oai_settings.xai_model.includes('grok-4')) {
$('#openai_max_context').attr('max', max_256k);
} else if (oai_settings.xai_model.includes('grok-code')) {
$('#openai_max_context').attr('max', max_256k);
} else {
// grok 2 and grok 3
$('#openai_max_context').attr('max', max_128k);
}
@@ -5220,6 +5291,10 @@ async function onOpenrouterModelSortChange() {
await getStatusOpen();
}
async function onElectronHubModelSortChange() {
await getStatusOpen();
}
async function onNewPresetClick() {
const name = await Popup.show.input(t`Preset name:`, t`Hint: Use a character/group name to bind preset to a specific chat.`, oai_settings.preset_settings_openai);
@@ -5677,11 +5752,11 @@ export function isImageInliningSupported() {
'c4ai-aya-vision',
'command-a-vision',
// Google AI Studio
'gemini-1.5',
'gemini-2.0',
'gemini-2.5',
'gemini-exp-1206',
'learnlm',
'gemini-robotics',
// MistralAI
'mistral-small-2503',
'mistral-small-2506',
@@ -5693,7 +5768,6 @@ export function isImageInliningSupported() {
// xAI (Grok)
'grok-4',
'grok-2-vision',
'grok-vision',
// Moonshot
'moonshot-v1-8k-vision-preview',
'moonshot-v1-32k-vision-preview',
@@ -5726,6 +5800,7 @@ export function isImageInliningSupported() {
case chat_completion_sources.COHERE:
return visionSupportedModels.some(model => oai_settings.cohere_model.includes(model));
case chat_completion_sources.XAI:
// TODO: xAI's /models endpoint doesn't return modality info
return visionSupportedModels.some(model => oai_settings.xai_model.includes(model));
case chat_completion_sources.AIMLAPI:
return (Array.isArray(model_list) && model_list.find(m => m.id === oai_settings.aimlapi_model)?.features?.includes('openai/chat-completion.vision'));
@@ -6117,12 +6192,14 @@ export function initOpenAI() {
oai_settings.openai_max_context = Number($(this).val());
$('#openai_max_context_counter').val(`${$(this).val()}`);
calculateOpenRouterCost();
calculateElectronHubCost();
saveSettingsDebounced();
});
$('#openai_max_tokens').on('input', function () {
oai_settings.openai_max_tokens = Number($(this).val());
calculateOpenRouterCost();
calculateElectronHubCost();
saveSettingsDebounced();
});
@@ -6326,6 +6403,16 @@ export function initOpenAI() {
saveSettingsDebounced();
});
$('#electronhub_sort_models').on('input', function () {
oai_settings.electronhub_sort_models = String($(this).val());
saveSettingsDebounced();
});
$('#electronhub_group_models').on('input', function () {
oai_settings.electronhub_group_models = !!$(this).prop('checked');
saveSettingsDebounced();
});
$('#squash_system_messages').on('input', function () {
oai_settings.squash_system_messages = !!$(this).prop('checked');
saveSettingsDebounced();
@@ -6503,6 +6590,14 @@ export function initOpenAI() {
width: '100%',
templateResult: getAimlapiModelTemplate,
});
$('#model_electronhub_select').select2({
placeholder: t`Select a model`,
searchInputPlaceholder: t`Search models...`,
searchInputCssClass: 'text_pole',
width: '100%',
templateResult: getElectronHubModelTemplate,
matcher: textValueMatcher,
});
$('#completion_prompt_manager_popup_entry_form_injection_trigger').select2({
placeholder: t`All types (default)`,
width: '100%',
@@ -6549,6 +6644,8 @@ export function initOpenAI() {
$('#model_openrouter_select').on('change', onModelChange);
$('#openrouter_group_models').on('change', onOpenrouterModelSortChange);
$('#openrouter_sort_models').on('change', onOpenrouterModelSortChange);
$('#electronhub_group_models').on('change', onElectronHubModelSortChange);
$('#electronhub_sort_models').on('change', onElectronHubModelSortChange);
$('#model_ai21_select').on('change', onModelChange);
$('#model_mistralai_select').on('change', onModelChange);
$('#model_cohere_select').on('change', onModelChange);
+39 -22
View File
@@ -4,9 +4,11 @@ import {
characters,
chat,
chat_metadata,
createOrEditCharacter,
default_user_avatar,
eventSource,
event_types,
getCurrentChatId,
getRequestHeaders,
getThumbnailUrl,
groupToEntity,
@@ -69,6 +71,9 @@ export let user_avatar = '';
/** @type {FilterHelper} Filter helper for the persona list */
export const personasFilter = new FilterHelper(debounce(getUserAvatars, debounce_timeout.quick));
/** @type {string} The last loaded chat id to remember for persona loading */
let personaLastLoadedChatId = null;
/** @type {function(string): void} */
let navigateToAvatar = () => { };
@@ -107,12 +112,16 @@ export function initUserAvatar(avatar) {
* @param {boolean} [options.toastPersonaNameChange=true] Whether to show a toast when the persona name is changed
* @param {boolean} [options.navigateToCurrent=false] Whether to navigate to the current persona after setting the avatar
*/
export function setUserAvatar(imgfile, { toastPersonaNameChange = true, navigateToCurrent = false } = {}) {
export async function setUserAvatar(imgfile, { toastPersonaNameChange = true, navigateToCurrent = false } = {}) {
const currentUserAvatar = user_avatar;
user_avatar = imgfile && typeof imgfile === 'string' ? imgfile : $(this).attr('data-avatar-id');
if (currentUserAvatar === user_avatar) {
return;
}
reloadUserAvatar();
updatePersonaUIStates({ navigateToCurrent: navigateToCurrent });
selectCurrentPersona({ toastPersonaNameChange: toastPersonaNameChange });
retriggerFirstMessageOnEmptyChat();
await retriggerFirstMessageOnEmptyChat();
saveSettingsDebounced();
$('.zoomed_avatar[forchar]').remove();
}
@@ -732,13 +741,13 @@ export async function askForPersonaSelection(title, text, personas, { okButton =
/**
* Automatically selects a persona based on the given name if a matching persona exists.
* @param {string} name - The name to search for
* @returns {boolean} True if a matching persona was found and selected, false otherwise
* @returns {Promise<boolean>} True if a matching persona was found and selected, false otherwise
*/
export function autoSelectPersona(name) {
export async function autoSelectPersona(name) {
for (const [key, value] of Object.entries(power_user.personas)) {
if (value === name) {
console.log(`Auto-selecting persona ${key} for name ${name}`);
setUserAvatar(key);
await setUserAvatar(key);
return true;
}
}
@@ -1131,7 +1140,7 @@ function onPersonaDescriptionInput() {
object.description = power_user.persona_description;
}
$(`.avatar-container[imgfile="${user_avatar}"] .ch_description`)
$(`.avatar-container[data-avatar-id="${user_avatar}"] .ch_description`)
.text(power_user.persona_description || $('#user_avatar_block').attr('no_desc_text'))
.toggleClass('text_muted', !power_user.persona_description);
saveSettingsDebounced();
@@ -1219,7 +1228,7 @@ function onPersonaDescriptionPositionInput() {
$('#persona_depth_position_settings').toggle(power_user.persona_description_position === persona_description_positions.AT_DEPTH);
}
function getOrCreatePersonaDescriptor() {
export function getOrCreatePersonaDescriptor() {
let object = power_user.persona_descriptions[user_avatar];
if (!object) {
@@ -1429,13 +1438,17 @@ function getPersonaTemporaryLockInfo() {
* @returns {Promise<boolean>} - A promise that resolves to a boolean indicating whether a persona was selected
*/
async function loadPersonaForCurrentChat({ doRender = false } = {}) {
const currentChatId = getCurrentChatId();
if (currentChatId === personaLastLoadedChatId) return;
personaLastLoadedChatId = currentChatId;
// Cache persona list to check if they exist
const userAvatars = await getUserAvatars(doRender);
// Check if the user avatar is set and exists in the list of user avatars
if (userAvatars.length && !userAvatars.includes(user_avatar)) {
console.log(`User avatar ${user_avatar} not found in user avatars list, pick the first available one`);
setUserAvatar(userAvatars[0], { toastPersonaNameChange: false, navigateToCurrent: true });
await setUserAvatar(userAvatars[0], { toastPersonaNameChange: false, navigateToCurrent: true });
}
// Define a persona for this chat
@@ -1530,7 +1543,7 @@ async function loadPersonaForCurrentChat({ doRender = false } = {}) {
// Persona avatar found, select it
if (chatPersona && user_avatar !== chatPersona) {
const willAutoLock = power_user.persona_auto_lock && user_avatar !== chat_metadata['persona'];
setUserAvatar(chatPersona, { toastPersonaNameChange: false, navigateToCurrent: true });
await setUserAvatar(chatPersona, { toastPersonaNameChange: false, navigateToCurrent: true });
if (power_user.persona_show_notifications) {
let message = t`Auto-selected persona based on ${connectType} connection.<br />Your messages will now be sent as ${power_user.personas[chatPersona]}.`;
@@ -1542,7 +1555,7 @@ async function loadPersonaForCurrentChat({ doRender = false } = {}) {
}
// Even if it's the same persona, we still might need to auto-lock to chat if that's enabled
else if (chatPersona && power_user.persona_auto_lock && !chat_metadata['persona']) {
lockPersona('chat');
await lockPersona('chat');
}
updatePersonaUIStates();
@@ -1559,7 +1572,7 @@ async function loadPersonaForCurrentChat({ doRender = false } = {}) {
export function getConnectedPersonas(characterKey = undefined) {
characterKey ??= selected_group || characters[Number(this_chid)]?.avatar;
const connectedPersonas = Object.entries(power_user.persona_descriptions)
.filter(([_, desc]) => desc.connections?.some(conn => conn.type === 'character' && conn.id === characterKey))
.filter(([_, { connections }]) => connections?.some(conn => conn.id === characterKey))
.map(([key, _]) => key);
return connectedPersonas;
}
@@ -1606,7 +1619,7 @@ export async function showCharConnections() {
// One of the persona was selected. So load it.
if (!isRemoving && selectedPersona) {
setUserAvatar(selectedPersona, { toastPersonaNameChange: false });
await setUserAvatar(selectedPersona, { toastPersonaNameChange: false });
if (power_user.persona_show_notifications) {
toastr.success(t`Selected persona ${power_user.personas[selectedPersona]} for current chat.`, t`Connected Persona Selected`);
}
@@ -1736,12 +1749,16 @@ async function syncUserNameToPersona() {
/**
* Retriggers the first message to reload it from the char definition.
*
* Only works if only the first message is present, and not in group mode.
*/
export function retriggerFirstMessageOnEmptyChat() {
if (Number(this_chid) >= 0 && !selected_group && chat.length === 1) {
$('#firstmessage_textarea').trigger('input');
export async function retriggerFirstMessageOnEmptyChat() {
if (chat_metadata.tainted) {
return;
}
if (selected_group) {
await reloadCurrentChat();
}
if (!selected_group && Number(this_chid) >= 0 && chat.length === 1) {
await createOrEditCharacter();
}
}
@@ -1838,9 +1855,9 @@ async function lockPersonaCallback(_args, value) {
* Sets a persona name and optionally an avatar.
* @param {{mode: 'lookup' | 'temp' | 'all'}} namedArgs Named arguments
* @param {string} name Name to set
* @returns {string}
* @returns {Promise<string>}
*/
function setNameCallback({ mode = 'all' }, name) {
async function setNameCallback({ mode = 'all' }, name) {
if (!name) {
toastr.warning('You must specify a name to change to');
return '';
@@ -1858,7 +1875,7 @@ function setNameCallback({ mode = 'all' }, name) {
let persona = Object.entries(power_user.personas).find(([avatar, _]) => avatar === name)?.[1];
if (!persona) persona = Object.entries(power_user.personas).find(([_, personaName]) => personaName.toLowerCase() === name.toLowerCase())?.[1];
if (persona) {
autoSelectPersona(persona);
await autoSelectPersona(persona);
return '';
} else if (mode === 'lookup') {
toastr.warning(`Persona ${name} not found`);
@@ -2016,9 +2033,9 @@ export async function initPersonas() {
$('#sync_name_button').on('click', syncUserNameToPersona);
$('#avatar_upload_file').on('change', changeUserAvatar);
$(document).on('click', '#user_avatar_block .avatar-container', function () {
$(document).on('click', '#user_avatar_block .avatar-container', async function () {
const imgfile = $(this).attr('data-avatar-id');
setUserAvatar(imgfile);
await setUserAvatar(imgfile);
});
$('#persona_rename_button').on('click', () => renamePersona(user_avatar));
+18 -4
View File
@@ -37,8 +37,8 @@ export const POPUP_RESULT = {
/**
* @typedef {object} PopupOptions
* @property {string|boolean?} [okButton=null] - Custom text for the OK button, or `true` to use the default (If set, the button will always be displayed, no matter the type of popup)
* @property {string|boolean?} [cancelButton=null] - Custom text for the Cancel button, or `true` to use the default (If set, the button will always be displayed, no matter the type of popup)
* @property {string|boolean?} [okButton=null] - Custom text for the OK button. A set text will always show the button. `true` or `false` to explicitly show or hide the button. `null` will leave the behavior and display of the button unchanged, based on the popup type.
* @property {string|boolean?} [cancelButton=null] - Custom text for the Cancel button. A set text will always show the button. `true` or `false` to explicitly show or hide the button. `null` will leave the behavior and display of the button unchanged, based on the popup type.
* @property {number?} [rows=1] - The number of rows for the input field
* @property {boolean?} [wide=false] - Whether to display the popup in wide mode (wide screen, 1/1 aspect ratio)
* @property {boolean?} [wider=false] - Whether to display the popup in wider mode (just wider, no height scaling)
@@ -326,21 +326,31 @@ export class Popup {
switch (type) {
case POPUP_TYPE.TEXT: {
//Text shows OK if not explicitly set to false, and CANCEL only if defined as true or with a caption
if (okButton === false) this.okButton.style.display = 'none';
if (!cancelButton) this.cancelButton.style.display = 'none';
break;
}
case POPUP_TYPE.CONFIRM: {
// Confirm shows OK if not explicitly set to false, and CANCEL if not explicitly set to false
if (okButton === false) this.okButton.style.display = 'none';
if (cancelButton === false) this.cancelButton.style.display = 'none';
// Override default captions for confirm on OK->Yes, CANCEL->No
if (!okButton) this.okButton.textContent = template.getAttribute('popup-button-yes');
if (!cancelButton) this.cancelButton.textContent = template.getAttribute('popup-button-no');
break;
}
case POPUP_TYPE.INPUT: {
this.mainInput.style.display = 'block';
if (!okButton) this.okButton.textContent = template.getAttribute('popup-button-save');
// Input shows OK if not explicitly set to false, and CANCEL if not explicitly set to false
if (okButton === false) this.okButton.style.display = 'none';
if (cancelButton === false) this.cancelButton.style.display = 'none';
// Override default captions for input on OK->Save
if (!okButton) this.okButton.textContent = template.getAttribute('popup-button-save');
break;
}
case POPUP_TYPE.DISPLAY: {
// Display hides OK and CANCEL and all main button controls
this.buttonControls.style.display = 'none';
this.closeButton.style.display = 'block';
break;
@@ -348,7 +358,6 @@ export class Popup {
case POPUP_TYPE.CROP: {
this.cropWrap.style.display = 'block';
this.cropImage.src = cropImage;
if (!okButton) this.okButton.textContent = template.getAttribute('popup-button-crop');
$(this.cropImage).cropper({
aspectRatio: cropAspect ?? 2 / 3,
autoCropArea: 1,
@@ -359,6 +368,11 @@ export class Popup {
this.cropData.want_resize = !power_user.never_resize_avatars;
},
});
// Crop shows OK if not explicitly set to false, and CANCEL if not explicitly set to false
if (okButton === false) this.okButton.style.display = 'none';
if (cancelButton === false) this.cancelButton.style.display = 'none';
// Override default captions for crop on OK->Crop
if (!okButton) this.okButton.textContent = template.getAttribute('popup-button-crop');
break;
}
default: {
+10 -1
View File
@@ -137,6 +137,7 @@ export const power_user = {
streaming_fps: 30,
smooth_streaming: false,
smooth_streaming_speed: 50,
stream_fade_in: false,
fast_ui_mode: true,
avatar_style: avatar_styles.ROUND,
@@ -1068,7 +1069,8 @@ function applyToastrPosition() {
toastr.options.positionClass = power_user.toastr_position;
fixToastrForDialogs();
$('#toastr_position').val(power_user.toastr_position).prop('selected', true);
$('#toastr_position').val(power_user.toastr_position);
$(`#toastr_position option[value="${power_user.toastr_position}"]`).prop('selected', true);
}
function applyChatWidth(type) {
@@ -1684,6 +1686,8 @@ export async function loadPowerUserSettings(settings, data) {
$('#smooth_streaming').prop('checked', power_user.smooth_streaming);
$('#smooth_streaming_speed').val(power_user.smooth_streaming_speed);
$('#stream_fade_in').prop('checked', power_user.stream_fade_in);
$('#font_scale').val(power_user.font_scale);
$('#font_scale_counter').val(power_user.font_scale);
@@ -3492,6 +3496,11 @@ jQuery(() => {
saveSettingsDebounced();
});
$('#stream_fade_in').on('input', function () {
power_user.stream_fade_in = !!$(this).prop('checked');
saveSettingsDebounced();
});
$('input[name="font_scale"]').on('input', async function (e, data) {
const applyMode = data?.forced ? 'forced' : 'normal';
power_user.font_scale = Number($(this).val());
+14 -10
View File
@@ -81,6 +81,9 @@ function autoSelectPreset() {
* @returns {PresetManager} Preset manager
*/
export function getPresetManager(apiId = '') {
if (apiId === 'koboldhorde') {
apiId = 'kobold';
}
if (!apiId) {
apiId = main_api == 'koboldhorde' ? 'kobold' : main_api;
}
@@ -814,7 +817,7 @@ class PresetManager {
* Reads a preset extension field from the preset.
* @param {object} options
* @param {string} [options.name] Name of the preset. If not provided, uses the currently selected preset name.
* @param {string} options.path Path to the preset extension field, e.g. 'myextension.data'.
* @param {string} options.path Path to the preset extension field, e.g. 'myextension.data'. If empty, reads the entire extensions object.
* @return {any} The value of the preset extension field, or null if not found.
*/
readPresetExtensionField({ name, path }) {
@@ -825,7 +828,7 @@ class PresetManager {
// Read from settings if the selected preset is the same as the provided name
if (settings && selectedName === presetName) {
const settingsExtensions = ensurePlainObject(settings.extensions || {});
return lodash.get(settingsExtensions, path, null);
return path ? lodash.get(settingsExtensions, path, null) : settingsExtensions;
}
// Otherwise, read from the preset by name
@@ -835,7 +838,7 @@ class PresetManager {
}
const presetExtensions = ensurePlainObject(preset.extensions || {});
const value = lodash.get(presetExtensions, path, null);
const value = path ? lodash.get(presetExtensions, path, null) : presetExtensions;
return value;
}
@@ -843,7 +846,7 @@ class PresetManager {
* Writes a value to a preset extension field.
* @param {object} options
* @param {string} [options.name] Name of the preset. If not provided, uses the currently selected preset name.
* @param {string} options.path Path to the preset extension field, e.g. 'myextension.data'.
* @param {string} options.path Path to the preset extension field, e.g. 'myextension.data'. If empty, writes to the root of the extensions object.
* @param {any} options.value Value to write to the preset extension field.
* @return {Promise<void>} Resolves when the preset is saved.
*/
@@ -856,7 +859,7 @@ class PresetManager {
if (settings && selectedName === presetName) {
// Set the value at the specified path
settings.extensions = ensurePlainObject(settings.extensions || {});
lodash.set(settings.extensions, path, value);
path ? lodash.set(settings.extensions, path, value) : (settings.extensions = value);
await saveSettings();
}
@@ -868,7 +871,7 @@ class PresetManager {
// Set the value at the specified path
preset.extensions = ensurePlainObject(preset.extensions || {});
lodash.set(preset.extensions, path, value);
path ? lodash.set(preset.extensions, path, value) : (preset.extensions = value);
// Save the updated preset
await this.savePreset(presetName, preset, { skipUpdate: true });
@@ -1033,10 +1036,11 @@ export async function initPresetManager() {
return;
}
await eventSource.emit(event_types.PRESET_RENAMED_BEFORE, { apiId: apiId, oldName: oldName, newName: newName });
const extensions = presetManager.readPresetExtensionField({ name: oldName, path: '' });
await presetManager.renamePreset(newName);
await eventSource.emit(event_types.PRESET_DELETED, { apiId: apiId, name: oldName });
await eventSource.emit(event_types.PRESET_CHANGED, { apiId: apiId, name: newName });
await presetManager.writePresetExtensionField({ name: newName, path: '', value: extensions });
await eventSource.emit(event_types.PRESET_RENAMED, { apiId: apiId, oldName: oldName, newName: newName });
if (apiId === 'openai') {
// This is a horrible mess, but prevents the renamed preset from being corrupted.
@@ -1116,13 +1120,13 @@ export async function initPresetManager() {
if (result) {
const successToast = !presetManager.isAdvancedFormatting() ? t`Preset deleted` : t`Template deleted`;
toastr.success(successToast);
await eventSource.emit(event_types.PRESET_DELETED, { apiId, name });
} else {
const warningToast = !presetManager.isAdvancedFormatting() ? t`Preset was not deleted from server` : t`Template was not deleted from server`;
toastr.warning(warningToast);
}
saveSettingsDebounced();
await eventSource.emit(event_types.PRESET_DELETED, { apiId: apiId, name: name });
});
$(document).on('click', '[data-preset-manager-restore]', async function () {
+9 -1
View File
@@ -15,6 +15,7 @@ import { commonEnumProviders, enumIcons } from './slash-commands/SlashCommandCom
import { enumTypes, SlashCommandEnumValue } from './slash-commands/SlashCommandEnumValue.js';
import { SlashCommandParser } from './slash-commands/SlashCommandParser.js';
import { textgen_types, textgenerationwebui_settings } from './textgen-settings.js';
import { applyStreamFadeIn } from './util/stream-fadein.js';
import { copyText, escapeRegex, isFalseBoolean, isTrueBoolean, setDatasetProperty, trimSpaces } from './utils.js';
/**
@@ -124,6 +125,8 @@ export function extractReasoningFromData(data, {
case chat_completion_sources.POLLINATIONS:
case chat_completion_sources.MOONSHOT:
case chat_completion_sources.COMETAPI:
case chat_completion_sources.ELECTRONHUB:
case chat_completion_sources.NANOGPT:
case chat_completion_sources.CUSTOM: {
return data?.choices?.[0]?.message?.reasoning_content
?? data?.choices?.[0]?.message?.reasoning
@@ -495,7 +498,12 @@ export class ReasoningHandler {
// Update the reasoning message
const reasoning = trimSpaces(this.reasoningDisplayText ?? this.reasoning);
const displayReasoning = messageFormatting(reasoning, '', false, false, messageId, {}, true);
this.messageReasoningContentDom.innerHTML = displayReasoning;
if (power_user.stream_fade_in) {
applyStreamFadeIn(this.messageReasoningContentDom, displayReasoning);
} else {
this.messageReasoningContentDom.innerHTML = displayReasoning;
}
// Update tooltip for hidden reasoning edit
/** @type {HTMLElement} */
+26 -8
View File
@@ -2,7 +2,7 @@ import { DOMPurify, moment } from '../lib.js';
import { event_types, eventSource, getRequestHeaders } from '../script.js';
import { t } from './i18n.js';
import { chat_completion_sources } from './openai.js';
import { callGenericPopup, Popup, POPUP_TYPE } from './popup.js';
import { callGenericPopup, Popup, POPUP_RESULT, POPUP_TYPE } from './popup.js';
import { SlashCommand } from './slash-commands/SlashCommand.js';
import { ARGUMENT_TYPE, SlashCommandArgument, SlashCommandNamedArgument } from './slash-commands/SlashCommandArgument.js';
import { enumIcons } from './slash-commands/SlashCommandCommonEnumsProvider.js';
@@ -293,11 +293,13 @@ export let secret_state = {};
* @param {string} key Secret key
* @param {string} value Secret value to write
* @param {string} [label] (Optional) Label for the key. If not provided, generated automatically.
* @param {Object} [options] Additional options
* @param {boolean} [options.allowEmpty] Whether to allow writing empty values. If false and value is empty, the secret will be deleted.
* @return {Promise<string?>} The ID of the newly created secret key, or null if no value is provided.
*/
export async function writeSecret(key, value, label) {
export async function writeSecret(key, value, label, { allowEmpty } = {}) {
try {
if (!value) {
if (!value && !allowEmpty) {
console.warn(`No value provided for ${key} in writeSecret, redirecting to deleteSecret`);
await deleteSecret(key);
return null;
@@ -558,7 +560,8 @@ async function openKeyManagerDialog(key) {
const template = $(await renderTemplateAsync('secretKeyManager', { name, key }));
template.find('button[data-action="add-secret"]').on('click', async function () {
let label = '';
const value = await Popup.show.input(t`Add Secret`, t`Enter the secret value:`, '', {
let result = POPUP_RESULT.CANCELLED;
const value = await Popup.show.input(t`Add Secret`, t`Enter the secret value (can be empty):`, '', {
customInputs: [{
id: 'newSecretLabel',
type: 'text',
@@ -567,13 +570,20 @@ async function openKeyManagerDialog(key) {
onClose: popup => {
if (popup.result) {
label = popup.inputResults.get('newSecretLabel').toString().trim();
result = popup.result;
}
},
});
if (!value) {
return;
if (result !== POPUP_RESULT.AFFIRMATIVE) {
return;
}
const allowEmpty = await Popup.show.confirm(t`No value entered`, t`No value was entered for the secret. Do you want to add an empty secret?`);
if (!allowEmpty) {
return;
}
}
await writeSecret(key, value, label);
await writeSecret(key, value, label, { allowEmpty: true });
await renderSecretsList();
});
@@ -821,6 +831,13 @@ function registerSecretSlashCommands() {
isRequired: false,
typeList: [ARGUMENT_TYPE.STRING],
}),
SlashCommandNamedArgument.fromProps({
name: 'empty',
description: t`Whether to allow empty values.`,
isRequired: false,
typeList: [ARGUMENT_TYPE.BOOLEAN],
defaultValue: String(false),
}),
],
unnamedArgumentList: [
SlashCommandArgument.fromProps({
@@ -831,6 +848,7 @@ function registerSecretSlashCommands() {
],
callback: async (args, value) => {
const quiet = isTrueBoolean(args?.quiet?.toString());
const allowEmpty = isTrueBoolean(args?.empty?.toString());
const key = args?.key?.toString()?.trim() || resolveSecretKey();
if (!key) {
@@ -849,7 +867,7 @@ function registerSecretSlashCommands() {
}
const valueStr = value?.toString()?.trim();
if (!valueStr) {
if (!valueStr && !allowEmpty) {
if (!quiet) {
toastr.error(t`No value provided for the secret key: ${key}`);
}
@@ -857,7 +875,7 @@ function registerSecretSlashCommands() {
}
const label = args?.label?.toString()?.trim() || getLabel();
const id = await writeSecret(key, valueStr, label);
const id = await writeSecret(key, valueStr, label, { allowEmpty });
if (!quiet) {
toastr.success(t`Secret has been written for the key: ${key}`);
+8
View File
@@ -4585,6 +4585,8 @@ export async function sendMessageAs(args, text) {
insertAt = chat.length + insertAt;
}
chat_metadata['tainted'] = true;
if (!isNaN(insertAt) && insertAt >= 0 && insertAt <= chat.length) {
chat.splice(insertAt, 0, message);
await saveChatConditional();
@@ -4635,6 +4637,8 @@ export async function sendNarratorMessage(args, text) {
insertAt = chat.length + insertAt;
}
chat_metadata['tainted'] = true;
if (!isNaN(insertAt) && insertAt >= 0 && insertAt <= chat.length) {
chat.splice(insertAt, 0, message);
await saveChatConditional();
@@ -4685,6 +4689,8 @@ export async function promptQuietForLoudResponse(who, text) {
},
};
chat_metadata['tainted'] = true;
chat.push(message);
await eventSource.emit(event_types.MESSAGE_SENT, (chat.length - 1));
addOneMessage(message);
@@ -4719,6 +4725,8 @@ async function sendCommentMessage(args, text) {
insertAt = chat.length + insertAt;
}
chat_metadata['tainted'] = true;
if (!isNaN(insertAt) && insertAt >= 0 && insertAt <= chat.length) {
chat.splice(insertAt, 0, message);
await saveChatConditional();
+2
View File
@@ -57,6 +57,7 @@ import {
import {
extension_settings,
ModuleWorkerWrapper,
openThirdPartyExtensionMenu,
renderExtensionTemplate,
renderExtensionTemplateAsync,
saveMetadataDebounced,
@@ -233,6 +234,7 @@ export function getContext() {
parseReasoningFromString,
unshallowCharacter,
unshallowGroupMembers,
openThirdPartyExtensionMenu,
symbols: {
ignore: IGNORE_SYMBOL,
},
+5
View File
@@ -765,8 +765,13 @@ async function importTags(character, { importSetting = null } = {}) {
*/
async function handleTagImport(character, { importSetting = null } = {}) {
/** @type {string[]} */
const alreadyAssignedTags = tag_map[character.avatar] ?? [];
const importTags = character.tags.map(t => t.trim()).filter(t => t)
.filter(t => !IMPORT_EXLCUDED_TAGS.includes(t))
.filter(t => {
const existingTag = getTag(t);
return !existingTag || !alreadyAssignedTags.includes(existingTag.id);
})
.slice(0, ANTI_TROLL_MAX_TAGS);
const existingTags = getExistingTags(importTags);
const newTags = importTags.filter(t => !existingTags.some(existingTag => existingTag.name.toLowerCase() === t.toLowerCase()))
+2
View File
@@ -22,8 +22,10 @@
<li><tt>&lcub;&lcub;char&rcub;&rcub;</tt> – <span data-i18n="help_macros_16">the Character's name</span></li>
<li><tt>&lcub;&lcub;version&rcub;&rcub;</tt> – <span data-i18n="help_macros_17">the Character's version number</span></li>
<li><tt>&lcub;&lcub;charDepthPrompt&rcub;&rcub;</tt> – <span data-i18n="help_macros_charDepthPrompt">the Character's @ Depth Note</span></li>
<li><tt>&lcub;&lcub;outlet::(name)&rcub;&rcub;</tt> – <span data-i18n="help_macros_outletName">the WI entry content for the outlet with the specified name</span></li>
<li><tt>&lcub;&lcub;group&rcub;&rcub;</tt> – <span data-i18n="help_macros_18">a comma-separated list of group member names (including muted) or the character name in solo chats. Alias: &lcub;&lcub;charIfNotGroup&rcub;&rcub;</span></li>
<li><tt>&lcub;&lcub;groupNotMuted&rcub;&rcub;</tt> – <span data-i18n="help_groupNotMuted">the same as &lcub;&lcub;group&rcub;&rcub;, but excludes muted members</span></li>
<li><tt>&lcub;&lcub;notChar&rcub;&rcub;</tt> – <span data-i18n="help_notChar">a comma-separated list of all participants in the conversation except for the current speaker (&lcub;&lcub;char&rcub;&rcub;). In group chats, this includes muted characters. When not in a generation, the list include all characters.</span></li>
<li><tt>&lcub;&lcub;model&rcub;&rcub;</tt> – <span data-i18n="help_macros_19">a text generation model name for the currently selected API. </span><b data-i18n="Can be inaccurate!">Can be inaccurate!</b></li>
<li><tt>&lcub;&lcub;lastMessage&rcub;&rcub;</tt> – <span data-i18n="help_macros_20">the text of the latest chat message.</span></li>
<li><tt>&lcub;&lcub;lastUserMessage&rcub;&rcub;</tt> – <span data-i18n="help_macros_lastUser">the text of the latest user chat message.</span></li>
+51
View File
@@ -648,6 +648,57 @@ export function getTokenizerModel() {
}
}
if (oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB && oai_settings.electronhub_model) {
if (oai_settings.electronhub_model.includes('gpt-4o') || oai_settings.electronhub_model.includes('gpt-5')) {
return gpt4oTokenizer;
}
else if (oai_settings.electronhub_model.includes('gpt-4.1') || oai_settings.electronhub_model.includes('gpt-4.5')) {
return gpt4oTokenizer;
}
else if (oai_settings.electronhub_model.includes('gpt-4')) {
return gpt4Tokenizer;
}
else if (oai_settings.electronhub_model.includes('gpt-3.5-turbo')) {
return turboTokenizer;
}
else if (oai_settings.electronhub_model.includes('claude')) {
return claudeTokenizer;
}
else if (oai_settings.electronhub_model.includes('jamba')) {
return jambaTokenizer;
}
else if (oai_settings.electronhub_model.includes('deepseek') || oai_settings.electronhub_model.includes('sonar-reasoning') || oai_settings.electronhub_model.includes('r1')) {
return deepseekTokenizer;
}
else if (oai_settings.electronhub_model.includes('qwen')) {
return qwen2Tokenizer;
}
else if (oai_settings.electronhub_model.includes('gemma')) {
return gemmaTokenizer;
}
else if (oai_settings.electronhub_model.includes('mistral')) {
return mistralTokenizer;
}
else if (oai_settings.electronhub_model.includes('yi')) {
return yiTokenizer;
}
else if (oai_settings.electronhub_model.includes('llama3') || oai_settings.electronhub_model.includes('llama-3') || oai_settings.electronhub_model.startsWith('l3')) {
return llama3Tokenizer;
}
else if (oai_settings.electronhub_model.includes('llama')) {
return llamaTokenizer;
}
else if (oai_settings.electronhub_model.includes('command-a')) {
return commandATokenizer;
}
else if (oai_settings.electronhub_model.includes('command-r')) {
return commandRTokenizer;
}
else if (oai_settings.electronhub_model.includes('nemo')) {
return nemoTokenizer;
}
}
if (oai_settings.chat_completion_source == chat_completion_sources.COHERE) {
if (oai_settings.cohere_model.includes('command-a')) {
return commandATokenizer;
+3 -2
View File
@@ -526,12 +526,13 @@ export class ToolManager {
for (let choiceIndex = 0; choiceIndex < parsed.candidates.length; choiceIndex++) {
const candidate = parsed.candidates[choiceIndex];
if (Array.isArray(candidate?.content?.parts)) {
for (let toolCallIndex = 0; toolCallIndex < candidate.content.parts.length; toolCallIndex++) {
const part = candidate.content.parts[toolCallIndex];
for (let partIndex = 0; partIndex < candidate.content.parts.length; partIndex++) {
const part = candidate.content.parts[partIndex];
if (part.functionCall) {
if (!Array.isArray(toolCalls[choiceIndex])) {
toolCalls[choiceIndex] = [];
}
const toolCallIndex = toolCalls[choiceIndex].length;
if (toolCalls[choiceIndex][toolCallIndex] === undefined) {
toolCalls[choiceIndex][toolCallIndex] = {};
}
+69
View File
@@ -0,0 +1,69 @@
import { morphdom } from '../../lib.js';
/**
* Check if the current browser supports native segmentation function.
* @returns {boolean} True if the Segmenter is supported by the current browser.
*/
export function isSegmenterSupported() {
return typeof Intl.Segmenter === 'function';
}
/**
* Segment text in the given HTML content using Intl.Segmenter.
* @param {HTMLElement} htmlElement Target HTML element
* @param {string} htmlContent HTML content to segment
* @param {'word'|'grapheme'|'sentence'} [granularity='word'] Text split granularity
*/
export function segmentTextInElement(htmlElement, htmlContent, granularity = 'word') {
htmlElement.innerHTML = htmlContent;
if (!isSegmenterSupported()) {
return;
}
// TODO: Support more locales, make granularity configurable.
const segmenter = new Intl.Segmenter('en-US', { granularity });
const textNodes = [];
const walker = document.createTreeWalker(htmlElement, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const textNode = /** @type {Text} */ (walker.currentNode);
// Skip ancestors of code/pre
if (textNode.parentElement && textNode.parentElement.closest('pre, code')) {
continue;
}
// Skip text nodes that are empty or only whitespace
if (/^\s*$/.test(textNode.data)) {
continue;
}
textNodes.push(textNode);
}
// Split every text node into segments using spans
for (const textNode of textNodes) {
const fragment = document.createDocumentFragment();
const segments = segmenter.segment(textNode.data);
for (const segment of segments) {
// TODO: Apply a different class for different segment length/content?
// For now, just use a single class for all segments.
const span = document.createElement('span');
span.innerText = segment.segment;
span.className = 'text_segment';
fragment.appendChild(span);
}
textNode.replaceWith(fragment);
}
}
/**
* Apply stream fade-in effect to the given message text element by morphing its content.
* @param {HTMLElement} messageTextElement Message text element
* @param {string} htmlContent New HTML content to apply
*/
export function applyStreamFadeIn(messageTextElement, htmlContent) {
const targetElement = /** @type {HTMLElement} */ (messageTextElement.cloneNode());
segmentTextInElement(targetElement, htmlContent);
morphdom(messageTextElement, targetElement);
}
+132 -4
View File
@@ -3,10 +3,11 @@ import {
DOMPurify,
Readability,
isProbablyReaderable,
lodash,
} from '../lib.js';
import { getContext } from './extensions.js';
import { characters, getRequestHeaders, this_chid, user_avatar } from '../script.js';
import { characters, getRequestHeaders, processDroppedFiles, this_chid, user_avatar } from '../script.js';
import { isMobile } from './RossAscends-mods.js';
import { collapseNewlines, power_user } from './power-user.js';
import { debounce_timeout } from './constants.js';
@@ -15,6 +16,10 @@ import { SlashCommandClosure } from './slash-commands/SlashCommandClosure.js';
import { getTagsList } from './tags.js';
import { groups, selected_group } from './group-chats.js';
import { getCurrentLocale, t } from './i18n.js';
import { importWorldInfo } from './world-info.js';
export const shiftUpByOne = (e, i, a) => a[i] = e + 1;
export const shiftDownByOne = (e, i, a) => a[i] = e - 1;
/**
* Pagination status string template.
@@ -25,6 +30,8 @@ export const PAGINATION_TEMPLATE = '<%= rangeStart %>-<%= rangeEnd %> .. <%= tot
export const localizePagination = function(container) {
container.find('[title="Next page"]').attr('title', t`Next page`);
container.find('[title="Previous page"]').attr('title', t`Previous page`);
container.find('[title="First page"]').attr('title', t`First page`);
container.find('[title="Last page"]').attr('title', t`Last page`);
};
/**
@@ -284,6 +291,15 @@ export function removeFromArray(array, item) {
return true;
}
/**
* Normalizes an array by removing duplicates, trimming strings, and filtering out empty values.
* @param {any[]} arr - The array to normalize.
* @returns {any[]} The normalized array.
*/
export function normalizeArray(arr) {
return [...new Set((arr ?? []).map(s => typeof s === 'string' ? s.trim() : s).filter(Boolean))];
}
/**
* Checks if a string only contains digits.
* @param {string} str The string to check.
@@ -616,7 +632,7 @@ export function isElementInViewport(el) {
/**
* Returns a name that is unique among the names that exist.
* @param {string} name The name to check.
* @param {{ (y: any): boolean; }} exists Function to check if name exists.
* @param {{ (name: string): boolean; }} exists Function to check if name exists.
* @returns {string} A unique name.
*/
export function getUniqueName(name, exists) {
@@ -1633,13 +1649,18 @@ export function createThumbnail(dataUrl, maxWidth = null, maxHeight = null, type
* @param {{ (): boolean; }} condition The condition to wait for.
* @param {number} [timeout=1000] The timeout in milliseconds.
* @param {number} [interval=100] The interval in milliseconds.
* @param {object} [options] Options object
* @param {boolean} [options.rejectOnTimeout=true] Whether to reject the promise on timeout or resolve it.
* @returns {Promise<void>} A promise that resolves when the condition is true.
*/
export async function waitUntilCondition(condition, timeout = 1000, interval = 100) {
export async function waitUntilCondition(condition, timeout = 1000, interval = 100, options = {}) {
const { rejectOnTimeout = true } = options;
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
clearInterval(intervalId);
reject(new Error('Timed out waiting for condition to be true'));
const timeoutFn = rejectOnTimeout ? reject : resolve;
timeoutFn(new Error('Timed out waiting for condition to be true'));
}, timeout);
const intervalId = setInterval(() => {
@@ -2560,3 +2581,110 @@ export function textValueMatcher(params, data) {
export function versionCompare(srcVersion, minVersion) {
return (srcVersion || '0.0.0').localeCompare(minVersion, undefined, { numeric: true, sensitivity: 'base' }) > -1;
}
/**
* Sets up the scroll-to-top button functionality.
* @param {object} params Parameters object
* @param {string} params.scrollContainerId Scrollable container element ID
* @param {string} params.buttonId Button element ID
* @param {string} params.drawerId Drawer element ID
* @param {number} [params.visibilityThreshold] Scroll position (px) to show the button (default: 300)
* @returns {() => void} Cleanup function to remove event listeners
*/
export function setupScrollToTop({ scrollContainerId, buttonId, drawerId, visibilityThreshold = 300 }) {
const scrollContainer = document.getElementById(scrollContainerId);
const btn = document.getElementById(buttonId);
const drawer = document.getElementById(drawerId);
if (!btn || !drawer) {
// Not fatal; the drawer or button may not exist in some builds. Use debug level.
console.debug('Scroll-to-top: button or drawer not found during setup.');
return () => { /* noop cleanup */ };
}
if (!scrollContainer) {
console.debug('Scroll-to-top: scroll container not found during setup.');
return () => { /* noop cleanup */ };
}
const updateButtonVisibility = () => btn.classList.toggle('visible', scrollContainer.scrollTop > visibilityThreshold);
const updateButtonVisibilityThrottled = lodash.throttle(updateButtonVisibility, debounce_timeout.standard, { leading: true, trailing: true });
const onScroll = () => updateButtonVisibilityThrottled();
scrollContainer.addEventListener('scroll', onScroll, { passive: true });
// Scroll to top on click (button semantics provide keyboard activation natively)
const onActivate = (/** @type {MouseEvent} */ e) => {
e.preventDefault();
e.stopPropagation();
const userPrefersReduced = power_user.reduced_motion;
scrollContainer.scrollTo({ top: 0, behavior: userPrefersReduced ? 'auto' : 'smooth' });
};
btn.addEventListener('click', onActivate);
// Initial state check
updateButtonVisibility();
// Return cleanup function for caller to hold and invoke when appropriate
return () => {
scrollContainer.removeEventListener('scroll', onScroll);
btn.removeEventListener('click', onActivate);
};
}
/**
* Imports content from an external URL.
* @param {string} url URL or UUID of the content to import.
* @param {Object} [options={}] Options object.
* @param {string|null} [options.preserveFileName=null] Optional file name to use for the imported content.
* @returns {Promise<void>} A promise that resolves when the import is complete.
*/
export async function importFromExternalUrl(url, { preserveFileName = null } = {}) {
let request;
if (isValidUrl(url)) {
console.debug('Custom content import started for URL: ', url);
request = await fetch('/api/content/importURL', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ url }),
});
} else {
console.debug('Custom content import started for Char UUID: ', url);
request = await fetch('/api/content/importUUID', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ url }),
});
}
if (!request.ok) {
toastr.info(request.statusText, 'Custom content import failed');
console.error('Custom content import failed', request.status, request.statusText);
return;
}
const data = await request.blob();
const customContentType = request.headers.get('X-Custom-Content-Type');
let fileName = request.headers.get('Content-Disposition').split('filename=')[1].replace(/"/g, '');
const file = new File([data], fileName, { type: data.type });
const extraData = new Map();
if (preserveFileName) {
fileName = preserveFileName;
extraData.set(file, preserveFileName);
}
switch (customContentType) {
case 'character':
await processDroppedFiles([file], extraData);
break;
case 'lorebook':
await importWorldInfo(file);
break;
default:
toastr.warning('Unknown content type');
console.error('Unknown content type', customContentType);
break;
}
}
+328 -68
View File
@@ -1,7 +1,7 @@
import { Fuse } from '../lib.js';
import { saveSettings, substituteParams, getRequestHeaders, chat_metadata, this_chid, characters, saveCharacterDebounced, menu_type, eventSource, event_types, getExtensionPromptByName, saveMetadata, getCurrentChatId, extension_prompt_roles } from '../script.js';
import { download, debounce, initScrollHeight, resetScrollHeight, parseJsonFile, extractDataFromPng, getFileBuffer, getCharaFilename, getSortableDelay, escapeRegex, PAGINATION_TEMPLATE, navigation_option, waitUntilCondition, isTrueBoolean, setValueByPath, flashHighlight, select2ModifyOptions, getSelect2OptionId, dynamicSelect2DataViaAjax, highlightRegex, select2ChoiceClickSubscribe, isFalseBoolean, getSanitizedFilename, checkOverwriteExistingData, getStringHash, parseStringArray, cancelDebounce, findChar, onlyUnique, equalsIgnoreCaseAndAccents } from './utils.js';
import { saveSettings, substituteParams, getRequestHeaders, chat_metadata, this_chid, characters, saveCharacterDebounced, menu_type, eventSource, event_types, getExtensionPromptByName, saveMetadata, getCurrentChatId, extension_prompt_roles, create_save, createOrEditCharacter, name1 } from '../script.js';
import { download, debounce, initScrollHeight, resetScrollHeight, parseJsonFile, extractDataFromPng, getFileBuffer, getCharaFilename, getSortableDelay, escapeRegex, PAGINATION_TEMPLATE, navigation_option, waitUntilCondition, isTrueBoolean, setValueByPath, flashHighlight, select2ModifyOptions, getSelect2OptionId, dynamicSelect2DataViaAjax, highlightRegex, select2ChoiceClickSubscribe, isFalseBoolean, getSanitizedFilename, checkOverwriteExistingData, getStringHash, parseStringArray, cancelDebounce, findChar, onlyUnique, equalsIgnoreCaseAndAccents, uuidv4, normalizeArray, getUniqueName } from './utils.js';
import { extension_settings, getContext } from './extensions.js';
import { NOTE_MODULE_NAME, metadata_keys, shouldWIAddPrompt } from './authors-note.js';
import { isMobile } from './RossAscends-mods.js';
@@ -22,6 +22,7 @@ import { StructuredCloneMap } from './util/StructuredCloneMap.js';
import { renderTemplateAsync } from './templates.js';
import { t } from './i18n.js';
import { accountStorage } from './util/AccountStorage.js';
import { getOrCreatePersonaDescriptor, setPersonaDescription, user_avatar } from './personas.js';
export const world_info_insertion_strategy = {
evenly: 0,
@@ -156,6 +157,7 @@ const KNOWN_DECORATORS = ['@@activate', '@@dont_activate'];
* @property {Array} worldInfoDepth - Array of depth entries
* @property {Array} anBefore - Array of entries before Author's Note
* @property {Array} anAfter - Array of entries after Author's Note
* @property {{[key: string]: string[]}} outletEntries - Array of entries to be added to an outlet
*/
/**
@@ -166,6 +168,7 @@ const KNOWN_DECORATORS = ['@@activate', '@@dont_activate'];
* @property {any[]} WIDepthEntries The depth entries.
* @property {any[]} ANBeforeEntries The entries before Author's Note.
* @property {any[]} ANAfterEntries The entries after Author's Note.
* @property {{[key: string]: string[]}} outletEntries - Array of entries to be added to an outlet
* @property {Set<any>} allActivatedEntries All entries.
*/
@@ -817,6 +820,7 @@ export const world_info_position = {
atDepth: 4,
EMTop: 5,
EMBottom: 6,
outlet: 7,
};
export const wi_anchor_position = {
@@ -866,6 +870,7 @@ export async function getWorldInfoPrompt(chat, maxContext, isDryRun, globalScanD
worldInfoDepth: activatedWorldInfo.WIDepthEntries ?? [],
anBefore: activatedWorldInfo.ANBeforeEntries ?? [],
anAfter: activatedWorldInfo.ANAfterEntries ?? [],
outletEntries: activatedWorldInfo.outletEntries ?? {},
};
}
@@ -1037,39 +1042,69 @@ function registerWorldInfoSlashCommands() {
/**
* Gets the name of the persona-bound lorebook.
* @returns {string} The name of the persona-bound lorebook
* @param {import('./slash-commands/SlashCommand.js').NamedArguments} args Named arguments
* @param {string} _unnamedArg not used
* @returns {Promise<string>} The name of the persona-bound lorebook
*/
function getPersonaBookCallback() {
return power_user.persona_description_lorebook || '';
async function getPersonaBookCallback({ name, create }, _unnamedArg) {
let bookName = power_user.persona_description_lorebook || '';
if (bookName) {
return bookName;
}
if (isTrueBoolean(String(create))) {
const newName = await createWorldWithName(name, `Persona Book ${name1}`.replace(/[^a-z0-9 -]/gi, '_').replace(/_{2,}/g, '_').substring(0, 64));
power_user.persona_description_lorebook = newName;
setPersonaDescription();
saveSettingsDebounced();
return newName;
}
return '';
}
/**
* Gets the name of the character-bound lorebook.
* @param {import('./slash-commands/SlashCommand.js').NamedArguments} args Named arguments
* @param {string} name Character name
* @returns {string} The name of the character-bound lorebook, a JSON string of the character's lorebooks, or an empty string
* @param {string} characterIdentifier Character name
* @returns {Promise<string>} The name of the character-bound lorebook, a JSON string of the character's lorebooks, or an empty string
*/
function getCharBookCallback({ type }, name) {
async function getCharBookCallback({ type, name, create }, characterIdentifier) {
const context = getContext();
if (context.groupId && !name) throw new Error('This command is not available in groups without providing a character name');
if (context.groupId && !characterIdentifier) throw new Error('This command is not available in groups without providing a character name');
type = String(type ?? '').trim().toLowerCase() || 'primary';
name = String(name ?? '') || context.characters[context.characterId]?.avatar || null;
const character = findChar({ name });
characterIdentifier = String(characterIdentifier ?? '') || context.characters[context.characterId]?.avatar || null;
const character = findChar({ name: characterIdentifier });
if (!character) {
toastr.error(t`Character not found.`);
return '';
}
const books = [];
if (type === 'all' || type === 'primary') {
books.push(character.data?.extensions?.world);
if (type === 'all' || type === 'primary' && character.data?.extensions?.world) {
books.push(character.data.extensions.world);
}
if (type === 'all' || type === 'additional') {
const fileName = getCharaFilename(context.characters.indexOf(character));
const extraCharLore = world_info.charLore?.find((e) => e.name === fileName);
if (extraCharLore && Array.isArray(extraCharLore.extraBooks)) {
books.push(...extraCharLore.extraBooks);
books.push(...extraCharLore.extraBooks.filter(onlyUnique).filter(Boolean));
}
}
if (isTrueBoolean(String(create)) && books.length === 0) {
const newName = await createWorldWithName(name, `Character Book ${character.name}`.replace(/[^a-z0-9 -]/gi, '_').replace(/_{2,}/g, '_').substring(0, 64));
// Also assign the book now - additional if requested, otherwise as primary
if (type === 'additional') {
await charUpdateAddAuxWorld(character.avatar, newName);
}
else {
await charUpdatePrimaryWorld(newName);
}
// Refresh UI, if needed
setWorldInfoButtonClass(this_chid);
books.push(newName);
}
return type === 'primary' ? (books[0] ?? '') : JSON.stringify(books.filter(onlyUnique).filter(Boolean));
}
@@ -1090,10 +1125,23 @@ function registerWorldInfoSlashCommands() {
return chat_metadata[METADATA_KEY];
}
const name = (() => {
if (isFalseBoolean(String(args.create))) {
return '';
}
const name = await createWorldWithName(args.name, `Chat Book ${getCurrentChatId()}`.replace(/[^a-z0-9 -]/gi, '_').replace(/_{2,}/g, '_').substring(0, 64));
chat_metadata[METADATA_KEY] = name;
await saveMetadata();
$('.chat_lorebook_button').addClass('world_set');
return name;
}
async function createWorldWithName(possibleName = undefined, fallbackName = undefined) {
let newName = (() => {
// Use the provided name if it's not in use
if (typeof args.name === 'string') {
const name = String(args.name);
if (typeof possibleName === 'string') {
const name = String(possibleName);
if (world_names.includes(name)) {
throw new Error('This World Info file name is already in use');
}
@@ -1101,14 +1149,14 @@ function registerWorldInfoSlashCommands() {
}
// Replace non-alphanumeric characters with underscores, cut to 64 characters
return `Chat Book ${getCurrentChatId()}`.replace(/[^a-z0-9]/gi, '_').replace(/_{2,}/g, '_').substring(0, 64);
return fallbackName ?? `Lorebook (${uuidv4()})`;
})();
await createNewWorldInfo(name);
chat_metadata[METADATA_KEY] = name;
await saveMetadata();
$('.chat_lorebook_button').addClass('world_set');
return name;
// Make sure the name is unique
newName = getUniqueName(newName, world_names.includes.bind(world_names));
await createNewWorldInfo(newName);
return newName;
}
async function findBookEntryCallback(args, value) {
@@ -1545,6 +1593,15 @@ function registerWorldInfoSlashCommands() {
isRequired: false,
acceptsMultiple: false,
}),
SlashCommandNamedArgument.fromProps({
name: 'create',
description: 'create a new lorebook if it doesn\'t exist',
typeList: [ARGUMENT_TYPE.BOOLEAN],
isRequired: false,
acceptsMultiple: false,
enumList: commonEnumProviders.boolean('trueFalse')(),
defaultValue: 'true',
}),
],
aliases: ['getchatlore', 'getchatwi'],
}));
@@ -1559,6 +1616,25 @@ function registerWorldInfoSlashCommands() {
name: 'getpersonabook',
callback: getPersonaBookCallback,
returns: 'lorebook name',
namedArgumentList: [
SlashCommandNamedArgument.fromProps({
name: 'name',
description: 'lorebook name if creating a new one, will be auto-generated otherwise',
typeList: [ARGUMENT_TYPE.STRING],
isRequired: false,
acceptsMultiple: false,
}),
SlashCommandNamedArgument.fromProps({
name: 'create',
description: 'create a new lorebook if it doesn\'t exist',
typeList: [ARGUMENT_TYPE.BOOLEAN],
isRequired: false,
acceptsMultiple: false,
enumList: commonEnumProviders.boolean('trueFalse')(),
defaultValue: 'false',
}),
],
helpString: 'Get a name of the current persona-bound lorebook and pass it down the pipe. Returns empty string if persona lorebook is not set.',
aliases: ['getpersonalore', 'getpersonawi'],
}));
@@ -1574,6 +1650,22 @@ function registerWorldInfoSlashCommands() {
enumList: ['primary', 'additional', 'all'],
defaultValue: 'primary',
}),
SlashCommandNamedArgument.fromProps({
name: 'name',
description: 'lorebook name if creating a new one, will be auto-generated otherwise',
typeList: [ARGUMENT_TYPE.STRING],
isRequired: false,
acceptsMultiple: false,
}),
SlashCommandNamedArgument.fromProps({
name: 'create',
description: 'create a new lorebook if it doesn\'t exist',
typeList: [ARGUMENT_TYPE.BOOLEAN],
isRequired: false,
acceptsMultiple: false,
enumList: commonEnumProviders.boolean('trueFalse')(),
defaultValue: 'false',
}),
],
unnamedArgumentList: [
SlashCommandArgument.fromProps({
@@ -3425,6 +3517,19 @@ export async function getWorldEntry(name, data, entry) {
contentInput.val(entry.content).trigger('input', { skipCount: true, noSave: true });
editTemplate.find('.editor_maximize').attr('data-for', contentInputId);
// Outlet name
const outletNameInput = editTemplate.find('input[name="outletName"]');
outletNameInput.data('uid', entry.uid);
outletNameInput.on('input', async function (_, { noSave = false } = {}) {
const uid = $(this).data('uid');
const value = $(this).val();
data.entries[uid].outletName = value;
setWIOriginalDataValue(data, uid, 'extensions.outlet_name', data.entries[uid].outletName);
!noSave && await saveWorldInfo(name, data);
});
outletNameInput.val(entry.outletName ?? '').trigger('input', { noSave: true });
setTimeout(() => createEntryInputAutocomplete(outletNameInput, getOutletNameCallback(data), { allowMultiple: true }), 1);
// Scan depth
const scanDepthInput = editTemplate.find('input[name="scanDepth"]');
scanDepthInput.data('uid', entry.uid);
@@ -3597,63 +3702,105 @@ export async function getWorldEntry(name, data, entry) {
return headerTemplate;
}
/**
* Builds a jQuery UI autocomplete callback: (control, request, response) => void
* @param {object} [opt={}] - Optional arguments
* @param {{entries: Record<string, any>}} [opt.data] - Your WI data
* @param {(entry:any)=>string|string[]|null|undefined} [opt.collectValues] - Extract values from one entry
* @param {() => Iterable<string>} [opt.includeExtras] - Optional global extras to include
* @param {(ctx:{result:string[], control:JQuery, input:any, haystack:string[]})=>string[]} [opt.postFilter] - Optional final filter step (for special rules like your "group" de-dupe logic)
*/
function buildAutocompleteCallback({ data, collectValues, includeExtras = () => [], postFilter } = {}) {
return function (control, input, output) {
const uid = $(control).data('uid');
// Collect unique values from all *other* entries
const values = new Set();
for (const entry of Object.values(data.entries ?? {})) {
if (entry?.uid == uid) continue;
const raw = collectValues(entry);
if (raw == null) continue;
const arr = Array.isArray(raw) ? raw : [raw];
for (const v of arr) {
const s = String(v).trim();
if (s) values.add(s);
}
}
// Add optional global extras
for (const v of includeExtras()) {
const s = String(v).trim();
if (s) values.add(s);
}
// Sort stable & locale-aware
const haystack = Array.from(values).sort((a, b) => a.localeCompare(b));
// Case-insensitive contains
const needle = String(input.term ?? '').toLowerCase();
let result = haystack.filter(x => x.toLowerCase().includes(needle));
// Optional final-pass semantics
if (postFilter) {
result = postFilter({ result, control: $(control), input, haystack });
}
output(result);
};
}
/**
* Splits a string into an array of strings, separated by commas and trimmed
* @param {string} s - The string to split
* @returns {string[]} An array of strings, separated by commas and trimmed
*/
const splitCsv = s => String(s ?? '').split(/,\s*/).filter(Boolean);
/**
* Get the inclusion groups for the autocomplete.
* @param {any} data WI data
* @returns {(input: any, output: any) => any} Callback function for the autocomplete
*/
function getInclusionGroupCallback(data) {
return function (control, input, output) {
const uid = $(control).data('uid');
const thisGroups = String($(control).val()).split(/,\s*/).filter(x => x).map(x => x.toLowerCase());
const groups = new Set();
for (const entry of Object.values(data.entries)) {
// Skip the groups of this entry, because auto-complete should only suggest the ones that are already available on other entries
if (entry.uid == uid) continue;
if (entry.group) {
entry.group.split(/,\s*/).filter(x => x).forEach(x => groups.add(x));
}
}
return buildAutocompleteCallback({
data,
collectValues: entry => entry.group ? splitCsv(entry.group) : [],
postFilter: ({ result, control, input, haystack }) => {
const thisGroups = splitCsv(String($(control).val()));
const needle = String(input.term ?? '').toLowerCase();
const hasExactMatch = haystack.some(x => x.toLowerCase() === needle);
const haystack = Array.from(groups);
haystack.sort((a, b) => a.localeCompare(b));
const needle = input.term.toLowerCase();
const hasExactMatch = haystack.findIndex(x => x.toLowerCase() == needle) !== -1;
const result = haystack.filter(x => x.toLowerCase().includes(needle) && (!thisGroups.includes(x) || hasExactMatch && thisGroups.filter(g => g == x).length == 1));
output(result);
};
// include suggestion if it contains the needle AND
// (not already present OR (exact match typed && appears only once))
return result.filter(x =>
!thisGroups.includes(x) ||
(hasExactMatch && thisGroups.filter(g => g === x).length === 1),
);
},
});
}
function getAutomationIdCallback(data) {
return function (control, input, output) {
const uid = $(control).data('uid');
const ids = new Set();
for (const entry of Object.values(data.entries)) {
// Skip automation id of this entry, because auto-complete should only suggest the ones that are already available on other entries
if (entry.uid == uid) continue;
if (entry.automationId) {
ids.add(String(entry.automationId));
}
}
return buildAutocompleteCallback({
data,
collectValues: entry => entry.automationId != null ? [String(entry.automationId)] : [],
includeExtras: () =>
('quickReplyApi' in globalThis && globalThis.quickReplyApi?.listAutomationIds)
? globalThis.quickReplyApi.listAutomationIds()
: [],
});
}
if ('quickReplyApi' in globalThis) {
for (const automationId of globalThis.quickReplyApi.listAutomationIds()) {
ids.add(String(automationId));
}
}
const haystack = Array.from(ids);
haystack.sort((a, b) => a.localeCompare(b));
const needle = input.term.toLowerCase();
const result = haystack.filter(x => x.toLowerCase().includes(needle));
output(result);
};
function getOutletNameCallback(data) {
return buildAutocompleteCallback({
data,
collectValues: entry => entry.position === world_info_position.outlet && entry.outletName ? [entry.outletName] : [],
});
}
/**
* Create an autocomplete for the inclusion group.
* Create an autocomplete for an input element.
* @param {JQuery<HTMLElement>} input - Input element to attach the autocomplete to
* @param {(control: JQuery<HTMLElement>, input: any, output: any) => any} callback - Source data callbacks
* @param {object} [options={}] - Optional arguments
@@ -3770,6 +3917,7 @@ export const newWorldInfoEntryDefinition = {
probability: { default: 100, type: 'number' },
useProbability: { default: true, type: 'boolean' },
depth: { default: DEFAULT_DEPTH, type: 'number' },
outletName: { default: '', type: 'string' },
group: { default: '', type: 'string' },
groupOverride: { default: false, type: 'boolean' },
groupWeight: { default: DEFAULT_WEIGHT, type: 'number' },
@@ -3935,6 +4083,16 @@ export async function deleteWorldInfo(worldInfoName) {
}
}
if (power_user.persona_description_lorebook === worldInfoName) {
power_user.persona_description_lorebook = '';
if (power_user.personas[user_avatar]) {
const object = getOrCreatePersonaDescriptor();
object.lorebook = '';
}
$('#persona_lore_button').toggleClass('world_set', false);
saveSettingsDebounced();
}
return true;
}
@@ -4281,7 +4439,7 @@ export async function checkWorldInfo(chat, maxContext, isDryRun, globalScanData
timedEffects.checkTimedEffects();
if (sortedEntries.length === 0) {
return { worldInfoBefore: '', worldInfoAfter: '', WIDepthEntries: [], EMEntries: [], ANBeforeEntries: [], ANAfterEntries: [], allActivatedEntries: new Set() };
return { worldInfoBefore: '', worldInfoAfter: '', WIDepthEntries: [], EMEntries: [], ANBeforeEntries: [], ANAfterEntries: [], outletEntries: {}, allActivatedEntries: new Set() };
}
/** @type {number[]} Represents the delay levels for entries that are delayed until recursion */
@@ -4682,6 +4840,8 @@ export async function checkWorldInfo(chat, maxContext, isDryRun, globalScanData
const ANTopEntries = [];
const ANBottomEntries = [];
const WIDepthEntries = [];
/** @type {{[key: string]: string[]}} */
const WIOutletEntries = {};
// Appends from insertion order 999 to 1. Use unshift for this purpose
// TODO (kingbri): Change to use WI Anchor positioning instead of separate top/bottom arrays
@@ -4730,6 +4890,18 @@ export async function checkWorldInfo(chat, maxContext, isDryRun, globalScanData
}
break;
}
case world_info_position.outlet: {
if (!entry.outletName) {
console.warn(`[WI] Entry ${entry.uid} has position 'outlet' but no outlet name. Skipping.`);
break;
}
if (Array.isArray(WIOutletEntries[entry.outletName])) {
WIOutletEntries[entry.outletName].push(content);
} else {
WIOutletEntries[entry.outletName] = [content];
}
break;
}
default:
break;
}
@@ -4751,7 +4923,7 @@ export async function checkWorldInfo(chat, maxContext, isDryRun, globalScanData
console.log(`[WI] ${isDryRun ? 'Hypothetically adding' : 'Adding'} ${allActivatedEntries.size} entries to prompt`, Array.from(allActivatedEntries.values()));
console.debug(`[WI] --- DONE${isDryRun ? ' (DRY RUN)' : ''} ---`);
return { worldInfoBefore, worldInfoAfter, EMEntries, WIDepthEntries, ANBeforeEntries: ANTopEntries, ANAfterEntries: ANBottomEntries, allActivatedEntries: new Set(allActivatedEntries.values()) };
return { worldInfoBefore, worldInfoAfter, EMEntries, WIDepthEntries, ANBeforeEntries: ANTopEntries, ANAfterEntries: ANBottomEntries, outletEntries: WIOutletEntries, allActivatedEntries: new Set(allActivatedEntries.values()) };
}
/**
@@ -4971,6 +5143,7 @@ function convertAgnaiMemoryBook(inputObj) {
displayIndex: index,
probability: 100,
useProbability: true,
outletName: '',
group: '',
groupOverride: false,
groupWeight: DEFAULT_WEIGHT,
@@ -5015,6 +5188,7 @@ function convertRisuLorebook(inputObj) {
displayIndex: index,
probability: entry.activationPercent ?? 100,
useProbability: entry.activationPercent ?? true,
outletName: '',
group: '',
groupOverride: false,
groupWeight: DEFAULT_WEIGHT,
@@ -5064,6 +5238,7 @@ function convertNovelLorebook(inputObj) {
displayIndex: index,
probability: 100,
useProbability: true,
outletName: '',
group: '',
groupOverride: false,
groupWeight: DEFAULT_WEIGHT,
@@ -5114,6 +5289,7 @@ export function convertCharacterBook(characterBook) {
useProbability: entry.extensions?.useProbability ?? true,
depth: entry.extensions?.depth ?? DEFAULT_DEPTH,
selectiveLogic: entry.extensions?.selectiveLogic ?? world_info_logic.AND_ANY,
outletName: entry.extensions?.outlet_name ?? '',
group: entry.extensions?.group ?? '',
groupOverride: entry.extensions?.group_override ?? false,
groupWeight: entry.extensions?.group_weight ?? DEFAULT_WEIGHT,
@@ -5558,6 +5734,90 @@ export async function moveWorldInfoEntry(sourceName, targetName, uid, { deleteOr
}
}
/**
* Updates the primary world info linked to a character.
* Can also unset it to null.
* @param {string} name - The name of the world info to link to the character.
*/
export async function charUpdatePrimaryWorld(name) {
const previousValue = $('#character_world').val();
$('#character_world').val(name);
console.debug('Character world selected:', name);
if (menu_type == 'create') {
create_save.world = name;
return;
}
if (previousValue && !name) {
try {
// Dirty hack to remove embedded lorebook from character JSON data.
const data = JSON.parse(String($('#character_json_data').val()));
if (data?.data?.character_book) {
data.data.character_book = undefined;
}
$('#character_json_data').val(JSON.stringify(data));
toastr.info(t`Embedded lorebook will be removed from this character.`);
} catch {
console.error('Failed to parse character JSON data.');
}
}
await createOrEditCharacter();
setWorldInfoButtonClass(undefined, !!name);
}
/**
* Adds one or more auxiliary world books to a character.
* @param {string} characterKey - The key of the character to add auxiliary world books to
* @param {string|string[]} nameOrNames - The name or names of the auxiliary world books to add
*/
export async function charUpdateAddAuxWorld(characterKey, nameOrNames) {
const fileName = getCharaFilename(null, { manualAvatarKey: characterKey });
const toAdd = Array.isArray(nameOrNames) ? nameOrNames : [nameOrNames];
updateAuxBooks(fileName, curr => [...curr, ...toAdd]);
}
/**
* Replaces the entire list of auxiliary world books for a character.
* @param {string} fileName - The filename of the character to update
* @param {string[]} books - The new list of auxiliary world books to replace the existing list with
*/
export function charSetAuxWorlds(fileName, books) {
updateAuxBooks(fileName, _ => Array.isArray(books) ? books : []);
}
function updateAuxBooks(fileName, computeNext) {
if (!fileName) return;
if (menu_type === 'create') {
const current = create_save.extra_books ?? [];
create_save.extra_books = normalizeArray(computeNext(current));
return; // no debounced save in create flow
}
const charLore = world_info.charLore ?? [];
const idx = charLore.findIndex(e => e.name === fileName);
const current = idx !== -1 ? (charLore[idx].extraBooks ?? []) : [];
const next = normalizeArray(computeNext(current));
if (next.length === 0) {
if (idx !== -1) charLore.splice(idx, 1);
} else if (idx === -1) {
charLore.push({ name: fileName, extraBooks: next });
} else {
charLore[idx] = { ...charLore[idx], extraBooks: next };
}
Object.assign(world_info, { charLore });
saveSettingsDebounced();
}
export function initWorldInfo() {
$('#world_info').on('mousedown change', async function (e) {
// If there's no world names, don't do anything
+27 -3
View File
@@ -133,6 +133,7 @@
* {
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-webkit-tap-highlight-color: transparent;
-moz-osx-font-smoothing: grayscale;
text-shadow: 0px 0px calc(var(--shadowWidth) * 1px) var(--SmartThemeShadowColor);
}
@@ -599,6 +600,14 @@ input[type='checkbox']:focus-visible {
max-height: var(--doc-height);
}
.mes_reasoning_details[data-state="thinking"] .mes_reasoning .text_segment,
.mes_text .text_segment {
animation-name: fade-in;
animation-timing-function: ease-in-out;
/* Not using variables for duration as they are zeroed when reduced motion is enabled */
animation-duration: 300ms;
}
.mes .mes_timer,
.mes .mesIDDisplay,
.mes .tokenCounterDisplay {
@@ -2923,6 +2932,10 @@ select option:not(:checked) {
color: var(--white70a);
}
select option[disabled]:not(:checked) {
color: var(--white30a);
}
/*#######################################################################*/
#rm_api_block {
@@ -2940,6 +2953,7 @@ select option:not(:checked) {
text-align: center;
}
.menu_button[disabled],
.menu_button.disabled {
filter: brightness(75%) grayscale(1);
opacity: 0.5;
@@ -3001,6 +3015,11 @@ select option:not(:checked) {
display: block;
}
/* Fix font size difference in API Connections dropdowns - Issue #4599 */
#custom_model_id {
font-size: calc(var(--mainFontSize) * 0.95);
}
.menu_button.api_button:hover {
background-color: var(--active);
}
@@ -3286,6 +3305,10 @@ input[type=search]:focus::-webkit-search-cancel-button {
position: relative;
}
#rm_group_top_bar:not(:has(#rm_group_activation_strategy option[value="0"]:checked)) label:has(#rm_group_allow_self_responses) {
display: none;
}
.group_member .queue_position:not(:empty)::before {
content: "#";
}
@@ -3675,8 +3698,8 @@ grammarly-extension {
min-width: calc(1.25em + 12px);
}
.menu_button:not(.disabled):hover,
.menu_button:not(.disabled).active {
.menu_button:not(.disabled):not([disabled]):hover,
.menu_button:not(.disabled):not([disabled]).active {
background-color: var(--white30a);
}
@@ -5740,7 +5763,8 @@ body:not(.movingUI) .drawer-content.maximized {
}
.paginationjs-pages ul li a {
padding: 0.05em 0.5em;
padding: 0.25em;
font-family: 'Font Awesome 6 Free';
text-decoration: none;
color: var(--SmartThemeBodyColor);
border: 1px solid var(--SmartThemeBorderColor);
+10
View File
@@ -124,6 +124,16 @@ const keyMigrationMap = [
migrate: () => void 0,
remove: true,
},
{
oldKey: 'autheliaAuth',
newKey: 'sso.autheliaAuth',
migrate: (value) => value,
},
{
oldKey: 'authentikAuth',
newKey: 'sso.authentikAuth',
migrate: (value) => value,
},
];
/**
+73 -26
View File
@@ -154,9 +154,9 @@ async function sendClaudeRequest(request, response) {
const useTools = Array.isArray(request.body.tools) && request.body.tools.length > 0;
const useSystemPrompt = Boolean(request.body.claude_use_sysprompt);
const convertedPrompt = convertClaudeMessages(request.body.messages, request.body.assistant_prefill, useSystemPrompt, useTools, getPromptNames(request));
const useThinking = /^claude-(3-7|opus-4|sonnet-4)/.test(request.body.model);
const useWebSearch = /^claude-(3-5|3-7|opus-4|sonnet-4)/.test(request.body.model) && Boolean(request.body.enable_web_search);
const isOpus41 = /^claude-opus-4-1/.test(request.body.model);
const useThinking = /^claude-(3-7|opus-4|sonnet-4|haiku-4-5)/.test(request.body.model);
const useWebSearch = /^claude-(3-5|3-7|opus-4|sonnet-4|haiku-4-5)/.test(request.body.model) && Boolean(request.body.enable_web_search);
const isLimitedSampling = /^claude-(opus-4-1|sonnet-4-5|haiku-4-5)/.test(request.body.model);
const cacheTTL = getConfigValue('claude.extendedTTL', false, 'boolean') ? '1h' : '5m';
let fixThinkingPrefill = false;
// Add custom stop sequences
@@ -226,7 +226,7 @@ async function sendClaudeRequest(request, response) {
betaHeaders.push('extended-cache-ttl-2025-04-11');
}
if (isOpus41) {
if (isLimitedSampling) {
if (requestBody.top_p < 1) {
delete requestBody.temperature;
} else {
@@ -377,24 +377,16 @@ async function sendMakerSuiteRequest(request, response) {
'gemini-2.0-flash-exp-image-generation',
'gemini-2.0-flash-preview-image-generation',
'gemini-2.5-flash-image-preview',
'gemini-2.5-flash-image',
];
// These models do not support setting the threshold to OFF at all.
const blockNoneModels = [
'gemini-1.5-pro-001',
'gemini-1.5-flash-001',
'gemini-1.5-flash-8b-exp-0827',
'gemini-1.5-flash-8b-exp-0924',
];
const isThinkingConfigModel = m => /^gemini-2.5-(flash|pro)/.test(m) && !/-image-preview$/.test(m);
const isThinkingConfigModel = m => /^gemini-2.5-(flash|pro)/.test(m) && !/-image(-preview)?$/.test(m);
const noSearchModels = [
'gemini-2.0-flash-lite',
'gemini-2.0-flash-lite-001',
'gemini-2.0-flash-lite-preview-02-05',
'gemini-1.5-flash-8b-exp-0924',
'gemini-1.5-flash-8b-exp-0827',
'gemini-robotics-er-1.5-preview',
];
// #endregion
@@ -413,15 +405,8 @@ async function sendMakerSuiteRequest(request, response) {
const prompt = convertGooglePrompt(request.body.messages, model, useSystemPrompt, getPromptNames(request));
let safetySettings = GEMINI_SAFETY;
if (blockNoneModels.includes(model)) {
safetySettings = GEMINI_SAFETY.map(setting => ({ ...setting, threshold: 'BLOCK_NONE' }));
}
if (enableWebSearch && !enableImageModality && !isGemma && !isLearnLM && !noSearchModels.includes(model)) {
const searchTool = model.includes('1.5')
? ({ google_search_retrieval: {} })
: ({ google_search: {} });
tools.push(searchTool);
tools.push({ google_search: {} });
}
if (Array.isArray(request.body.tools) && request.body.tools.length > 0 && !enableImageModality && !isGemma) {
@@ -1012,7 +997,7 @@ async function sendXaiRequest(request, response) {
bodyParams['stop'] = request.body.stop;
}
if (request.body.reasoning_effort && ['grok-3-mini-beta', 'grok-3-mini-fast-beta'].includes(request.body.model)) {
if (request.body.reasoning_effort) {
bodyParams['reasoning_effort'] = request.body.reasoning_effort === 'high' ? 'high' : 'low';
}
@@ -1255,6 +1240,7 @@ async function sendElectronHubRequest(request, response) {
'frequency_penalty': request.body.frequency_penalty,
'top_p': request.body.top_p,
'top_k': request.body.top_k,
'logit_bias': request.body.logit_bias,
'seed': request.body.seed,
...bodyParams,
};
@@ -1848,9 +1834,9 @@ router.post('/generate', function (request, response) {
}
const cachingAtDepth = getConfigValue('claude.cachingAtDepth', -1, 'number');
const isClaude3or4 = /anthropic\/claude-(3|opus-4|sonnet-4)/.test(request.body.model);
const isClaude3or4 = /anthropic\/claude-(3|opus-4|sonnet-4|haiku-4)/.test(request.body.model);
const cacheTTL = getConfigValue('claude.extendedTTL', false, 'boolean') ? '1h' : '5m';
if (Number.isInteger(cachingAtDepth) && cachingAtDepth >= 0 && isClaude3or4) {
if (Array.isArray(request.body.messages) && Number.isInteger(cachingAtDepth) && cachingAtDepth >= 0 && isClaude3or4) {
cachingAtDepthForOpenRouterClaude(request.body.messages, cachingAtDepth, cacheTTL);
}
@@ -2209,4 +2195,65 @@ multimodalModels.post('/electronhub', async (_req, res) => {
}
});
multimodalModels.post('/mistral', async (req, res) => {
try {
const key = readSecret(req.user.directories, SECRET_KEYS.MISTRALAI);
if (!key) {
return res.json([]);
}
const response = await fetch('https://api.mistral.ai/v1/models', {
headers: {
'Authorization': `Bearer ${key}`,
},
});
if (!response.ok) {
return res.json([]);
}
/** @type {any} */
const data = await response.json();
const multimodalModels = data.data.filter(m => m.capabilities?.vision).map(m => m.id);
return res.json(multimodalModels);
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
});
multimodalModels.post('/xai', async (req, res) => {
try {
const key = readSecret(req.user.directories, SECRET_KEYS.XAI);
if (!key) {
return res.json([]);
}
// xAI's /models endpoint doesn't return modality info, so we must use /language-models instead
const response = await fetch('https://api.x.ai/v1/language-models', {
headers: {
'Authorization': `Bearer ${key}`,
},
});
if (!response.ok) {
return res.json([]);
}
/** @type {any} */
const data = await response.json();
const multimodalModels = data.models.filter(m => m.input_modalities?.includes('image')).map(m => m.id);
if (!multimodalModels.includes('grok-4-0709')) {
// The endpoint says it doesn't support images, but it does
multimodalModels.push('grok-4-0709');
}
return res.json(multimodalModels);
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
});
router.use('/multimodal-models', multimodalModels);
+2
View File
@@ -108,6 +108,7 @@ class DiskCache {
dir: this.cachePath,
ttl: false,
forgiveParseErrors: true,
expiredInterval: 0,
// @ts-ignore
maxFileDescriptors: 100,
});
@@ -688,6 +689,7 @@ function convertWorldInfoToCharacterBook(name, entries) {
useProbability: entry.useProbability ?? false,
depth: entry.depth ?? 4,
selectiveLogic: entry.selectiveLogic ?? 0,
outlet_name: entry.outletName ?? '',
group: entry.group ?? '',
group_override: entry.groupOverride ?? false,
group_weight: entry.groupWeight ?? null,

Some files were not shown because too many files have changed in this diff Show More