Compare commits

...
161 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
Cohee 6dabf12ed7 Merge pull request #4516 from SillyTavern/staging
Staging
2025-09-13 20:48:26 +03:00
Cohee 98e2d3fa28 Bump package version 2025-09-13 18:25:15 +03:00
Cohee 345660503f Format lang.json file 2025-09-13 18:25:06 +03:00
Rawi1005 a6c3e4c444 Add Thai Translation (#4513)
* Add Thai Translation

* Remove yarn.lock and add to .gitignore

* Update Thai translation

* Update Thai translation for World Info entry status descriptions

* fixed thai translation
2025-09-12 19:20:14 +03:00
Cohee 60bcbe3b4f Merge branch 'release' into staging 2025-09-12 12:33:44 +03:00
Cohee f852b7c4ea Fix npm audit in tests 2025-09-12 12:33:28 +03:00
Cohee 2f3b55d863 Groq: Update caption models list
Fixes #4507
2025-09-12 12:30:48 +03:00
Cohee b7890bfe34 Merge branch 'release' into staging 2025-09-12 12:23:53 +03:00
Cohee 2c5229e382 Fix npm audit 2025-09-12 12:23:36 +03:00
cloak1505 8656dd3a7a Sync OpenRouter providers list (#4509) 2025-09-10 17:30:16 +03:00
nfuller286andCohee 1147507d06 feat: Add Azure OpenAI chat completions provider (#4456)
* feat: Add Azure OpenAI chat completions provider

This commit introduces comprehensive support for integrating Azure OpenAI as a new chat completion source within SillyTavern. The implementation specifically navigates Azure's reliance on deployment names, differing from standard model selection.

Includes:

- **New Feat / UI:** Dedicated settings in `public/index.html` for Azure parameters (Base URL, Deployment Name, API Version, API Key) and a new `public/img/azure_openai.svg` icon.
- **Frontend Logic (`public/scripts/openai.js`):** Manages Azure OpenAI settings and dynamic URL generation. The 'Connect' button triggers a `GET /models` endpoint call solely for API configuration validation (key, URL, version). Upon successful validation, a subsequent `POST` request is made to the AI, and the active model is extracted from its response payload, then populated for UI display (no direct user model selection).
- **Backend Logic (`src/endpoints/backends/chat-completions.js`):** Implements `sendAzureOpenAIRequest` to proxy requests, handling Azure’s unique authentication and URL structures. Enhanced the `/status` endpoint for Azure-specific validation.
- **Secret Management:** Secure handling of Azure OpenAI API keys in `public/scripts/secrets.js` and `src/endpoints/secrets.js`.
- **Autoconnect:** `public/scripts/RossAscends-mods.js` modified to enable automatic connection for Azure OpenAI if an API key is present.

Impact:
- Users can now connect to and utilize Azure OpenAI services.
- Requires new configuration details in the UI.
- Enhances API routing and validation with Azure-specific behavior.
- Navigates model handling: model name is *derived dynamically* from AI response, not directly selected, aligning with internal SillyTavern structure.

* fixed the html issues, openai.ujs and secrets.js

	modified:   public/index.html#
    modified:   public/scripts/openai.js
	modified:   public/scripts/secrets.js

* Extends Azure OpenAI with advanced capabilities

Enables advanced features such as function calling, image inlining, and model reasoning in the UI for Azure OpenAI.

Refactors the backend to support structured output (JSON mode), native thinking, and reasoning effort for compatible Azure OpenAI models. Adds support for logprobs, multiple responses (`n`), and seed, aligning with standard OpenAI behavior.

Improves request handling with a retry mechanism for rate limits and more robust error reporting. Ensures correct parameter handling for model-specific features and conflicts, such as when native thinking is enabled. Optimizes the Azure OpenAI status probe for efficiency.
	modified:   public/index.html
	modified:   public/scripts/openai.js
	modified:   src/endpoints/backends/chat-completions.js

* PR fixes
Simplification
Removed reasoning logic from backend
	modified:   src/endpoints/backends/chat-completions.js

	modified:   src/endpoints/backends/chat-completions.js

* Fix PR comments
Removed the front end compiled url UI element and related.
Misc simplifications
	modified:   public/index.html
	modified:   public/scripts/openai.js
	modified:   src/endpoints/backends/chat-completions.js

* Fixed accidental api temporary disabled
	modified:   public/index.html

* Don't transfer status code verbatim

* Fix formatting

* Enable tool calling

* Fix logo coloration

* Move model arrays to shared constants

* Fix capitalization

* Remove obsolete comment

* Improve response schema parameter format

* Fix tokenizer model selection

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-10 11:44:30 +03:00
RivelleandCohee 5aa1c8fbac Improvement: Enhanced UI Consistency (#4499)
* Improvement: Enhanced UI Consistency

- Added a class to `<div class="inline-drawer-toggle inline-drawer-header">` in **AI Response Configuration** and **API Connections** menus to match the styling of similar elements in **User Settings**
- Improved spacing and sizing for buttons such as `.bg_example .jg-menu` in the **Backgrounds** menu. The previous widths and gaps were too small, often causing accidental taps (especially on mobile devices)

* fix

* Adjust padding and background color in style.css

* Update inline drawer classes for configuration sections

* Remove border styles from expandable sections

* fix

* fix

* fix(sad)

* Adjust desktop bg_list width

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-09 23:23:34 +03:00
Wolfsblvt 862c2b7ba3 Implement robust quote extraction for TTS narration with support for nested quotes (#4502)
* feat: implement robust quote extraction for TTS narration with multi-language support

* refactor: simplify quote matching definition, remove dead code
2025-09-09 22:22:00 +03:00
WolfsblvtandCohee f62eeb76a6 Fix toast positioning inside popups to align with the "Notifications" positioning option (#4506)
* fix: adjust toast container positioning in popups to match core toastr behavior

Fixes #4490

* Fix misplaced element role

* Hide toast container while opening animation is running

* fix: update toast role from alert to status

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-09 22:00:02 +03:00
Wolfsblvt d1349b10bb feat: add ctrl+enter handling for non-empty text input during regeneration (#4504)
Closes #4497
2025-09-09 16:15:27 +03:00
WolfsblvtandCohee dcc6ddf7ad Fix/cleanup and background interactability (keyboard navigation, focus/hover) (#4503)
* refactor: remove unused background styles

* feat: add support for nested @media, @supports, and @container rules in dynamic focus styles

* fix: add keyboard focus support for background menu buttons back

* fix: move "custom" background copy functionality to unified button UI and make it work again

* refactor: simplify CSSContainerRule instance check using window global

* fix: update hover and focus selector placeholder replacements to handle multiple occurrences in selector

* Fix focused outline offset of background samples

* Fix locked background outline color

* Add a11y roles to background menu items

* Add mobile-only button selector

* fix: update button and list item selectors

* Improve keyboard navigation in narrow layout

* Hide rename button for custom=true backgrounds

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-09 15:57:16 +03:00
RivelleandCohee 40a46bee9d Improvement: Add Upload Button to Image Gallery (#4500)
* Improvement: Add Upload Button to Image Gallery

- Added an **Upload Image** button to the **Image Gallery** for a more intuitive experience and easier use on mobile devices ~~(so I can upload some awesome GIFs right from my phone)~~
- Adjusted the `<select class="gallery-sort-select">` menu styling for better consistency with other sections, making it more compact and reducing wasted space

* Fix type error

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-08 19:35:06 +03:00
Cohee 9a5235efcd Do not replace newlines inside of pre blocks (#4498)
Fixes #4475
2025-09-08 13:37:41 +03:00
TosdandCohee 57e363cae6 feat: Regex Presets (#4468)
* Work in progress

* feat: save confirmation

* Fix eslint, add typedef

* Add slash command and compatibility with profiles

* Move UI label up

* Null safety

* Fix duplicate block title

* i18n: zh-CN translation

* Adjust debugger styles

* Move presets block down

* Do not generate id twice for new entries

* Add missing translations

* Simplify settings migration logic

* Fix type comment

* Add missing keys

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-08 12:35:14 +03:00
Cohee 6221c540e4 Reasoning: Support auto-parse for impersonation results (#4489) 2025-09-06 18:16:06 +03:00
Rivelle 8709162df3 Add: id="PersonaManagement" to Persona Management div (#4495)
Adds a missing id for the Persona Management div to align with other panels. If another naming convention is preferred, feel free to update.
2025-09-06 17:22:34 +03:00
L b793e3e19b Fix Backgrounds Borders (#4491) 2025-09-05 09:41:32 +03:00
Ngo Dinh Gia BaoandCohee 8687bb99f3 Add Electron Hub as Chat Completions Provider (#4458)
* fixed merge conflicts

* Supported max tokens + fixed wrong image model mapping

* fixed merge conflicts

* fixed merge conflicts

* updated the logic

* updated the logic

* replaced hard coded reasoning_effort mode list with a dynamic function

* replaced hard coded reasoning_effort model list with a dynamic function

* Fix eslint

* Adjust reasoning effort logic

* Code clean-up

* Add logo

* Add inline image quality

* Fix multimodal models list

* Fix seed not passed

* Add "detail" error parser

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-04 21:25:31 +03:00
CoheeandCopilot d134abd50e Server: Add host whitelisting (#4476)
* Add host whitelisting middleware

* Add prompt to enable hostWhitelist

* perf: Freeze config array

* Update src/middleware/hostWhitelist.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* perf: Add max known hosts limit

* Add validation warning disable hint

* Add conditional host whitelist middleware based on SSL configuration

* Check for cache exhaustion before logging

* Revert "Add conditional host whitelist middleware based on SSL configuration"

This reverts commit 968104c6f4.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-09-04 20:52:23 +03:00
Cohee 680e61d1a0 Fix npm audit 2025-09-04 19:11:07 +03:00
Cohee e871886b13 Server: Support passphrase for SSL private key (#4488)
* SSL: support passphrase for private key

* Recommend CLI argument or environment variable for key passphrase

* Fix SSL passphrase handling to ensure it is always a string
2025-09-04 19:02:48 +03:00
LandCohee 0ba317a318 More modern backgrounds buttons and filename (#4484)
* init

* move background styles, enlarge and clip image to get rid of antialising bug

* move styles from style.css to backgrounds.css

* Reformat backgrounds.css

* Improve selector specificity, fix type errors, increase font size on thumbnails, decrease mobile toggle size

* Fix webp chat backgrounds thumbnails

* Respect reduced motion preference

* Remove transition delay

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-04 18:13:35 +03:00
Cohee 4d98b48956 Unlock Inline Image Quality control for OAI-compatible sources 2025-09-03 14:32:42 +03:00
Cohee 2bc503ec00 Fix eslint 2025-09-03 14:12:23 +03:00
Cohee 13db803bc6 CC: Remove auto-retry on code 429 2025-09-02 14:32:56 +03:00
Cohee 005a062fe7 Fix context size setting for 🤏🍌 2025-09-01 23:02:28 +03:00
Cohee ff8d7d64fc a11y: Setup observers for element roles (#4469)
* a11y: Setup observers for element roles

* Reuse a function

* Add error handling
2025-09-01 17:24:13 +03:00
fe8ebedeb2 fix: Resolve streaming output for Vertex AI Express Mode (#4474)
* fix(api): Resolve streaming output for Vertex AI Express Mode

* chore: Remove unused 'util' variable

* chore: Restore original debug log

* Even cleaner diff

---------

Co-authored-by: AliceRabbit <b290627396@gmail.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-09-01 16:49:55 +03:00
Cohee 285b09ceb7 NanoGPT: Add as captioning source 2025-08-31 19:00:27 +03:00
Cohee 5eea41d315 NanoGPT: Pull max context and vision capability from endpoint 2025-08-31 18:23:39 +03:00
Cohee 57cd001221 NanoGPT: Enable prompt cache for Claude models 2025-08-31 16:57:03 +03:00
Cohee bc2d3300df DeepSeek: Apply semi-strict PPP for reasoner 2025-08-31 16:45:57 +03:00
Cohee 2694ad47f3 DeepSeek: Unlock sampling params for reasoner 2025-08-31 16:45:36 +03:00
epylliaandCohee 9f257b602f Fix compiler errors in public/global.d.ts (#4464)
* Fix TS1038 errors

"A 'declare' modifier cannot be used in an already ambient context."

* Fix TS1040 errors

"'async' modifier cannot be used in an ambient context."

* Fix TS2371 errors

"A parameter initializer is only allowed in a function or constructor
implementation."

* Fix TS2430 errors

"Interface 'ColorPickerEvent' incorrectly extends interface
'ChangeEvent<HTMLElement, any, any, any>'".

The issue here is that the "ColorPickerEvent" objects provided by
toolcool-color-picker.js are vanilla JS CustomEvent objects, not JQuery
event objects. We need to mangle the types here a bit to make JQuery
happy. (At runtime, JQuery is happy to pass along the vanilla Event
object; JQuery's types just don't reflect this.)

* Remove variable and type exports

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-08-31 16:30:38 +03:00
TosdandCohee c46e1a46aa Update zh-CN translations (#4466)
* Update zh-CN translations

* Update zh-CN translations

* Add missing translations

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-08-31 16:06:31 +03:00
LandCohee e1af2fb47d Header change (#4465)
* header changes

* new line, comments

* Simplify styling targets

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-08-31 14:28:12 +03:00
Cohee ddb97d78d3 Chat Completion: Adjust depth of 0-depth injects on continue with prefill (#4452) 2025-08-30 06:25:09 +03:00
as-gh2andas-gh2 26a67b9afe Avoid consuming fetch response twice (#4460)
Fixes #4459

Co-authored-by: as-gh2 <->
2025-08-29 19:43:05 +03:00
Cohee 80fa7f96f1 Caption: Improve Ollama models handling 2025-08-27 00:45:24 +03:00
Cohee 5e4bb0415e OpenRouter: Add Google image output parsing 2025-08-26 22:01:38 +03:00
Cohee 0d84fa67bd gemini-2.5-flash-image-preview 2025-08-26 21:34:02 +03:00
e9e14001e3 Update ru-ru locale (#4449)
* Work on tl

* Small fix

* Fix formatting

---------

Co-authored-by: Yokayo <nonameutubecomm@gmail.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-08-26 20:37:55 +03:00
MAX-TABandCohee f9d1279a69 fix: Slash command descriptions and argument help text are not translated (#4434)
* fix: Slash command descriptions and argument help text are not translated #4428

* fix

* fix: Refine slash command translation scope per review

* fix

* Join split multiline strings

* Revert error name

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-08-26 20:25:52 +03:00
Cohee f81088f2e0 Update third-party npm dependencies (#4447) 2025-08-25 21:51:54 +03:00
MAX-TABandCohee 176825bdb8 feat: Advanced Regex Chain Debugger and Testing Panel (#4418)
* feat: Advanced Regex Chain Debugger and Testing Panel

* fix

* fix_2

* fix_3

* Address code review suggestions for debugger feature

* feat: Add match statistics to debugger

* ESLint

* feat: Enhance debugger with diff view and nav popup

* ESLint

* Fix styles and full results expand

* Diff clean-up

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-08-25 21:44:01 +03:00
Cohee 12ac171979 Temporarily disable cometapi provider 2025-08-25 20:41:26 +03:00
135 changed files with 10308 additions and 2681 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.
+2 -1
View File
@@ -54,4 +54,5 @@ public/scripts/extensions/third-party
.aider*
.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
+38 -8
View File
@@ -40,9 +40,15 @@ browserLaunch:
port: 8000
# -- SSL options --
ssl:
# Enable SSL/TLS encryption
enabled: false
# Path to certificate (relative to server root)
certPath: "./certs/cert.pem"
# Path to private key (relative to server root)
keyPath: "./certs/privkey.pem"
# Private key passphrase (leave empty if not needed)
# For better security, use a CLI argument or an environment variable (SILLYTAVERN_SSL_KEYPASSPHRASE)
keyPassphrase: ""
# -- SECURITY CONFIGURATION --
# Toggle whitelist mode
whitelistMode: true
@@ -76,19 +82,43 @@ 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
enabled: false
# Scan incoming requests for potential host header spoofing
scan: true
# List of allowed hosts. Do not include localhost or IPs, these are safe.
# Use a dot to create subdomain patterns.
# Examples:
# - example.com
# - .trycloudflare.com
hosts: []
# User session timeout *in seconds* (defaults to 24 hours).
## Set to a positive number to expire session after a certain time of inactivity
## Set to 0 to expire session when the browser is closed
+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": "",
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<title>Forbidden</title>
</head>
<body>
<h1>Forbidden</h1>
<p>
If you are the system administrator, add the hostname you are accessing from to the
host whitelist, or disable host whitelisting in the
<code>config.yaml</code> file located in the root directory of your installation.
</p>
<hr />
<p>
<em>Access from this host is not allowed. This attempt has been logged.</em>
</p>
</body>
</html>
+44 -34
View File
@@ -1,16 +1,16 @@
{
"name": "sillytavern",
"version": "1.13.3",
"version": "1.13.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sillytavern",
"version": "1.13.3",
"version": "1.13.5",
"hasInstallScript": true,
"license": "AGPL-3.0",
"dependencies": {
"@adobe/css-tools": "^4.4.3",
"@adobe/css-tools": "^4.4.4",
"@agnai/sentencepiece-js": "^1.1.1",
"@agnai/web-tokenizers": "^0.1.3",
"@iconfu/svg-inject": "^1.2.3",
@@ -42,9 +42,9 @@
"archiver": "^7.0.1",
"bing-translate-api": "^4.1.0",
"body-parser": "^1.20.2",
"bowser": "^2.11.0",
"bowser": "^2.12.1",
"bytes": "^3.1.2",
"chalk": "^5.4.1",
"chalk": "^5.6.0",
"command-exists": "^1.2.9",
"compression": "^1.8.1",
"cookie-parser": "^1.4.6",
@@ -64,6 +64,7 @@
"handlebars": "^4.7.8",
"helmet": "^8.1.0",
"highlight.js": "^11.11.1",
"host-validation-middleware": "^0.1.1",
"html-entities": "^2.6.0",
"iconv-lite": "^0.6.3",
"ip-matching": "^2.1.2",
@@ -74,7 +75,7 @@
"lodash": "^4.17.21",
"mime-types": "^3.0.1",
"moment": "^2.30.1",
"morphdom": "^2.7.5",
"morphdom": "^2.7.7",
"multer": "^2.0.2",
"node-fetch": "^3.3.2",
"node-persist": "^4.0.4",
@@ -90,14 +91,14 @@
"sillytavern-transformers": "2.14.6",
"simple-git": "^3.28.0",
"slidetoggle": "^4.0.0",
"tiktoken": "^1.0.21",
"tiktoken": "^1.0.22",
"url-join": "^5.0.0",
"vectra": "^0.2.2",
"wavefile": "^11.0.0",
"webpack": "^5.98.0",
"write-file-atomic": "^5.0.1",
"ws": "^8.18.3",
"yaml": "^2.8.0",
"yaml": "^2.8.1",
"yargs": "^17.7.1",
"yauzl": "^3.2.0"
},
@@ -114,7 +115,7 @@
"@types/cors": "^2.8.19",
"@types/deno": "^2.3.0",
"@types/express": "^4.17.23",
"@types/jquery": "^3.5.32",
"@types/jquery": "^3.5.33",
"@types/jquery-cropper": "^1.0.4",
"@types/jquery.transit": "^0.9.33",
"@types/jqueryui": "^1.12.24",
@@ -149,9 +150,9 @@
}
},
"node_modules/@adobe/css-tools": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.3.tgz",
"integrity": "sha512-VQKMkwriZbaOgVCby1UDY/LDk5fIjhQicCvVPFqfe+69fWaPWydbWJ3wRt59/YzIwda1I81loas3oCoHxnqvdA==",
"version": "4.4.4",
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz",
"integrity": "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==",
"license": "MIT"
},
"node_modules/@agnai/sentencepiece-js": {
@@ -1911,9 +1912,9 @@
"license": "MIT"
},
"node_modules/@types/jquery": {
"version": "3.5.32",
"resolved": "https://registry.npmjs.org/@types/jquery/-/jquery-3.5.32.tgz",
"integrity": "sha512-b9Xbf4CkMqS02YH8zACqN1xzdxc3cO735Qe5AbSUFmyOiaWAbcpqh9Wna+Uk0vgACvoQHpWDg2rGdHkYPLmCiQ==",
"version": "3.5.33",
"resolved": "https://registry.npmjs.org/@types/jquery/-/jquery-3.5.33.tgz",
"integrity": "sha512-SeyVJXlCZpEki5F0ghuYe+L+PprQta6nRZqhONt9F13dWBtR/ftoaIbdRQ7cis7womE+X2LKhsDdDtkkDhJS6g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2771,13 +2772,13 @@
}
},
"node_modules/axios": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.3.tgz",
"integrity": "sha512-iP4DebzoNlP/YN2dpwCgb8zoCmhtkajzS48JvwmkSkXvPI3DHc7m+XYL5tGnSlJtR6nImXZmdCuN5aP8dh1d8A==",
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.0.tgz",
"integrity": "sha512-oXTDccv8PcfjZmPGlWsPSwtOJCZ/b6W5jAMCNcfwJbCzDckwG0jrYJFaWH1yvivfCXjVzV/SPDEhMB3Q+DSurg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
@@ -2896,9 +2897,9 @@
"license": "ISC"
},
"node_modules/bowser": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/bowser/-/bowser-2.11.0.tgz",
"integrity": "sha512-AlcaJBi/pqqJBIQ8U9Mcpc9i8Aqxn88Skv5d+xBX006BY5u8N3mGLHa5Lgppa7L/HfwgwLgZ6NYs+Ag6uUmJRA==",
"version": "2.12.1",
"resolved": "https://registry.npmjs.org/bowser/-/bowser-2.12.1.tgz",
"integrity": "sha512-z4rE2Gxh7tvshQ4hluIT7XcFrgLIQaw9X3A+kTTRdovCz5PMukm/0QC/BKSYPj3omF5Qfypn9O/c5kgpmvYUCw==",
"license": "MIT"
},
"node_modules/brace-expansion": {
@@ -3126,9 +3127,9 @@
}
},
"node_modules/chalk": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz",
"integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.0.tgz",
"integrity": "sha512-46QrSQFyVSEyYAgQ22hQ+zDa60YHA4fBstHmtSApj1Y5vKtG27fWowW03jCk5KcbXEWPZUIR894aARCA/G1kfQ==",
"license": "MIT",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
@@ -5249,6 +5250,15 @@
"node": ">=12.0.0"
}
},
"node_modules/host-validation-middleware": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/host-validation-middleware/-/host-validation-middleware-0.1.1.tgz",
"integrity": "sha512-fakcpp+x4nbP0fACY5gaHWpaOfstq3w8uB6wvhbPBLqH9GV/tdiM9Ht5mclZVbUuPLGBw1bkH5yyTD6HZq057g==",
"license": "MIT",
"engines": {
"node": "^18.0.0 || >=20.0.0"
}
},
"node_modules/html-entities": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz",
@@ -6178,9 +6188,9 @@
}
},
"node_modules/morphdom": {
"version": "2.7.5",
"resolved": "https://registry.npmjs.org/morphdom/-/morphdom-2.7.5.tgz",
"integrity": "sha512-z6bfWFMra7kBqDjQGHud1LSXtq5JJC060viEkQFMBX6baIecpkNr2Ywrn2OQfWP3rXiNFQRPoFjD8/TvJcWcDg==",
"version": "2.7.7",
"resolved": "https://registry.npmjs.org/morphdom/-/morphdom-2.7.7.tgz",
"integrity": "sha512-04GmsiBcalrSCNmzfo+UjU8tt3PhZJKzcOy+r1FlGA7/zri8wre3I1WkYN9PT3sIeIKfW9bpyElA+VzOg2E24g==",
"license": "MIT"
},
"node_modules/ms": {
@@ -8001,9 +8011,9 @@
"license": "MIT"
},
"node_modules/tiktoken": {
"version": "1.0.21",
"resolved": "https://registry.npmjs.org/tiktoken/-/tiktoken-1.0.21.tgz",
"integrity": "sha512-/kqtlepLMptX0OgbYD9aMYbM7EFrMZCL7EoHM8Psmg2FuhXoo/bH64KqOiZGGwa6oS9TPdSEDKBnV2LuB8+5vQ==",
"version": "1.0.22",
"resolved": "https://registry.npmjs.org/tiktoken/-/tiktoken-1.0.22.tgz",
"integrity": "sha512-PKvy1rVF1RibfF3JlXBSP0Jrcw2uq3yXdgcEXtKTYn3QJ/cBRBHDnrJ5jHky+MENZ6DIPwNUGWpkVx+7joCpNA==",
"license": "MIT"
},
"node_modules/timm": {
@@ -8610,9 +8620,9 @@
}
},
"node_modules/yaml": {
"version": "2.8.0",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.0.tgz",
"integrity": "sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==",
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz",
"integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
+9 -8
View File
@@ -1,6 +1,6 @@
{
"dependencies": {
"@adobe/css-tools": "^4.4.3",
"@adobe/css-tools": "^4.4.4",
"@agnai/sentencepiece-js": "^1.1.1",
"@agnai/web-tokenizers": "^0.1.3",
"@iconfu/svg-inject": "^1.2.3",
@@ -32,9 +32,9 @@
"archiver": "^7.0.1",
"bing-translate-api": "^4.1.0",
"body-parser": "^1.20.2",
"bowser": "^2.11.0",
"bowser": "^2.12.1",
"bytes": "^3.1.2",
"chalk": "^5.4.1",
"chalk": "^5.6.0",
"command-exists": "^1.2.9",
"compression": "^1.8.1",
"cookie-parser": "^1.4.6",
@@ -54,6 +54,7 @@
"handlebars": "^4.7.8",
"helmet": "^8.1.0",
"highlight.js": "^11.11.1",
"host-validation-middleware": "^0.1.1",
"html-entities": "^2.6.0",
"iconv-lite": "^0.6.3",
"ip-matching": "^2.1.2",
@@ -64,7 +65,7 @@
"lodash": "^4.17.21",
"mime-types": "^3.0.1",
"moment": "^2.30.1",
"morphdom": "^2.7.5",
"morphdom": "^2.7.7",
"multer": "^2.0.2",
"node-fetch": "^3.3.2",
"node-persist": "^4.0.4",
@@ -80,14 +81,14 @@
"sillytavern-transformers": "2.14.6",
"simple-git": "^3.28.0",
"slidetoggle": "^4.0.0",
"tiktoken": "^1.0.21",
"tiktoken": "^1.0.22",
"url-join": "^5.0.0",
"vectra": "^0.2.2",
"wavefile": "^11.0.0",
"webpack": "^5.98.0",
"write-file-atomic": "^5.0.1",
"ws": "^8.18.3",
"yaml": "^2.8.0",
"yaml": "^2.8.1",
"yargs": "^17.7.1",
"yauzl": "^3.2.0"
},
@@ -112,7 +113,7 @@
"type": "git",
"url": "https://github.com/SillyTavern/SillyTavern.git"
},
"version": "1.13.3",
"version": "1.13.5",
"scripts": {
"start": "node server.js",
"debug": "node --inspect server.js",
@@ -145,7 +146,7 @@
"@types/cors": "^2.8.19",
"@types/deno": "^2.3.0",
"@types/express": "^4.17.23",
"@types/jquery": "^3.5.32",
"@types/jquery": "^3.5.33",
"@types/jquery-cropper": "^1.0.4",
"@types/jquery.transit": "^0.9.33",
"@types/jqueryui": "^1.12.24",
+302
View File
@@ -0,0 +1,302 @@
/* Main Page Backgrounds */
#bg1 {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
position: absolute;
width: 100%;
height: 100%;
transition: background-image var(--animation-duration-3x) ease-in-out;
z-index: -1;
}
/* Fitting options */
#background_fitting {
max-width: 8em;
}
/* Fill/Cover - scales to fill width while maintaining aspect ratio */
#bg1.cover {
background-size: cover;
background-position: center;
}
/* Fit/Contain - shows entire image maintaining aspect ratio */
#bg1.contain {
background-size: contain;
background-position: center;
background-repeat: no-repeat;
}
/* Stretch - stretches to fill entire space */
#bg1.stretch {
background-size: 100% 100%;
}
/* Center - centers without scaling */
#bg1.center {
background-size: auto;
background-position: center;
background-repeat: no-repeat;
}
/* This is the main flex container for the entire drawer */
.drawer-content.openDrawer.bg-drawer-layout {
display: flex;
}
.bg-drawer-layout {
flex-direction: column;
padding: 0;
}
#bg-header-fixed {
flex-shrink: 0;
padding: 5px;
background-color: var(--SmartThemeBlurTintColor);
border-bottom: 1px solid var(--SmartThemeBorderColor);
width: 100%;
}
.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;
gap: 5px;
}
#bg-scrollable-content {
flex-grow: 1;
overflow-y: auto;
overflow-x: hidden;
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);
}
/* Thumbnails */
.bg_example:hover .BGSampleTitle {
opacity: 1;
}
.bg_example .mobile-only-menu-toggle {
display: none;
}
.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:focus-visible {
outline-offset: inherit;
outline-color: var(--interactable-outline-color);
}
.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;
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;
}
.bg_example:not(.locked-background) .jg-unlock,
.bg_example.locked-background .jg-lock {
display: none;
}
.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 {
display: flex;
position: absolute;
top: 2px;
right: 2px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 5px;
padding: 3px 3px;
z-index: 3;
backdrop-filter: blur(4px);
border: 1px solid var(--SmartThemeBorderColor);
justify-items: center;
align-items: center;
opacity: 0;
visibility: hidden;
transform: scale(0.9);
transform-origin: center;
transition: opacity var(--animation-duration) ease-out, visibility var(--animation-duration) ease-out, transform var(--animation-duration) ease-out;
}
.bg_example:hover .jg-menu,
.bg_example:focus-within .jg-menu {
opacity: 1;
visibility: visible;
transform: scale(1);
}
.bg_example .jg-button {
display: flex;
width: 24px;
height: 24px;
align-items: center;
justify-content: center;
color: white;
padding: 5px;
font-size: 1.1em;
border-radius: 5px;
transition: background-color var(--animation-duration) ease;
}
.bg_example .jg-button:hover {
background-color: rgba(255, 255, 255, 0.2);
}
/* 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-scroll-top.visible {
opacity: 1;
pointer-events: auto;
}
#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,
.bg_example[custom="true"] .jg-edit {
display: none;
}
/* Thumbnail Title */
.bg_example .BGSampleTitle {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));
color: var(--SmartThemeBodyColor);
font-size: 0.9em;
font-weight: 600;
padding: 0px 6px 2px;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
opacity: 0;
transition: opacity var(--animation-duration) ease-in-out;
pointer-events: none;
border-radius: 0 0 8px 8px;
}
.bg_example:hover .BGSampleTitle,
.bg_example:focus-within .BGSampleTitle {
opacity: 1;
}
+72 -8
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,10 +33,70 @@
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;
}
#Backgrounds .bg_example .BGSampleTitle {
opacity: 1;
bottom: 0px;
}
.bg_example:hover .jg-menu,
.bg_example:focus-within .jg-menu {
display: none;
}
.bg_example.mobile-menu-open .jg-menu {
display: flex;
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;
justify-content: center;
position: absolute;
top: 5px;
right: 5px;
width: 30px;
height: 30px;
background-color: rgba(0, 0, 0, 0.4);
color: white;
border-radius: 6px;
z-index: 3;
cursor: pointer;
backdrop-filter: blur(2px);
}
.bg_example .jg-button {
width: 30px;
height: 30px;
}
#background_fitting {
max-width: 6em;
}
#Backgrounds.drawer-content.openDrawer.bg-drawer-layout {
width: 100dvw;
max-width: 100dvw;
}
#extensions_settings,
#extensions_settings2 {
width: 100% !important;
@@ -348,10 +420,6 @@
.horde_multiple_hint {
display: none;
}
.bg_list {
width: unset;
}
}
/*landscape mode phones and ipads*/
@@ -412,10 +480,6 @@
flex-basis: max(calc(100% / 2 - 10px), 180px);
}
.BGSampleTitle {
display: none;
}
.tag.excluded:after {
top: unset;
bottom: unset;
+25 -8
View File
@@ -26,7 +26,6 @@ dialog {
/* Fix weird animation issue with font-scaling during popup open */
backface-visibility: hidden;
transform: translateZ(0);
-webkit-font-smoothing: subpixel-antialiased;
/* Variables setup */
@@ -93,6 +92,11 @@ dialog {
animation: fade-in var(--popup-animation-speed) ease-in-out;
}
/* Fix toast container snapping into the backdrop while the animation is running */
.popup[opening] #toast-container {
visibility: hidden;
}
/* Open state of the dialog */
.popup[open] {
color: var(--SmartThemeBodyColor);
@@ -118,17 +122,30 @@ body.no-blur .popup[open]::backdrop {
animation: fade-out var(--popup-animation-speed) ease-in-out;
}
.popup #toast-container {
/* Fix toastr in dialogs by actually placing it at the top of the screen via transform */
height: 100dvh;
top: calc(50% + var(--topBarBlockSize));
left: 50%;
transform: translate(-50%, -50%);
/* Edge inset to match Toastr default spacing */
:root {
--toast-edge: 12px;
}
/* Fix text align, popups are centered by default. toasts should not. */
.popup #toast-container {
/* Popups are centered by default; toasts should not be */
text-align: left;
}
/* Per-position position adjustments caused by the top bar, inside the popup */
.popup #toast-container.toast-top-left {
top: calc(var(--toast-edge) + var(--topBarBlockSize));
}
.popup #toast-container.toast-top-center {
/* toastr in core does not have a top offset on center, so we don't do that either in popups */
top: var(--topBarBlockSize);
}
.popup #toast-container.toast-top-right {
top: calc(var(--toast-edge) + var(--topBarBlockSize));
}
.popup-crop-wrap {
margin: 10px auto;
max-height: 75vh;
+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;
+11 -11
View File
@@ -5,20 +5,20 @@ import { QuickReplyApi } from './scripts/extensions/quick-reply/api/QuickReplyAp
declare global {
// Custom types
declare type InstructSettings = typeof power_user.instruct;
declare type ContextSettings = typeof power_user.context;
declare type ReasoningSettings = typeof power_user.reasoning;
type InstructSettings = typeof power_user.instruct;
type ContextSettings = typeof power_user.context;
type ReasoningSettings = typeof power_user.reasoning;
// Global namespace modules
interface Window {
ai: any;
}
declare var pdfjsLib;
declare var ePub;
declare var quickReplyApi: QuickReplyApi;
var pdfjsLib;
var ePub;
var quickReplyApi: QuickReplyApi;
declare var SillyTavern: {
var SillyTavern: {
getContext(): typeof getContext;
llm: any;
libs: typeof libs;
@@ -63,7 +63,7 @@ declare global {
* @param lang Target language
* @param provider Translation provider
*/
async function translate(text: string, lang: string, provider: string = null): Promise<string>;
function translate(text: string, lang: string, provider?: string | null): Promise<string>;
interface ConvertVideoArgs {
buffer: Uint8Array;
@@ -76,9 +76,9 @@ declare global {
*/
function convertVideoToAnimatedWebp(args: ConvertVideoArgs): Promise<Uint8Array>;
interface ColorPickerEvent extends JQuery.ChangeEvent<HTMLElement> {
type ColorPickerEvent = Omit<JQuery.ChangeEvent<HTMLElement>, "detail"> & {
detail: {
rgba: string;
};
}
}
};
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

+1
View File
@@ -0,0 +1 @@
<svg id="uuid-adbdae8e-5a41-46d1-8c18-aa73cdbfee32" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18" height="100px" width="100px" transform="rotate(0) scale(1, 1)"><path d="m0,2.7v12.6c0,1.491,1.209,2.7,2.7,2.7h12.6c1.491,0,2.7-1.209,2.7-2.7V2.7c0-1.491-1.209-2.7-2.7-2.7H2.7C1.209,0,0,1.209,0,2.7ZM10.8,0v3.6c0,3.976,3.224,7.2,7.2,7.2h-3.6c-3.976,0-7.199,3.222-7.2,7.198v-3.598c0-3.976-3.224-7.2-7.2-7.2h3.6c3.976,0,7.2-3.224,7.2-7.2Z" stroke-width="0"/></svg>

After

Width:  |  Height:  |  Size: 468 B

+1
View File
@@ -0,0 +1 @@
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="118.66667" height="177.33333" viewBox="0 0 89 133"><path d="M14.5 1.8c-6.3 3-11.3 8.8-13.2 15.1C-.1 21.8-.2 27.6.6 70.6l.9 48.2 3.1 4.4c1.9 2.6 5.3 5.4 8.4 7l5.2 2.8h26.7c14.8 0 28.2-.5 30.2-1 5.4-1.5 11.6-8.6 12.4-14.3 1-6.5-.2-10.4-4.7-15.3-5.1-5.5-8.3-6.4-23.3-6.4C46.2 96 43 94.9 43 90.5c0-4.3 3.3-5.5 15.4-5.5 13 0 18-1.8 22.7-8.3 5.4-7.5 5-14.4-1.3-21.3-5.1-5.5-11-7.4-22.8-7.4-9.2 0-13-1.5-13-5 0-3.9 3.6-5 16.9-5 14.5 0 19.4-1.6 23.7-7.9 5.4-7.9 5.2-15.9-.6-22.5-5.4-6.1-6.7-6.4-37.5-7.1-26.3-.6-28.2-.5-32 1.3z"/></svg>

After

Width:  |  Height:  |  Size: 589 B

+240 -202
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,10 +648,10 @@
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">
<div class="range-block" data-source="openai,custom,xai,aimlapi,moonshot,azure_openai">
<div class="range-block-title" data-i18n="Multiple swipes per generation">
Multiple swipes per generation
</div>
@@ -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">
@@ -691,7 +693,7 @@
</span>
</div>
</div>
<div class="range-block" data-source="openai,claude,aimlapi,openrouter,ai21,makersuite,vertexai,mistralai,custom,cohere,perplexity,groq,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi">
<div class="range-block" data-source="openai,claude,aimlapi,openrouter,ai21,makersuite,vertexai,mistralai,custom,cohere,perplexity,groq,electronhub,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi,azure_openai">
<div class="range-block-title" data-i18n="Temperature">
Temperature
</div>
@@ -704,7 +706,7 @@
</div>
</div>
</div>
<div class="range-block" data-source="openai,aimlapi,openrouter,custom,cohere,perplexity,groq,mistralai,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi">
<div class="range-block" data-source="openai,aimlapi,openrouter,custom,cohere,perplexity,groq,mistralai,electronhub,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi,azure_openai">
<div class="range-block-title" data-i18n="Frequency Penalty">
Frequency Penalty
</div>
@@ -717,7 +719,7 @@
</div>
</div>
</div>
<div class="range-block" data-source="openai,aimlapi,openrouter,custom,cohere,perplexity,groq,mistralai,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi">
<div class="range-block" data-source="openai,aimlapi,openrouter,custom,cohere,perplexity,groq,mistralai,electronhub,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi,azure_openai">
<div class="range-block-title" data-i18n="Presence Penalty">
Presence Penalty
</div>
@@ -730,7 +732,7 @@
</div>
</div>
</div>
<div class="range-block" data-source="claude,aimlapi,openrouter,makersuite,vertexai,cohere,perplexity">
<div class="range-block" data-source="claude,aimlapi,openrouter,makersuite,vertexai,cohere,perplexity,electronhub">
<div class="range-block-title" data-i18n="Top K">
Top K
</div>
@@ -743,7 +745,7 @@
</div>
</div>
</div>
<div class="range-block" data-source="openai,claude,aimlapi,openrouter,ai21,makersuite,vertexai,mistralai,custom,cohere,perplexity,groq,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi">
<div class="range-block" data-source="openai,claude,aimlapi,openrouter,ai21,makersuite,vertexai,mistralai,custom,cohere,perplexity,groq,electronhub,nanogpt,deepseek,xai,pollinations,moonshot,fireworks,cometapi,azure_openai">
<div class="range-block-title" data-i18n="Top P">
Top P
</div>
@@ -980,7 +982,7 @@
</div>
</div>
</div>
<div class="range-block" data-source="openai,openrouter,mistralai,custom,cohere,groq,nanogpt,xai,pollinations,aimlapi,makersuite,vertexai">
<div class="range-block" data-source="openai,openrouter,mistralai,custom,cohere,groq,electronhub,nanogpt,xai,pollinations,aimlapi,makersuite,vertexai,azure_openai">
<div class="range-block-title justifyLeft" data-i18n="Seed">
Seed
</div>
@@ -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>
@@ -1970,7 +1951,7 @@
</span>
</div>
</div>
<div class="range-block" data-source="makersuite,vertexai,aimlapi,openrouter,claude,xai,nanogpt">
<div class="range-block" data-source="makersuite,vertexai,aimlapi,openrouter,claude,xai,electronhub,nanogpt">
<label for="openai_enable_web_search" class="checkbox_label flexWrap widthFreeExpand">
<input id="openai_enable_web_search" type="checkbox" />
<span data-i18n="Enable web search">Enable web search</span>
@@ -1984,7 +1965,7 @@
</b>
</div>
</div>
<div class="range-block" data-source="openai,cohere,mistralai,custom,claude,aimlapi,openrouter,groq,deepseek,makersuite,vertexai,ai21,xai,pollinations,moonshot,fireworks,cometapi">
<div class="range-block" data-source="openai,cohere,mistralai,custom,claude,aimlapi,openrouter,groq,deepseek,makersuite,vertexai,ai21,xai,pollinations,moonshot,fireworks,cometapi,electronhub,azure_openai">
<label for="openai_function_calling" class="checkbox_label flexWrap widthFreeExpand">
<input id="openai_function_calling" type="checkbox" />
<span data-i18n="Enable function calling">Enable function calling</span>
@@ -1999,7 +1980,7 @@
<strong data-i18n="enable_functions_desc_4">Not supported when Prompt Post-Processing with "no tools" is used!</strong>
</div>
</div>
<div class="range-block" data-source="openai,aimlapi,openrouter,mistralai,makersuite,vertexai,claude,custom,xai,pollinations,moonshot,cohere,cometapi">
<div class="range-block" data-source="openai,aimlapi,openrouter,mistralai,makersuite,vertexai,claude,custom,xai,pollinations,moonshot,cohere,cometapi,nanogpt,electronhub,azure_openai">
<label for="openai_image_inlining" class="checkbox_label flexWrap widthFreeExpand">
<input id="openai_image_inlining" type="checkbox" />
<span data-i18n="Send inline images">Send inline images</span>
@@ -2015,7 +1996,7 @@
<code><i class="fa-solid fa-wand-magic-sparkles"></i></code>
<span data-i18n="image_inlining_hint_3">menu to attach an image file to the chat.</span>
</div>
<div class="flex-container flexFlowColumn wide100p textAlignCenter marginTop10" data-source="openai,custom,xai,pollinations,cohere">
<div class="flex-container flexFlowColumn wide100p textAlignCenter marginTop10" data-source="openai,custom,xai,pollinations,cohere,cometapi,nanogpt,moonshot,aimlapi,openrouter,mistralai,electronhub,azure_openai">
<div class="flex-container oneline-dropdown">
<label for="openai_inline_image_quality" data-i18n="Inline Image Quality">
Inline Image Quality
@@ -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">
<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>
@@ -2091,7 +2072,7 @@
</span>
</div>
</div>
<div class="flex-container flexFlowColumn wide100p textAlignCenter marginTop10" data-source="openai,custom,claude,xai,makersuite,vertexai,aimlapi,openrouter,pollinations,perplexity,cometapi">
<div class="flex-container flexFlowColumn wide100p textAlignCenter marginTop10" data-source="openai,custom,claude,xai,makersuite,vertexai,aimlapi,openrouter,pollinations,perplexity,cometapi,electronhub,azure_openai">
<div class="flex-container oneline-dropdown" title="Constrains effort on reasoning for reasoning models.&#10;Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response." data-i18n="[title]Constrains effort on reasoning for reasoning models.">
<label for="openai_reasoning_effort">
<span data-i18n="Reasoning Effort">Reasoning Effort</span>
@@ -2105,7 +2086,7 @@
<option data-i18n="openai_reasoning_effort_high" value="high">High</option>
<option data-i18n="openai_reasoning_effort_maximum" value="max">Maximum</option>
</select>
<div class="toggle-description justifyLeft marginBot5" data-source="openai,custom,xai,aimlapi,openrouter,perplexity" data-i18n="OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level.">
<div class="toggle-description justifyLeft marginBot5" data-source="openai,custom,xai,aimlapi,openrouter,perplexity,electronhub,azure_openai" data-i18n="OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level.">
OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level.
</div>
<div class="toggle-description justifyLeft marginBot5" data-source="claude" data-i18n="Allocates a portion of the response length for thinking (min: 1024 tokens, low: 10%, medium: 25%, high: 50%, max: 95%), but minimum 1024 tokens. Auto does not request thinking.">
@@ -2144,7 +2125,7 @@
</div>
</div>
</div>
<div class="range-block m-t-1" data-source="openai,aimlapi,openrouter,custom">
<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>
@@ -2802,10 +2783,13 @@
<optgroup>
<option value="ai21">AI21</option>
<option value="aimlapi">AI/ML API</option>
<option value="azure_openai">Azure OpenAI</option>
<option value="claude">Claude</option>
<option value="cohere">Cohere</option>
<option value="cometapi">CometAPI</option>
<!-- Temporarily disabled. -->
<!-- <option value="cometapi">CometAPI</option> -->
<option value="deepseek">DeepSeek</option>
<option value="electronhub">Electron Hub</option>
<option value="fireworks">Fireworks AI</option>
<option value="groq">Groq</option>
<option value="makersuite">Google AI Studio</option>
@@ -3032,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>
@@ -3079,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">
@@ -3171,45 +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>
@@ -3221,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>
@@ -3346,15 +3324,10 @@
<!-- 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">
<option value="gemini-2.0-flash-exp" data-mode="full">gemini-2.0-flash-exp</option>
@@ -3378,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>
@@ -3466,6 +3379,56 @@
<option value="mistral-saba-24b">mistral-saba-24b</option>
</select>
</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>
</div>
<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>
<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>
<div class="flex-container">
@@ -3647,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>
@@ -3717,6 +3674,49 @@
<option value="kimi-thinking-preview">kimi-thinking-preview</option>
</select>
</div>
<div id="azure_openai_settings" data-source="azure_openai">
<!-- Azure Base URL -->
<h4><span data-i18n="Azure Base URL">Azure Base URL</span></h4>
<div class="flex-container">
<input id="azure_base_url" data-setting="azure_base_url" class="text_pole wide100p" type="text" placeholder="https://your-resource.openai.azure.com/">
</div>
<!-- Azure Deployment Name -->
<h4><span data-i18n="Deployment Name">Deployment Name</span></h4>
<div class="flex-container">
<input id="azure_deployment_name" data-setting="azure_deployment_name" class="text_pole wide100p" type="text" placeholder="your-deployment-name" title="The name of your model deployment in Azure." data-i18n="[title]The name of your model deployment in Azure.">
</div>
<!-- Azure API Version Dropdown -->
<h4><span data-i18n="API Version">API Version</span></h4>
<div class="flex-container">
<select id="azure_api_version" data-setting="azure_api_version" class="text_pole wide100p">
<option value="2025-04-01-preview">2025-04-01-preview</option>
<option value="2024-10-21">2024-10-21</option>
</select>
</div>
<!-- Azure API Key -->
<h4><span data-i18n="Azure API Key">Azure API Key</span></h4>
<div class="flex-container">
<input id="api_key_azure_openai" data-setting="api_key_azure_openai" class="text_pole flex1" type="password" 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_azure_openai"></div>
</div>
<div class="neutral_warning" data-i18n="For privacy reasons, your API key will be hidden after you click 'Connect'." data-for="api_key_azure_openai">
For privacy reasons, your API key will be hidden after you click 'Connect'.
</div>
<!-- Model Name (Select) -->
<h4><span data-i18n="Model Name">Model Name</span></h4>
<div class="flex-container">
<select id="azure_openai_model" data-setting="azure_openai_model" class="text_pole wide100p">
<option value="" disabled selected data-i18n="Click 'Connect' to fetch model name">Click 'Connect' to fetch model name</option>
</select>
</div>
<div>
<small data-i18n="The underlying model of your deployment. This is detected automatically when you connect.">The underlying model of your deployment. This is detected automatically when you connect.</small>
</div>
</div>
<div id="prompt_post_processing_form">
<h4>
<span data-i18n="Prompt Post-Processing">
@@ -4217,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>
@@ -4897,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">
@@ -4908,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" />
@@ -5277,17 +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">
<div class="flex-container">
<div class="flex-container alignItemsBaseline wide100p">
<h3 class="margin0 flex2" data-i18n="Background Image">
Background Image
</h3>
<input id="bg-filter" data-i18n="[placeholder]Filter" placeholder="Filter" class="text_pole flex1" type="search" />
<div id="Backgrounds" class="drawer-content closedDrawer bg-drawer-layout">
<div id="bg-header-fixed">
<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>
@@ -5300,16 +5305,25 @@
<span data-i18n="Auto-select">Auto-select</span>
</div>
</div>
<h3 data-i18n="System Backgrounds" class="wide100p textAlignCenter">
System Backgrounds
</h3>
<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">
<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">
<form id="form_bg_download" class="bg_example no-border no-shadow" action="javascript:void(null);" method="post" enctype="multipart/form-data">
<label class="input-file">
<input type="file" id="add_bg_button" name="avatar" accept="image/*, video/*">
<div class="bg_example no-border no-shadow add_bg_but" style="background-image: url('/img/addbg3.png');"></div>
</label>
</form>
</div>
<h3 data-i18n="Chat Backgrounds" class="wide100p textAlignCenter">
Chat Backgrounds
@@ -5320,6 +5334,12 @@
<div id="bg_custom_content" class="bg_list">
</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/*">
</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">
@@ -5409,7 +5429,7 @@
<div class="drawer-toggle">
<div class="drawer-icon fa-solid fa-face-smile fa-fw closedIcon" title="Persona Management" data-i18n="[title]Persona Management"></div>
</div>
<div class="drawer-content closedDrawer">
<div id="PersonaManagement" class="drawer-content closedDrawer">
<div class="flex-container wide100p alignitemscenter spaceBetween flexNoGap">
<div class="flex-container alignItemsBaseline wide100p">
<div class="flex1 flex-container alignItemsBaseline">
@@ -5477,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">
@@ -6228,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;">
@@ -6253,14 +6276,19 @@
</div>
</div>
<div id="background_template" class="template_element">
<div class="bg_example flex-container" bgfile="" class="bg_example_img" title="">
<div title="Copy to system backgrounds" data-i18n="[title]Copy to system backgrounds" class="bg_button bg_example_copy fa-solid fa-file-arrow-up"></div>
<div title="Rename background" data-i18n="[title]Rename background" class="bg_button bg_example_edit fa-solid fa-pencil"></div>
<div title="Lock" data-i18n="[title]Lock" class="bg_button bg_example_lock fa-solid fa-lock"></div>
<div title="Unlock" data-i18n="[title]Unlock" class="bg_button bg_example_unlock fa-solid fa-lock-open"></div>
<div title="Delete background" data-i18n="[title]Delete background" class="bg_button bg_example_cross fa-solid fa-circle-xmark"></div>
<div class="BGSampleTitle">
<div class="bg_example flex-container" bgfile="" title="">
<div class="bg_example_img"></div>
<div class="mobile-only-menu-toggle">
<i class="fa-solid fa-ellipsis-vertical"></i>
</div>
<div class="jg-menu">
<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>
<div class="BGSampleTitle"></div>
</div>
</div>
<!-- templates for JS to reuse when needed -->
@@ -6379,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">
@@ -6436,7 +6471,7 @@
</span>
<div class="flex-container">
<div class="flex-container flexFlowColumn">
<label class="checkbox flex-container alignitemscenter flexNoGap" title="This entry will not be recursively activated by other entries.">
<label class="checkbox flex-container alignitemscenter flexNoGap" data-i18n="[title]This entry will not be recursively activated by other entries." title="This entry will not be recursively activated by other entries.">
<input type="checkbox" name="excludeRecursion" />
<span data-i18n="Non-recursable">
Non-recursable
@@ -6716,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) {
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "وضع علامة",
"API key (optional)": "مفتاح API (اختياري)",
"Server url": "رابط الخادم",
"Electron Hub API Key": "مفتاح API لـ Electron Hub",
"Electron Hub Model": "نموذج Electron Hub",
"Example: http://127.0.0.1:5000": "مثال: http://127.0.0.1:5000",
"Custom model (optional)": "نموذج مخصص (اختياري)",
"vllm-project/vllm": "vllm-project/vllm (وضع غلاف OpenAI API)",
@@ -367,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": "حجم السياق",
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "Flagge",
"API key (optional)": "API-Schlüssel (optional)",
"Server url": "Server-URL",
"Electron Hub API Key": "Electron Hub API-Schlüssel",
"Electron Hub Model": "Electron Hub-Modell",
"Example: http://127.0.0.1:5000": "Beispiel: http://127.0.0.1:5000",
"Custom model (optional)": "Benutzerdefiniertes Modell (optional)",
"vllm-project/vllm": "vllm-project/vllm (OpenAI API-Wrappermodus)",
@@ -367,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",
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "bandera",
"API key (optional)": "Clave API (opcional)",
"Server url": "URL del servidor",
"Electron Hub API Key": "Clave API de Electron Hub",
"Electron Hub Model": "Modelo de Electron Hub",
"Example: http://127.0.0.1:5000": "Ejemplo: http://127.0.0.1:5000",
"Custom model (optional)": "Modelo personalizado (opcional)",
"vllm-project/vllm": "vllm-project/vllm (modo contenedor de API OpenAI)",
@@ -367,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",
+4 -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",
@@ -1411,6 +1411,8 @@
"Do not proceed if you do not agree to this!": "Ne continuez pas si vous n'êtes pas d'accord avec cela !",
"Claude API Key": "Clé API Claude",
"Allow fallback models": "Autoriser les modèles de secours",
"Electron Hub API Key": "Clé API Electron Hub",
"Electron Hub Model": "Modèle Electron Hub",
"NanoGPT API Key": "Clé API NanoGPT",
"NanoGPT Model": "Modèle NanoGPT",
"DeepSeek API Key": "Clé API DeepSeek",
@@ -1564,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ð",
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "bandiera",
"API key (optional)": "Chiave API (opzionale)",
"Server url": "URL del server",
"Electron Hub API Key": "Chiave API di Electron Hub",
"Electron Hub Model": "Modello di Electron Hub",
"Example: http://127.0.0.1:5000": "Esempio: http://127.0.0.1:5000",
"Custom model (optional)": "Modello personalizzato (opzionale)",
"vllm-project/vllm": "vllm-project/vllm (modalità wrapper API OpenAI)",
@@ -367,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",
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "フラグ",
"API key (optional)": "APIキー(オプション)",
"Server url": "サーバーURL",
"Electron Hub API Key": "Electron Hub API キー",
"Electron Hub Model": "Electron Hub モデル",
"Example: http://127.0.0.1:5000": "例: http://127.0.0.1:5000",
"Custom model (optional)": "カスタムモデル(オプション)",
"vllm-project/vllm": "vllm-project/vllm (OpenAI API ラッパーモード)",
@@ -367,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": "コンテキストサイズ",
+3 -1
View File
@@ -319,6 +319,8 @@
"flag": "깃발",
"API key (optional)": "API 키 (선택 사항)",
"Server url": "서버 URL",
"Electron Hub API Key": "Electron Hub API 키",
"Electron Hub Model": "Electron Hub 모델",
"Example: http://127.0.0.1:5000": "예시: http://127.0.0.1:5000",
"Custom model (optional)": "사용자 정의 모델 (선택 사항)",
"vllm-project/vllm": "vllm-project/vllm(OpenAI API 래퍼 모드)",
@@ -372,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": "컨텍스트 크기",
+66 -17
View File
@@ -1,17 +1,66 @@
[
{ "lang": "ar-sa", "display": "عربي (Arabic)" },
{ "lang": "zh-cn", "display": "简体中文 (Chinese) (Simplified)" },
{ "lang": "zh-tw", "display": "繁體中文 (Chinese) (Taiwan)" },
{ "lang": "nl-nl", "display": "Nederlands (Dutch)" },
{ "lang": "de-de", "display": "Deutsch (German)" },
{ "lang": "fr-fr", "display": "Français (French)" },
{ "lang": "is-is", "display": "íslenska (Icelandic)" },
{ "lang": "it-it", "display": "Italiano (Italian)" },
{ "lang": "ja-jp", "display": "日本語 (Japanese)" },
{ "lang": "ko-kr", "display": "한국어 (Korean)" },
{ "lang": "pt-pt", "display": "Português (Portuguese brazil)" },
{ "lang": "ru-ru", "display": "Русский (Russian)" },
{ "lang": "es-es", "display": "Español (Spanish)" },
{ "lang": "uk-ua", "display": "Yкраїнська (Ukrainian)" },
{ "lang": "vi-vn", "display": "Tiếng Việt (Vietnamese)" }
]
[
{
"lang": "ar-sa",
"display": "عربي (Arabic)"
},
{
"lang": "zh-cn",
"display": "简体中文 (Chinese) (Simplified)"
},
{
"lang": "zh-tw",
"display": "繁體中文 (Chinese) (Taiwan)"
},
{
"lang": "nl-nl",
"display": "Nederlands (Dutch)"
},
{
"lang": "de-de",
"display": "Deutsch (German)"
},
{
"lang": "fr-fr",
"display": "Français (French)"
},
{
"lang": "is-is",
"display": "íslenska (Icelandic)"
},
{
"lang": "it-it",
"display": "Italiano (Italian)"
},
{
"lang": "ja-jp",
"display": "日本語 (Japanese)"
},
{
"lang": "ko-kr",
"display": "한국어 (Korean)"
},
{
"lang": "pt-pt",
"display": "Português (Portuguese brazil)"
},
{
"lang": "ru-ru",
"display": "Русский (Russian)"
},
{
"lang": "es-es",
"display": "Español (Spanish)"
},
{
"lang": "uk-ua",
"display": "Українська (Ukrainian)"
},
{
"lang": "vi-vn",
"display": "Tiếng Việt (Vietnamese)"
},
{
"lang": "th-th",
"display": "ไทย (Thai)"
}
]
+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",
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "bandeira",
"API key (optional)": "Chave da API (opcional)",
"Server url": "URL do servidor",
"Electron Hub API Key": "Chave API Electron Hub",
"Electron Hub Model": "Modelo Electron Hub",
"Example: http://127.0.0.1:5000": "Exemplo: http://127.0.0.1:5000",
"Custom model (optional)": "Modelo personalizado (opcional)",
"vllm-project/vllm": "vllm-project/vllm (modo wrapper da API OpenAI)",
@@ -367,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",
+271 -110
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",
@@ -40,7 +40,7 @@
"Smoothing Factor": "Коэффициент сглаживания",
"No Repeat Ngram Size": "Размер no_repeat_ngram",
"Min Length": "Мин. длина",
"Alternative server URL (leave empty to use the default value).": "URL альтернативного сервера (оставьте пустым для стандартного значения)",
"Alternative server URL (leave empty to use the default value).": "URL реверс-прокси (оставьте пустым для стандартного значения)",
"Remove your real OAI API Key from the API panel BEFORE typing anything into this box": "Удалите свой личный OAI API Key из панели API, и ТОЛЬКО ПОСЛЕ ЭТОГО вводите что-то сюда",
"We cannot provide support for problems encountered while using an unofficial OpenAI proxy": "Мы не сможем предоставить помощь с проблемами, с которыми вы столкнетесь при использовании неофициальных прокси для OpenAI",
"Context Size (tokens)": "Размер контекста (в токенах)",
@@ -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": "Подключиться",
@@ -145,7 +145,7 @@
"View API Usage Metrics": "Посмотреть статистику использования API",
"Show External models (provided by API)": "Показать \"сторонние\" модели (предоставленные API)",
"Allow fallback routes": "Разрешить резервные маршруты",
"Allow fallback routes Description": "Автоматически выбирает альтернативную модель, если выбранная модель не может удовлетворить ваш запрос.",
"Allow fallback routes Description": "Автоматически выбирает альтернативную модель, если выбранная модель не может обслужить ваш запрос.",
"OpenRouter API Key": "Ключ от OpenRouter API",
"OpenRouter Model": "Модель OpenRouter",
"View Remaining Credits": "Посмотреть оставшиеся кредиты",
@@ -154,7 +154,7 @@
"View hidden API keys": "Посмотреть скрытые API-ключи",
"Advanced Formatting": "Расширенное форматирование",
"Context Template": "Шаблон контекста",
"Replace Macro in Stop Strings": "Заменять макросы в пользовательских стоп-строках",
"Replace Macro in Stop Strings": "Заменять макросы в стоп-строках",
"Story String": "Общий шаблон",
"Example Separator": "Разделитель примеров сообщений",
"Chat Start": "Начало чата",
@@ -184,7 +184,7 @@
"Scan Depth": "Глубина сканирования",
"Case-Sensitive": "С учетом регистра",
"Match Whole Words": "Только полное совпадение",
"Use global setting": "Использовать глобальную настройку",
"Use global setting": "Глоб. настройка",
"Yes": "Да",
"No": "Нет",
"Context %": "Процент контекста",
@@ -201,8 +201,8 @@
"Bubbles": "Пузыри",
"No Blur Effect": "Отключить размытие",
"No Text Shadows": "Отключить тень текста",
"Waifu Mode": "Рeжим Вайфу",
"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": "Меню отладки",
@@ -279,7 +279,7 @@
"Impersonate": "Перевоплощение",
"Regenerate": "Повторная генерация",
"Message Sound": "Звук сообщения",
"Author's Note": "Заметки автора",
"Author's Note": "Авторские заметки",
"Replace empty message": "Заменять пустые сообщения",
"Send this text instead of nothing when the text box is empty.": "Этот текст будет отправлен в случае отсутствия текста на отправку.",
"Unrestricted maximum value for the context slider": "Убрать потолок для ползунка контекста. Включайте только если точно понимаете, что делаете",
@@ -322,24 +322,29 @@
"Order ↘": "Порядок ↘",
"UID ↗": "UID ↗",
"UID ↘": "UID ↘",
"Trigger% ↗": "Триггер% ↗",
"Trigger% ↘": "Триггер% ↘",
"Trigger% ↗": "% срабатываний ↗",
"Trigger% ↘": "% срабатываний ↘",
"Depth:": "Глубина:",
"Character Lore First": "Сначала лор персонажа",
"Global Lore First": "Сначала глобальный лор",
"Recursive Scan": "Рекурсивное сканирование",
"Case Sensitive": "Учитывать регистр",
"Alert On Overflow": "Оповещение о переполнении",
"Alert On Overflow": "Оповещение о превышении бюджета",
"Use Probability": "Использовать вероятность",
"Exclude from recursion": "Исключить из рекурсии",
"Entry Title/Memo": "Название или заметка о записи",
"Position:": "Положение:",
"T_Position": "↑Char: Перед определениями Персонажа\n↓Char: После определений Персонажа\n↑AN: Перед Пометок автора\n↓AN: После Пометок автора\n@D: На глубине",
"T_Position": "↑Перс: Перед описанием персонажа\n↓Перс: После описания персонажа\n↑ПС: Перед примерами сообщений\n↓ПС: После примеров сообщений\n↑АЗ: Перед авторскими заметками\n↓АЗ: После авторских заметок\nНа глуб. ⚙️: на глубине (система)\nНа глуб. 👤: на глубине (пользователь)\nНа глуб. 🤖: на глубине (ассистент)",
"Before Char Defs": "↑Перс.",
"After Char Defs": "↓Перс.",
"Before AN": "↑АЗ",
"After AN": "↓АЗ",
"Order": "Очерёдность:",
"Before EM": "↑ПС",
"After EM": "↓ПС",
"at Depth System": "На глуб. ⚙️",
"at Depth User": "На глуб. 👤",
"at Depth AI": "На глуб. 🤖",
"Order": "Приоритет:",
"Update a theme file": "Обновить файл темы",
"Save as a new theme": "Сохранить как новую тему",
"Minimum number of blacklisted words detected to trigger an auto-swipe": "Минимальное количество обнаруженных запрещённых слов, при котором срабатывает авто-свайп.",
@@ -349,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",
@@ -358,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": "Кнопка отправки продолжает сообщение",
@@ -367,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": "Минимальная длина сгенерированных сообщений",
@@ -385,13 +390,13 @@
"Remove text shadow effect": "Удаление эффекта тени от текста.",
"Reduce chat height, and put a static sprite behind the chat window": "Уменьшить высоту чата и поместить статичный спрайт за окном чата.",
"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": "Альтернативный пользовательский интерфейс для числовых параметров выборки с меньшим количеством шагов.",
"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": "Отобразить теговые папки с персонажами в списке персонажей.",
@@ -399,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 в новый файл.",
@@ -409,12 +414,12 @@
"If checked and the character card contains a jailbreak override (Post History Instruction), use that instead": "При включении этой опции, пользовательский джейлбрейк будет заменяться кастомным джейлбрейком из карточки (при его наличии).",
"Show actual file names on the disk, in the characters list display only": "Отображение названий файлов персонажей на диске, только в списке персонажей.",
"Prompt to import embedded card tags on character import. Otherwise embedded tags are ignored": "Запрашивать разрешения на импорт встроенных тегов карт при импорте персонажей. В противном случае встроенные теги игнорируются.",
"Hide character definitions from the editor panel behind a spoiler button": "Спрятать определения персонажей из панели редактора за кнопку спойлера.",
"Hide character definitions from the editor panel behind a spoiler button": "Спрятать описания персонажей из панели редактора за кнопку спойлера.",
"Show a button in the input area to ask the AI to continue (extend) its last message": "Показывать на форме ответа кнопку, по нажатии на которую ИИ продолжит своё предыдущее сообщение.",
"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 на основе настраиваемых критериев.",
@@ -427,8 +432,8 @@
"Your Persona": "Ваша персона",
"Show notifications on switching personas": "Показывать уведомления при смене персоны",
"In Story String / Prompt Manager": "В общем шаблоне / Менеджере промптов",
"Top of Author's Note": "Сверху от заметок автора",
"Bottom of Author's Note": "Снизу от заметок автора",
"Top of Author's Note": "Сверху от авторских заметок",
"Bottom of Author's Note": "Снизу от авторских заметок",
"How do I use this?": "Как пользоваться?",
"More...": "Ещё...",
"Link to World Info": "Ссылка на информацию о мире",
@@ -436,7 +441,7 @@
"Scenario Override": "Перезапись сценария",
"Rename": "Переименовать",
"Character Description": "Описание персонажа",
"Creator's Notes": "Заметки создателя",
"Creator's Notes": "Примечание от создателя",
"A-Z": "A-Z",
"Z-A": "Z-A",
"Newest": "Сначала новые",
@@ -471,7 +476,7 @@
"Enter your name": "Введите свое имя",
"Name this character": "Назовите этого персонажа",
"Search / Create Tags": "Искать / Создать тэги",
"Describe your character's physical and mental traits here.": "Опишите ментальные и физические черты персонажа",
"Describe your character's physical and mental traits here.": "Опишите характер персонажа и его внешность",
"This will be the first message from the character that starts every chat.": "Это будет первое сообщение от персонажа при начале нового чата",
"Chat Name (Optional)": "Название чата (необязательно)",
"Search...": "Поиск...",
@@ -483,10 +488,10 @@
"(Write a comma-separated list of tags)": "(Список тегов через запятую)",
"(A brief description of the personality)": "(Краткое описание личности)",
"(Circumstances and context of the interaction)": "(Обстоятельства и контекст этого диалога)",
"(Examples of chat dialog. Begin each example with START on a new line.)": "(Примеры диалога. Начинайте каждый пример с START или новой строкой.)",
"(Examples of chat dialog. Begin each example with START on a new line.)": "(Примеры диалога. Начинайте каждый пример со START и на новой строке.)",
"Type here...": "Пишите здесь...",
"Comma separated (required)": "Через запятую (обязательное поле)",
"What this keyword should mean to the AI, sent verbatim": "Что это ключевое слово должно означать для ИИ, отправляется дословно",
"What this keyword should mean to the AI, sent verbatim": "Объясните ИИ, что он должен знать об этом ключевом слове",
"Filter to Character(s)": "Фильтр по персонажу(ам)",
"Character Exclusion": "Исключить персонажей",
"Inclusion Group": "Группа записей",
@@ -544,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": "Сменить вид сетки",
@@ -569,12 +574,12 @@
"Remove": "Убрать",
"Select a World Info file for": "Выбрать файл с миром для",
"Primary Lorebook": "Основной лорбук",
"A selected World Info will be bound to this character as its own Lorebook.": "Информация о мире будет привязана к персонажу как его собственный лорбук.",
"When generating an AI reply, it will be combined with the entries from a global World Info selector.": "Когда ИИ генерирует ответ, он будет совмещён с записями из глобально выбранного мира.",
"A selected World Info will be bound to this character as its own Lorebook.": "Данный мир будет привязан к персонажу как его собственный лорбук.",
"When generating an AI reply, it will be combined with the entries from a global World Info selector.": "При генерации ответа, данный лорбук будет работать вместе с глобально выбранным лорбуком.",
"Exporting a character would also export the selected Lorebook file embedded in the JSON data.": "При экспорте персонажа вместе с ним также выгрузится выбранный лорбук в виде JSON.",
"Additional Lorebooks": "Вспомогательные лорбуки",
"Associate one or more auxillary Lorebooks with this character.": "Привязать к этому персонажу один или больше вспомогательных лорбуков",
"NOTE: These choices are optional and won't be preserved on character export!": "ВНИМАНИЕ: эти выборы необязательные и не будут сохранены при экспорте персонажа!",
"Associate one or more auxillary Lorebooks with this character.": "Привязать к этому персонажу один или больше вспомогательных лорбуков.",
"NOTE: These choices are optional and won't be preserved on character export!": "ВНИМАНИЕ: вспомогательные лорбуки не будут выгружены при экспорте персонажа!",
"Rename chat file": "Переименовать чат",
"Export JSONL chat file": "Экспортировать чат в формате JSONL",
"Download chat as plain text document": "Скачать чат в формате .txt",
@@ -713,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": "По размеру контекста",
@@ -784,20 +789,20 @@
"Enable magnification for zoomed avatar display.": "Добавляет возможность приближать увеличенную версию аватарки.",
"Unique to this chat": "Только для текущего чата",
"Checkpoints inherit the Note from their parent, and can be changed individually after that.": "Чекпоинты наследуют заметки от родительского чата, но впоследствие их всегда можно изменить.",
"Include in World Info Scanning": "Учитывать при сканировании Информации о мире",
"Before Main Prompt / Story String": "Перед основным промптом / строкой истории",
"After Main Prompt / Story String": "После основного промпта / строки истории",
"Include in World Info Scanning": "Учитывать при сканировании лорбуком",
"Before Main Prompt / Story String": "Перед основным промптом / общим шаблоном",
"After Main Prompt / Story String": "После основного промпта / общего шаблона",
"In-chat @ Depth": "Встав. на глуб.",
"as": "роль:",
"Insertion Frequency": "Частота вставки",
"(0 = Disable, 1 = Always)": "(0 = никогда, 1 = всегда)",
"User inputs until next insertion:": "Ваших сообщений до след. вставки:",
"Character Author's Note (Private)": "Заметки автора персонажа (личные)",
"Will be automatically added as the author's note for this character. Will be used in groups, but can't be modified when a group chat is open.": "Автоматически применятся к этому персонажу в качестве заметок автора. Будут использоваться в группах, но при активном групповом чате к редактированию недоступны.",
"Use character author's note": "Использовать заметки автора персонажа",
"Replace Author's Note": "Вместо заметок автора",
"Default Author's Note": "Стандартные заметки автора",
"Will be automatically added as the Author's Note for all new chats.": "Будут автоматически добавляться во все новые чаты в качестве Заметок автора",
"Character Author's Note (Private)": "Авторские заметки для персонажа (личные)",
"Will be automatically added as the author's note for this character. Will be used in groups, but can't be modified when a group chat is open.": "Автоматически применятся к этому персонажу в качестве авторских заметок. Будут использоваться в группах, но при активном групповом чате к редактированию недоступны.",
"Use character author's note": "Использовать авторские заметки для персонажа",
"Replace Author's Note": "Вместо авторских заметок",
"Default Author's Note": "Стандартные авторские заметки",
"Will be automatically added as the Author's Note for all new chats.": "Будут автоматически добавляться во все новые чаты в качестве авторских заметок",
"1 = disabled": "1 = откл.",
"write short replies, write replies using past tense": "пиши короткие ответы, пиши в настоящем времени",
"Positive Prompt": "Положительный промпт",
@@ -906,7 +911,7 @@
"ext_sum_force_text": "Пересказать сейчас",
"Disable automatic summary updates. While paused, the summary remains as-is. You can still force an update by pressing the Summarize now button (which is only available with the Main API).": "Отключить авто-обновление пересказа. Пересказ всё время будет фиксированным. Однако останется возможность принудительно обновить пересказ через кнопку \"Пересказать сейчас\" (доступно только через Основное API)",
"ext_sum_pause": "Приостановить",
"Omit World Info and Author's Note from text to be summarized. Only has an effect when using the Main API. The Extras API always omits WI/AN.": "Исключать из пересказа Информацию о мире и Заметки автора. Работает только для Основного API. Extras API всегда их исключает.",
"Omit World Info and Author's Note from text to be summarized. Only has an effect when using the Main API. The Extras API always omits WI/AN.": "Исключать из пересказа Информацию о мире и Авторские заметки. Работает только для Основного API. Extras API всегда их исключает.",
"ext_sum_no_wi_an": "Без мира и заметок",
"ext_sum_settings_tip": "Изменить промпт пересказа, место для инжекта и т.д.",
"ext_sum_settings": "Настройки пересказа",
@@ -1019,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.": "Не добавлять имя персонажа",
@@ -1333,13 +1338,7 @@
"WI_Entry_Status_Normal": "Обычная",
"WI_Entry_Status_Vectorized": "Векторизованная",
"WI_Entry_Status_Disabled": "Отключена",
"Before EM": "↑EM",
"After EM": "↓EM",
"at Depth System": "@D ⚙️",
"at Depth User": "@D 👤",
"at Depth AI": "@D 🤖",
"Depth": "Глубина",
"Trigger %:": "Trigger %:",
"Probability": "Вероятность",
"Duplicate world info entry": "Дублировать запись",
"Delete world info entry": "Удалить запись",
@@ -1411,26 +1410,7 @@
"ext_regex_title": "Regex",
"ext_regex_import_target": "Импортировать в:",
"ext_regex_move_to_scoped": "Сделать локальным",
"Trigger Stable Diffusion": "Trigger Stable Diffusion",
"sd_Yourself": "Yourself",
"sd_Your_Face": "Your Face",
"sd_Me": "Me",
"sd_The_Whole_Story": "The Whole Story",
"sd_The_Last_Message": "The Last Message",
"sd_Raw_Last_Message": "Raw Last Message",
"sd_Background": "Background",
"Image Generation": "Image Generation",
"sd_refine_mode": "Allow to edit prompts manually before sending them to generation API",
"sd_refine_mode_txt": "Edit prompts before generation",
"sd_interactive_mode": "Automatically generate images when sending messages like 'send me a picture of cat'.",
"sd_interactive_mode_txt": "Interactive mode",
"sd_multimodal_captioning": "Use multimodal captioning to generate prompts for user and character portraits based on their avatars.",
"sd_multimodal_captioning_txt": "Use multimodal captioning for portraits",
"sd_expand": "Automatically extend prompts using text generation model",
"sd_expand_txt": "Auto-enhance prompts",
"sd_snap": "Snap generation requests with a forced aspect ratio (portraits, backgrounds) to the nearest known resolution, while trying to preserve the absolute pixel counts (recommended for SDXL).",
"sd_snap_txt": "Snap auto-adjusted resolutions",
"Source": "Source",
"sd_auto_url": "Example: {{auto_url}}",
"Authentication (optional)": "Authentication (optional)",
"Example: username:password": "Example: username:password",
@@ -1441,18 +1421,10 @@
"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.",
"sd_vlad_url": "Example: {{vlad_url}}",
"The server must be accessible from the SillyTavern host machine.": "The server must be accessible from the SillyTavern host machine.",
"Hint: Save an API key in AI Horde API settings to use it here.": "Hint: Save an API key in AI Horde API settings to use it here.",
"Allow NSFW images from Horde": "Разрешить NSFW-картинки в Horde",
"Sanitize prompts (recommended)": "Sanitize prompts (recommended)",
"Automatically adjust generation parameters to ensure free image generations.": "Automatically adjust generation parameters to ensure free image generations.",
"Avoid spending Anlas": "Avoid spending Anlas",
"Opus tier": "(Opus tier)",
"View my Anlas": "View my Anlas",
"These settings only apply to DALL-E 3": "These settings only apply to DALL-E 3",
"Image Style": "Image Style",
"Image Quality": "Image Quality",
"Standard": "Standard",
"HD": "HD",
"sd_comfy_url": "Example: {{comfy_url}}",
"Open workflow editor": "Open workflow editor",
"Create new workflow": "Create new workflow",
@@ -1460,9 +1432,6 @@
"Enhance": "Enhance",
"Refine": "Refine",
"Decrisper": "Decrisper",
"Sampling steps": "Sampling steps ()",
"Width": "Width ()",
"Height": "Height ()",
"Resolution": "Resolution",
"Model": "Model",
"Sampling method": "Sampling method",
@@ -1472,8 +1441,6 @@
"DYN variants of SMEA samplers often lead to more varied output, but may fail at very high resolutions.": "DYN variants of SMEA samplers often lead to more varied output, but may fail at very high resolutions.",
"DYN": "DYN",
"Scheduler": "Scheduler",
"Restore Faces": "Restore Faces",
"Hires. Fix": "Hires. Fix",
"Upscaler": "Upscaler",
"Upscale by": "Upscale by",
"Denoising strength": "Denoising strength",
@@ -1484,7 +1451,6 @@
"Delete style": "Delete style",
"Common prompt prefix": "Common prompt prefix",
"sd_prompt_prefix_placeholder": "Use {prompt} to specify where the generated prompt will be inserted",
"Negative common prompt prefix": "Negative common prompt prefix",
"Character-specific prompt prefix": "Character-specific prompt prefix",
"Won't be used in groups.": "Won't be used in groups.",
"sd_character_prompt_placeholder": "Any characteristics that describe the currently selected character. Will be added after a common prompt prefix.\nExample: female, green eyes, brown hair, pink shirt",
@@ -1655,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": "Удалить сообщение",
@@ -1836,13 +1802,13 @@
"Also delete the chat files": "Также удалить файлы чатов",
"Delete the character?": "Удалить персонажа?",
"Not a valid number": "Некорректное число",
"Author's Note depth updated": "Глубина заметок автора обновлена",
"Author's Note frequency updated": "Частота заметок автора обновлена",
"Author's Note depth updated": "Глубина авторских заметок обновлена",
"Author's Note frequency updated": "Частота авторских заметок обновлена",
"Not a valid position": "Некорректная позиция",
"Author's Note position updated": "Позиция заметок автора обновлена",
"Something went wrong. Could not save character's author's note.": "Что-то пошло не так. Не удалось сохранить заметки автора для этого персонажа.",
"Author's Note position updated": "Позиция авторских заметок обновлена",
"Something went wrong. Could not save character's author's note.": "Что-то пошло не так. Не удалось сохранить авторские заметки для этого персонажа.",
"Select a character before trying to use Author's Note": "Сначала необходимо выбрать персонажа",
"Author's Note text updated": "Текст заметок автора обновлён",
"Author's Note text updated": "Текст авторских заметок обновлён",
"Group Validation": "Валидация группы",
"Warning: Listed member ${0} does not exist as a character. It will be removed from the group.": "Предупреждение: персонаж ${0} не существует в виде карточки. Он будет удалён из группы.",
"Group Chat could not be saved": "Не удалось сохранить групповой чат",
@@ -1938,7 +1904,7 @@
"Do you want to remove these fields before exporting?": "Желаете ли удалить эти поля перед экспортом?",
"Save": "Сохранить",
"Chat Lorebook": "Лорбук для чата",
"chat_world_template_txt": "Выбранный мир будет привязан к этому чату. Будет добавляться в промпт наряду с глобальным лорбуком и лором персонажа.",
"chat_world_template_txt": "Выбранный мир будет привязан к этому чату. Будет работать наряду с глобальным лорбуком и лором персонажа.",
"world_button_title": "Лор персонажа\n\nНажмите, чтобы загрузить\nShift + ЛКМ, чтобы открыть диалог привязки мира",
"No auxillary Lorebooks set. Click here to select.": "Вспомогательный лорбук не выбран. Нажмите, чтобы выбрать.",
"ext_regex_user_input_desc": "Отправленные вами сообщения.",
@@ -2010,8 +1976,8 @@
"Imported tags:": "Импортируемые теги:",
"Importing Tags": "Импорт тегов",
"Couldn't import tags:": "Не удалось импортировать теги:",
"Allow fallback models": "Разрешить fallback-модели",
"Allow fallback providers": "Разрешить fallback-провайдеров",
"Allow fallback models": "Разрешить резервные модели",
"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": "Провайдеры моделей",
@@ -2028,6 +1994,8 @@
"Click on the setting name to omit it from the profile.": "Нажмите на название настройки, чтобы исключить её из профиля",
"Included settings:": "Сохранённые параметры:",
"Server URL": "Адрес сервера",
"Electron Hub API Key": "Ключ от API Electron Hub",
"Electron Hub Model": "Модель Electron Hub",
"NanoGPT API Key": "Ключ от API NanoGPT",
"NanoGPT Model": "Модель NanoGPT",
"Use extension settings": "Использовать настройки из расширения",
@@ -2044,14 +2012,14 @@
"Title/Memo": "Название",
"Strategy": "Статус",
"Position": "Позиция",
"Trigger %": "% срабатывания",
"Trigger %": "% срабатываний",
"Use global": "Глоб. настройка",
"Whole Words": "Целые слова",
"Non-recursable": "Не рекурсивная",
"Delay until recursion": "Рекурсивная",
"Toggle entry's active state.": "Вкл/выкл запись.",
"Prioritize": "Важная",
"Prioritize this entry: When checked, this entry is prioritized out of all selections.If multiple are prioritized, the one with the highest 'Order' is chosen.": "Важная запись получает приоритет среди всех выбранных. Если важных записей несколько, выбирается та, у которой выше \"Очерёдность\".",
"Prioritize this entry: When checked, this entry is prioritized out of all selections.If multiple are prioritized, the one with the highest 'Order' is chosen.": "Важная запись получает приоритет среди всех выбранных. Если важных записей несколько, выбирается та, у которой выше \"Приоритет\".",
"Group Weight": "Вес в группе",
"A relative likelihood of entry activation within the group": "Относительная вероятность активации записи в рамках группы",
"Sticky": "Липучка",
@@ -2067,7 +2035,7 @@
"Switch to plaintext mode": "Вкл/выкл режим чистого текста",
"Exclude": "Режим исключения",
"Switch the Character/Tags filter around to exclude the listed characters and tags from matching for this entry": "Инвертировать логику: для выбранных в фильтре персонажей/тегов данная запись активна НЕ БУДЕТ",
"Apply current sorting as Order": "Настроить Очерёдность в соответствии с текущей сортировкой",
"Apply current sorting as Order": "Настроить Приоритет в соответствии с текущей сортировкой",
"Create a new World Info": "Создать новый мир",
"Enter a name for the new file:": "Название нового файла:",
"Inclusion Groups ensure only one entry from a group is activated at a time, if multiple are triggered.Documentation: World Info - Inclusion Group": "Если сразу несколько записей из одной группы окажутся активированными, по факту сработает только одна. Одна запись может входить в несколько групп, отделяются запятыми. Раздел в документации: World Info - Inclusion Group",
@@ -2165,7 +2133,7 @@
"openai_reasoning_effort_high": "Подробные",
"Persona Lore Alt+Click to open the lorebook": "Лорбук данной персоны\nAlt + ЛКМ чтобы открыть лорбук",
"Persona Lorebook for": "Лорбук для персоны",
"persona_world_template_txt": "Выбранная Информация о мире будет привязана к этой персоне. Информация будет добавляться в каждом промпте вместе с глобальным лорбуком и лорбуками персонажа и чата.",
"persona_world_template_txt": "Выбранный мир будет привязан к этой персоне. Будет работать вместе с глобальным лорбуком и лорбуками персонажа и чата.",
"Global list": "Глобальный список",
"Preset-specific list": "Список для данного пресета",
"Banned tokens/strings are being sent in the request.": "Запрещённые токены и строки отсылаются в запросе.",
@@ -2280,7 +2248,7 @@
"Character Words": "Слов отправлено персонажем",
"stats_header_User": "пользователю",
"stats_header_Character": "персонажу",
"${0} Stats": "Статистика по ${0}",
"${0} Stats": "Статистика по ${0}",
"Context": "Контекст",
"Response": "Ответ",
"Connected": "Подключено",
@@ -2438,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": "Добавить ключ",
@@ -2465,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",
@@ -2521,6 +2489,16 @@
"Automatically generated chat backups.": "Автоматически создаваемые бэкапы чатов.",
"Settings Backups": "Копии настроек",
"Automatically generated settings backups.": "Автоматически создаваемые бэкапы настроек.",
"Files": "Файлы",
"Files that are not associated with chat messages or Data Bank. WILL DELETE MANUAL UPLOADS!": "Файлы, не связанные ни с одним сообщением или банком данных. ЗАГРУЖЕННЫЕ ВРУЧНУЮ ФАЙЛЫ ТАКЖЕ БУДУТ УДАЛЕНЫ!",
"Images": "Изображения",
"Images that are not associated with chat messages. WILL DELETE MANUAL UPLOADS!": "Картинки, не связанные ни с одним сообщением. ЗАГРУЖЕННЫЕ ВРУЧНУЮ ФАЙЛЫ ТАКЖЕ БУДУТ УДАЛЕНЫ!",
"Avatar Thumbnails": "Превью для аватарок",
"Thumbnails for avatars of missing or deleted characters.": "Превью для аватарок удалённых персонажей",
"Background Thumbnails": "Превью для фонов",
"Thumbnails for missing or deleted backgrounds.": "Превью для удалённых фоновых изображений",
"Persona Thumbnails": "Превью для персон",
"Thumbnails for missing or deleted personas.": "Превью для удалённых персон",
"Delete all items in this category": "Удалить всё в этой категории",
"View item content": "Посмотреть содержимое",
"Download item": "Скачать содержимое",
@@ -2570,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": "Свайп",
@@ -2583,5 +2561,188 @@
"Moonshot AI API Key": "Ключ от API Moonshot AI",
"Moonshot AI Model": "Модель Moonshot AI",
"AI/ML API Key": "Ключ от API AI/ML",
"AI/ML Model": "Модель AI/ML"
"AI/ML Model": "Модель AI/ML",
"Replace Character": "Заменить персонажа",
"Choose a new character card to replace this character with.": "Выберите, каким персонажем хотите заменить текущего.",
"All chats, assets and group memberships will be preserved, but local changes to the character data will be lost.": "Чаты с персонажем, его ассеты и членство в группах сохранятся. Однако сделанные вами изменения в карточке будут утеряны.",
"Proceed?": "Продолжить?",
"No Creator's Notes provided.": "Создатель не оставил примечаний.",
"No auxiliary Lorebooks set. Click here to select.": "Вспомогательных лорбуков нет. ЛКМ, чтобы выбрать.",
"Persona Title (optional, display only)": "Сноска (не влияет на чат, только в интерфейсе)",
"This entry will not be recursively activated by other entries.": "Не будет активироваться другими записями.",
"This entry will not activate other entries recursively.": "Не будет активировать другие записи.",
"This entry can only be activated on recursive checking.": "Активируется только другими записями.",
"This entry will be included ignoring budget constraints, assuming all other checks pass.": "Будет включена в промпт даже при превышении бюджета токенов (при условии, что все остальные условия соблюдены)",
"Ignore budget": "Игнорировать бюджет",
"Filter to Generation Triggers": "Только для опред. типов генераций",
"Apply current sorting as Order": "Выставить приоритеты по текущей сортировке",
"Apply your current sorting to the \"Order\" field. The Order values will go down from the chosen number.": "Заполнить поле \"Приоритет\" в соответствии с текущей сортировкой для всех записей. Поля будут заполнены значениями, начиная с этого числа:",
"More than 100 entries in this world. If you don't choose a number higher than that, the lower entries will default to 0.<br />(Usual default: 100)<br />Minimum: ${0}": "В этом лорбуке больше 100 записей! Если не выставить число больше 100, то последние записи будут иметь приоритет 0.<br/>(Стандартное значение: 100)<br/>(Минимальное число: ${0})",
"Apply": "Применить",
"Apply Current Sorting": "Выставить приоритеты по сортировке",
"Delete the entry with UID: ${0}?": "Удалить запись с UID: ${0}?",
"This action is irreversible!": "Отменить будет невозможно!",
"Recursion Level": "Уровень рекурсии",
"delay_until_recursion_level": "Насколько глубоко должна зайти рекурсия, чтобы иметь возможность активировать эту запись.\n\nИзначально рекурсия делает проход по 1 уровню. Если там не находится подходящих записей, то она идёт на 2 уровень, и там повторяет процесс.\nИ так, пока не дойдёт до самого глубокого уровня.\n\nАктуально только для рекурсивных записей (с отмеченной галочкой \"Рекурсивная\").",
"A number lower than the entry count has been chosen. All entries below that will default to 0.": "Введённое число меньше, чем общее кол-во записей. Всем записям внизу списка присвоен приоритет 0.",
"Invalid number: ${0}": "Некорректное число: ${0}",
"Allow animations for WEBP backgrounds. This is only a change for the selection menu.": "Разрешить анимации в WEBP фонах. Актуально только для меню выбора.",
"sd_refine_mode_txt": "Редактировать промпты перед генерацией",
"sd_refine_mode": "Отправлять промпты на проверку вам, прежде чем пересылать в API",
"sd_function_tool_txt": "Использовать вызов функций",
"sd_function_tool": "Использовать функцию, чтобы понимать, когда пора генерировать изображение",
"sd_interactive_mode_txt": "Интерактивный режим",
"sd_interactive_mode": "Автоматически генерировать изображения, когда появляется сообщение вида \"send me a picture of a cat\"",
"sd_multimodal_captioning_txt": "Мультимодальный промптинг",
"sd_multimodal_captioning": "Использовать мультимодальный промптинг для создания портретов пользователя и персонажа, основываясь на их аватарках",
"sd_free_extend_txt": "Дописывать промпты в свободном режиме",
"sd_free_extend_small": "(для интерактивного режима или команд)",
"sd_free_extend": "Автоматически дописывать промпты в свободном режиме (для всего, что не касается фонов и портретов), используя текущую выбранную LLM",
"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, чтобы автоматически подтянуть его сюда.",
"Sanitize prompts (recommended)": "Прогонять промпты через санитайзер (рекомендуется)",
"Sampling method": "Метод сэмплинга",
"Resolution": "Целевое разрешение",
"Sampling steps": "Кол-во шагов",
"Width": "Ширина",
"Height": "Высота",
"Not all samplers supported.": "Поддерживает не все виды сэмплинга.",
"(-1 for random)": "(-1 для случайного)",
"Common prompt prefix": "Фиксированный префикс для промптов",
"Preset for prompt prefix and negative prompt": "Пресет для префиксов промпта и для негативных промптов",
"Style": "Стиль",
"Negative common prompt prefix": "Фиксированный префикс для негативных промптов",
"Chat Message Visibility (by source)": "Видимость сообщений в чате (по источникам)",
"Uncheck to hide the extension's messages in chat prompts.": "Снимите галочку, чтобы скрыть из промптов сообщения, приходящие из этого источника.",
"Extensions Menu": "Меню расширений",
"Slash Command": "Слэш-команды",
"Interactive Mode": "Интерактивный режим",
"Function Tool": "Функция",
"Save style": "Сохранить стиль",
"Delete style": "Удалить стиль",
"Are you sure you want to delete the style \"${0}\"?": "Вы точно хотите удалить стиль \"${0}\"?",
"API Key": "Ключ от API",
"These settings only apply to DALL-E 3": "Данные настройки применяются только для DALL-E 3",
"Image Style": "Стиль изображения",
"Image Quality": "Качество изображения",
"Standard": "Стандарт",
"sd_res_512x512": "512x512 (1:1, иконки, аватарки)",
"sd_res_600x600": "600x600(1:1, иконки, аватарки)",
"sd_res_512x768": "512x768 (2:3, вертикальная аватарка для карточки)",
"sd_res_768x512": "768x512 (3:2, 35мм плёнка для кинофильмов, альбомн. ориентация)",
"sd_res_960x540": "960x540 (16:9, обои, альбомн. ориентация)",
"sd_res_540x960": "540x960 (9:16, обои, книжн. ориентация)",
"sd_res_1920x1088": "1920x1088 (16:9, обои, альбомн. ориентация)",
"sd_res_1088x1920": "1088x1920 (9:16, обои, книжн. ориентация)",
"sd_res_1280x720": "1280x720 (16:9, обои, альбомн. ориентация)",
"sd_res_720x1280": "720x1280 (9:16, обои, книжн. ориентация)",
"Click to set": "Нажмите чтобы задать",
"Prompt Upsampling": "Применять Prompt Upsampling",
"Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation.": "При активации автоматически модифицирует промпт, чтобы сделать процесс генерации более креативным.",
"Important:": "Важно:",
"The server must be accessible from the SillyTavern host machine.": " Адрес должен быть доступен с сервера SillyTavern.",
"Open workflow editor": "Открыть редактор воркфлоу",
"Create new workflow": "Создать новый воркфлоу",
"Delete workflow": "Удалить воркфлоу",
"Delete the workflow? This action is irreversible.": "Удалить этот воркфлоу? Отменить будет невозможно.",
"Swap width and height": "Поменять местами ширину и высоту",
"Authentication (optional)": "Данные для аутентификации (необязательно)",
"sd_auto_auth_warning_1": " запускайте Stable Diffusion с флагом",
"sd_auto_auth_warning_2": "! Адрес SD должен быть доступен с сервера SillyTavern.",
"Upscale by": "Множитель апскейлинга",
"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": "Доступные голоса"
}
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "прапорцем",
"API key (optional)": "Ключ API (необов'язково)",
"Server url": "URL-адреса сервера",
"Electron Hub API Key": "Ключ API для Electron Hub",
"Electron Hub Model": "Модель Electron Hub",
"Example: http://127.0.0.1:5000": "Приклад: http://127.0.0.1:5000",
"Custom model (optional)": "Власна модель (необов'язково)",
"vllm-project/vllm": "vllm-project/vllm (режим оболонки OpenAI API)",
@@ -367,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": "Розмір контексту",
+3 -1
View File
@@ -317,6 +317,8 @@
"flag": "cờ",
"API key (optional)": "Key API (tùy chọn)",
"Server url": "URL máy chủ",
"Electron Hub API Key": "Key API Electron Hub",
"Electron Hub Model": "Model Electron Hub",
"Example: http://127.0.0.1:5000": "Ví dụ: http://127.0.0.1:5000",
"Custom model (optional)": "Model tùy chỉnh (tùy chọn)",
"vllm-project/vllm": "vllm-project/vllm (Chế độ trình bao bọc API OpenAI)",
@@ -367,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",
+396 -188
View File
File diff suppressed because it is too large Load Diff
+4 -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": "從不",
@@ -1791,6 +1791,8 @@
"Derive context size from backend": "從後端推導上下文大小",
"Using a proxy that you're not running yourself is a risk to your data privacy.": "使用非自行管理的代理服務可能導致您的資料隱私外洩。",
"Claude API Key": "Claude API 金鑰",
"Electron Hub API Key": "Electron Hub API 金鑰",
"Electron Hub Model": "Electron Hub 模型",
"NanoGPT API Key": "NanoGPT API 金鑰",
"NanoGPT Model": "NanoGPT 模型",
"context_derived": "若可能,根據模型後設資料推導。",
+1 -1
View File
@@ -84,7 +84,7 @@
</div>
<script src="lib/jquery-3.5.1.min.js"></script>
<script src="scripts/login.js"></script>
<script src="scripts/login.js" type="module"></script>
</body>
</html>
+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"
}
]
}
+401 -278
View File
File diff suppressed because it is too large Load Diff
+55 -43
View File
@@ -402,6 +402,7 @@ function RA_autoconnect(PrevApi) {
|| (secret_state[SECRET_KEYS.COHERE] && oai_settings.chat_completion_source == chat_completion_sources.COHERE)
|| (secret_state[SECRET_KEYS.PERPLEXITY] && oai_settings.chat_completion_source == chat_completion_sources.PERPLEXITY)
|| (secret_state[SECRET_KEYS.GROQ] && oai_settings.chat_completion_source == chat_completion_sources.GROQ)
|| (secret_state[SECRET_KEYS.ELECTRONHUB] && oai_settings.chat_completion_source == chat_completion_sources.ELECTRONHUB)
|| (secret_state[SECRET_KEYS.NANOGPT] && oai_settings.chat_completion_source == chat_completion_sources.NANOGPT)
|| (secret_state[SECRET_KEYS.DEEPSEEK] && oai_settings.chat_completion_source == chat_completion_sources.DEEPSEEK)
|| (secret_state[SECRET_KEYS.XAI] && oai_settings.chat_completion_source == chat_completion_sources.XAI)
@@ -411,6 +412,7 @@ function RA_autoconnect(PrevApi) {
|| (secret_state[SECRET_KEYS.COMETAPI] && oai_settings.chat_completion_source == chat_completion_sources.COMETAPI)
|| (oai_settings.chat_completion_source === chat_completion_sources.POLLINATIONS)
|| (isValidUrl(oai_settings.custom_url) && oai_settings.chat_completion_source == chat_completion_sources.CUSTOM)
|| (secret_state[SECRET_KEYS.AZURE_OPENAI] && oai_settings.chat_completion_source == chat_completion_sources.AZURE_OPENAI)
) {
$('#api_button_openai').trigger('click');
}
@@ -480,8 +482,7 @@ export function dragElement($elmnt) {
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
let height, width, top, left, right, bottom,
maxX, maxY, winHeight, winWidth,
topbar;
maxX, maxY, winHeight, winWidth;
const elmntName = $elmnt.attr('id');
const elmntNameEscaped = $.escapeSelector(elmntName);
@@ -540,11 +541,6 @@ export function dragElement($elmnt) {
winWidth = window.innerWidth;
winHeight = window.innerHeight;
topbar = document.getElementById('top-bar');
const topbarstyle = getComputedStyle(topbar);
topBarFirstX = parseInt(topbarstyle.marginInline);
topBarLastY = parseInt(topbarstyle.height);
// Prepare state object if missing
if (!power_user.movingUIState[elmntName]) power_user.movingUIState[elmntName] = {};
@@ -770,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 () {
@@ -1066,6 +1065,19 @@ export function initRossMods() {
$('#option_regenerate').trigger('click');
$('#options').hide();
}
// If there is input text, we do not trigger a regenerate - we just send it
if ($('#send_textarea').val() !== '') {
if (shouldSendOnEnter()) {
console.debug('Sending with Ctrl+Enter');
event.preventDefault();
sendTextareaMessage();
} else {
console.debug('Text area is not empty, but send on enter is disabled');
}
return;
}
if (skipConfirm) {
doRegenerate();
} else {
+116
View File
@@ -0,0 +1,116 @@
/**
* Shared module between login and main app.
* Be careful what you import!
*/
const buttonSelectors = [
'.menu_button',
'.right_menu_button',
'.mes_button',
'.drawer-icon',
'.inline-drawer-icon',
'.swipe_left',
'.swipe_right',
'.character_select',
'.tags .tag',
'.jg-menu .jg-button',
'.bg_example .mobile-only-menu-toggle',
'.paginationjs-pages li a',
].join(', ');
const listSelectors = [
'.options-content',
'.list-group',
'#rm_print_characters_block',
'#rm_group_members',
'#rm_group_add_members',
'.tag_view_list_tags',
'.secretKeyManagerList',
'.recentChatList',
'.dataMaidCategoryContent',
'#userList',
'.bg_list',
].join(', ');
const listItemSelectors = [
'.options-content .list-group-item',
'.list-group .list-group-item',
'#rm_print_characters_block .entity_block',
'#rm_group_members .group_member',
'#rm_group_add_members .group_member',
'.tag_view_list_tags .tag_view_item',
'.secretKeyManagerList .secretKeyManagerItem',
'.recentChatList .recentChat',
'.dataMaidCategoryContent .dataMaidItem',
'#userList .userSelect',
'.bg_list .bg_example',
].join(', ');
const toolbarSelectors = [
'.jg-menu',
].join(', ');
/** @type {Record<string, (element: Element) => void>} */
const a11yRules = {
[buttonSelectors]: (element) => {
element.setAttribute('role', 'button');
},
[listSelectors]: (element) => {
element.setAttribute('role', 'list');
},
[listItemSelectors]: (element) => {
element.setAttribute('role', 'listitem');
},
[toolbarSelectors]: (element) => {
element.setAttribute('role', 'toolbar');
},
'#toast-container .toast': (element) => {
element.setAttribute('role', 'status');
},
};
/**
* Apply accessibility rules to an element.
* @param {Element} element Element to process.
*/
function applyA11yRules(element) {
try {
for (const [selector, rule] of Object.entries(a11yRules)) {
// Apply if the element directly matches the selector
if (element.matches(selector)) {
rule(element);
}
// Apply the rule to descendants
element.querySelectorAll(selector).forEach(rule);
}
} catch (error) {
console.error('Error applying accessibility rules to element:', element, error);
}
}
function setAccessibilityObserver() {
// Apply for existing elements
applyA11yRules(document.body);
// Setup observer for dynamic content
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
for (const addedNode of mutation.addedNodes) {
if (addedNode instanceof Element && addedNode.nodeType === Node.ELEMENT_NODE) {
applyA11yRules(addedNode);
}
}
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
}
export function initAccessibility() {
setAccessibilityObserver();
}
+294 -185
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();
}
/**
@@ -265,9 +271,10 @@ async function onCopyToSystemBackgroundClick(e) {
* It caches the thumbnail in local storage and returns a blob URL for the thumbnail.
* If the thumbnail cannot be fetched, it returns a transparent PNG pixel as a fallback.
* @param {string} bg Background URL
* @param {boolean} isCustom Is the background custom?
* @returns {Promise<string>} Blob URL of the thumbnail
*/
async function getThumbnailFromStorage(bg) {
async function getThumbnailFromStorage(bg, isCustom) {
const cachedBlobUrl = THUMBNAIL_BLOBS.get(bg);
if (cachedBlobUrl) {
return cachedBlobUrl;
@@ -281,7 +288,8 @@ async function getThumbnailFromStorage(bg) {
}
try {
const response = await fetch(getBackgroundPath(bg), { cache: 'force-cache' });
const url = isCustom ? bg : getBackgroundPath(bg);
const response = await fetch(url, { cache: 'force-cache' });
if (!response.ok) {
throw new Error('Fetch failed with status: ' + response.status);
}
@@ -380,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();
}
}
@@ -443,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',
@@ -452,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();
}
}
@@ -479,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);
@@ -519,7 +573,7 @@ async function resolveImageUrl(bg, isCustom) {
const fileExtension = bg.split('.').pop().toLowerCase();
const isAnimated = ['mp4', 'webp'].includes(fileExtension);
const thumbnailUrl = isAnimated && !background_settings.animation
? await getThumbnailFromStorage(bg)
? await getThumbnailFromStorage(bg, isCustom)
: isCustom
? bg
: getThumbnailUrl('bg', bg);
@@ -527,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();
@@ -573,14 +608,21 @@ async function delBackground(bg) {
}
async function onBackgroundUploadSelected() {
const form = $('#form_bg_download').get(0);
const form = $('#form_bg_upload').get(0);
if (!(form instanceof HTMLFormElement)) {
console.error('form_bg_download is not a form');
console.error('form_bg_upload is not a form');
return;
}
const formData = new FormData(form);
const file = formData.get('avatar');
if (!(file instanceof File) || file.size === 0) {
form.reset();
return;
}
await convertFileIfVideo(formData);
await uploadBackground(formData);
form.reset();
@@ -614,7 +656,7 @@ async function convertFileIfVideo(formData) {
const sourceBuffer = await file.arrayBuffer();
const convertedBuffer = await globalThis.convertVideoToAnimatedWebp({ buffer: new Uint8Array(sourceBuffer), name: file.name });
const convertedFileName = file.name.replace(/\.[^/.]+$/, '.webp');
const convertedFile = new File([convertedBuffer], convertedFileName, { type: 'image/webp' });
const convertedFile = new File([new Uint8Array(convertedBuffer)], convertedFileName, { type: 'image/webp' });
formData.set('avatar', convertedFile);
toastMessage.remove();
} catch (error) {
@@ -671,46 +713,107 @@ 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);
$(document).on('click', '.bg_example', onSelectBackgroundClick);
$(document).on('click', '.bg_example_lock', onLockBackgroundClick);
$(document).on('click', '.bg_example_unlock', onUnlockBackgroundClick);
$(document).on('click', '.bg_example_edit', onRenameBackgroundClick);
$(document).on('click', '.bg_example_cross', onDeleteBackgroundClick);
$(document).on('click', '.bg_example_copy', onCopyToSystemBackgroundClick);
$(document)
.off('click', '.bg_example').on('click', '.bg_example', onSelectBackgroundClick)
.off('click', '.bg_example .mobile-only-menu-toggle').on('click', '.bg_example .mobile-only-menu-toggle', function (e) {
e.stopPropagation();
const $context = $(this).closest('.bg_example');
const wasOpen = $context.hasClass('mobile-menu-open');
// Close all other open menus before opening a new one.
$('.bg_example.mobile-menu-open').removeClass('mobile-menu-open');
if (!wasOpen) {
$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');
switch (action) {
case 'lock':
onLockBackgroundClick.call(this, e.originalEvent);
break;
case 'unlock':
onUnlockBackgroundClick.call(this, e.originalEvent);
break;
case 'edit':
onRenameBackgroundClick.call(this, e.originalEvent);
break;
case 'delete':
onDeleteBackgroundClick.call(this, e.originalEvent);
break;
case 'copy':
onCopyToSystemBackgroundClick.call(this, e.originalEvent);
break;
}
});
$('#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',
}));
@@ -735,4 +838,10 @@ export function initBackgrounds() {
await getBackgrounds();
await onChatChanged();
});
setupScrollToTop({
scrollContainerId: 'bg-scrollable-content',
buttonId: 'bg-scroll-top',
drawerId: 'Backgrounds',
});
}
+30 -4
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())
@@ -1758,7 +1757,34 @@ export function addDOMPurifyHooks() {
// Replace line breaks with <br> in unknown elements
if (node instanceof HTMLUnknownElement) {
node.innerHTML = node.innerHTML.trim().replaceAll('\n', '<br>');
node.innerHTML = node.innerHTML.trim();
/** @type {Text[]} */
const candidates = [];
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const textNode = /** @type {Text} */ (walker.currentNode);
if (!textNode.data.includes('\n')) continue;
// Skip if this text node is within a <pre> (any ancestor)
if (textNode.parentElement && textNode.parentElement.closest('pre')) continue;
candidates.push(textNode);
}
for (const textNode of candidates) {
const parts = textNode.data.split('\n');
const frag = document.createDocumentFragment();
parts.forEach((part, idx) => {
if (part.length) {
frag.appendChild(document.createTextNode(part));
}
if (idx < parts.length - 1) {
frag.appendChild(document.createElement('br'));
}
});
textNode.replaceWith(frag);
}
}
const isMediaAllowed = isExternalMediaAllowed();
+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 });
}
+52 -16
View File
@@ -33,22 +33,37 @@ const observer = new MutationObserver(mutations => {
* @param {boolean} [options.fromExtension=false] - Indicates if the styles are from an extension
*/
function applyDynamicFocusStyles(styleSheet, { fromExtension = false } = {}) {
/** @type {{baseSelector: string, rule: CSSStyleRule}[]} */
/** @typedef {{ type: 'media'|'supports'|'container', conditionText: string }} WrapperCond */
/** @type {{baseSelector: string, rule: CSSStyleRule, wrappers: WrapperCond[]}[]} */
const hoverRules = [];
/** @type {Set<string>} */
const focusRules = new Set();
const PLACEHOLDER = ':__PLACEHOLDER__';
/**
* Builds a stable signature string for a chain of wrapper conditions so we can distinguish
* identical selectors under different contexts (e.g., different @media queries)
* @param {WrapperCond[]} wrappers
* @returns {string}
*/
function wrapperSignature(wrappers) {
return wrappers.map(w => `${w.type}:${w.conditionText}`).join(';');
}
/**
* Processes the CSS rules and separates selectors for hover and focus
* @param {CSSRuleList} rules - The CSS rules to process
* @param {WrapperCond[]} wrappers - Current chain of wrapper conditions (@media/@supports/etc.)
*/
function processRules(rules) {
function processRules(rules, wrappers = []) {
Array.from(rules).forEach(rule => {
if (rule instanceof CSSImportRule) {
// Make sure that @import rules are processed recursively
processImportedStylesheet(rule.styleSheet);
// If the @import has media conditions, treat them as wrappers as well
/** @type {WrapperCond[]} */
const extra = (rule.media && rule.media.mediaText) ? [{ type: 'media', conditionText: rule.media.mediaText }] : [];
processImportedStylesheet(rule.styleSheet, [...wrappers, ...extra]);
} else if (rule instanceof CSSStyleRule) {
// Separate multiple selectors on a rule
const selectors = rule.selectorText.split(',').map(s => s.trim());
@@ -60,17 +75,25 @@ function applyDynamicFocusStyles(styleSheet, { fromExtension = false } = {}) {
// We currently do nothing here. Rules containing both hover and focus are very specific and should never be automatically touched
}
else if (isHover) {
const baseSelector = selector.replace(':hover', PLACEHOLDER).trim();
hoverRules.push({ baseSelector, rule });
const baseSelector = selector.replace(/:hover/g, PLACEHOLDER).trim();
hoverRules.push({ baseSelector, rule, wrappers: [...wrappers] });
} else if (isFocus) {
// We need to make sure that we remember all existing :focus, :focus-within and :focus-visible rules
const baseSelector = selector.replace(':focus-within', PLACEHOLDER).replace(':focus-visible', PLACEHOLDER).replace(':focus', PLACEHOLDER).trim();
focusRules.add(baseSelector);
const baseSelector = selector.replace(/:focus(-within|-visible)?/g, PLACEHOLDER).trim();
focusRules.add(`${baseSelector}|${wrapperSignature(wrappers)}`);
}
});
} else if (rule instanceof CSSMediaRule || rule instanceof CSSSupportsRule) {
// Recursively process nested rules
processRules(rule.cssRules);
} else if (rule instanceof CSSMediaRule) {
// Recursively process nested @media rules
processRules(rule.cssRules, [...wrappers, { type: 'media', conditionText: rule.conditionText }]);
} else if (rule instanceof CSSSupportsRule) {
// Recursively process nested @supports rules
processRules(rule.cssRules, [...wrappers, { type: 'supports', conditionText: rule.conditionText }]);
} else if (rule instanceof window.CSSContainerRule) {
// Recursively process nested @container rules (if supported by the browser)
// Note: conditionText contains the query like "(min-width: 300px)" or "style(color)"
// Using 'container' as the type ensures uniqueness separate from @media/@supports
processRules(rule.cssRules, [...wrappers, { type: 'container', conditionText: rule.conditionText }]);
}
});
}
@@ -78,21 +101,22 @@ function applyDynamicFocusStyles(styleSheet, { fromExtension = false } = {}) {
/**
* Processes the CSS rules of an imported stylesheet recursively
* @param {CSSStyleSheet} sheet - The imported stylesheet to process
* @param {WrapperCond[]} wrappers - Wrapper conditions inherited from (at)import media
*/
function processImportedStylesheet(sheet) {
function processImportedStylesheet(sheet, wrappers = []) {
if (sheet && sheet.cssRules) {
processRules(sheet.cssRules);
processRules(sheet.cssRules, wrappers);
}
}
processRules(styleSheet.cssRules);
processRules(styleSheet.cssRules, []);
/** @type {CSSStyleSheet} */
let targetStyleSheet = null;
// Now finally create the dynamic focus rules
hoverRules.forEach(({ baseSelector, rule }) => {
if (!focusRules.has(baseSelector)) {
hoverRules.forEach(({ baseSelector, rule, wrappers }) => {
if (!focusRules.has(`${baseSelector}|${wrapperSignature(wrappers)}`)) {
// Only initialize the dynamic stylesheet if needed
targetStyleSheet ??= getDynamicStyleSheet({ fromExtension });
@@ -103,7 +127,19 @@ function applyDynamicFocusStyles(styleSheet, { fromExtension = false } = {}) {
// If something like :focus-within or a more specific selector like `.blah:has(:focus-visible)` for elements inside,
// it should be manually defined in CSS.
const focusSelector = rule.selectorText.replace(/:hover/g, ':focus-visible');
const focusRule = `${focusSelector} { ${rule.style.cssText} }`;
let focusRule = `${focusSelector} { ${rule.style.cssText} }`;
// Wrap the generated rule into the same @media/@supports/@container chain (if any)
if (wrappers.length > 0) {
// Build nested blocks from outermost to innermost
// Example: @media (x) { @supports (y) { <rule> } }
focusRule = wrappers.reduceRight((inner, w) => {
if (w.type === 'media') return `@media ${w.conditionText} { ${inner} }`;
if (w.type === 'supports') return `@supports ${w.conditionText} { ${inner} }`;
if (w.type === 'container') return `@container ${w.conditionText} { ${inner} }`;
return inner;
}, focusRule);
}
try {
targetStyleSheet.insertRule(focusRule, targetStyleSheet.cssRules.length);
+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',
};
+5
View File
@@ -188,7 +188,12 @@ export const extension_settings = {
dice: {},
/** @type {import('./char-data.js').RegexScriptData[]} */
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;
}
+23 -5
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);
@@ -439,6 +440,8 @@ jQuery(async function () {
'cohere': SECRET_KEYS.COHERE,
'aimlapi': SECRET_KEYS.AIMLAPI,
'moonshot': SECRET_KEYS.MOONSHOT,
'nanogpt': SECRET_KEYS.NANOGPT,
'electronhub': SECRET_KEYS.ELECTRONHUB,
};
if (chatCompletionApis[api] && secret_state[chatCompletionApis[api]]) {
@@ -543,8 +546,12 @@ jQuery(async function () {
}
await processEndpoint('openrouter', '/api/openrouter/models/multimodal');
await processEndpoint('aimlapi', '/api/backends/chat-completions/aimlapi/models/multimodal');
await processEndpoint('pollinations', '/api/backends/chat-completions/pollinations/models/multimodal');
await processEndpoint('aimlapi', '/api/backends/chat-completions/multimodal-models/aimlapi');
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();
@@ -588,10 +595,12 @@ jQuery(async function () {
saveSettingsDebounced();
});
$('#caption_ollama_pull').on('click', (e) => {
const presetModel = extension_settings.caption.multimodal_model !== 'ollama_current' ? extension_settings.caption.multimodal_model : '';
const selectedModel = extension_settings.caption.multimodal_model;
const staticModels = { 'ollama_current': textgenerationwebui_settings.ollama_model, 'ollama_custom': extension_settings.caption.ollama_custom_model };
const presetModel = staticModels[selectedModel] || selectedModel;
e.preventDefault();
$('#ollama_download_model').trigger('click');
$('#dialogue_popup_input').val(presetModel);
$('.popup .popup-input').val(presetModel);
});
$('#caption_multimodal_api').on('change', async () => {
const api = String($('#caption_multimodal_api').val());
@@ -616,6 +625,15 @@ jQuery(async function () {
extension_settings.caption.show_in_chat = !!$('#caption_show_in_chat').prop('checked');
saveSettingsDebounced();
});
$('#caption_ollama_custom_model').val(extension_settings.caption.ollama_custom_model || '').on('input', () => {
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) {
+51 -51
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,9 +18,10 @@
<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>
<option value="google">Google AI Studio</option>
<option value="vertexai">Google Vertex AI</option>
<option value="groq">Groq</option>
@@ -28,6 +29,7 @@
<option value="llamacpp">llama.cpp</option>
<option value="mistral">MistralAI</option>
<option value="moonshot">Moonshot AI</option>
<option value="nanogpt">NanoGPT</option>
<option value="ollama">Ollama</option>
<option value="openai">OpenAI</option>
<option value="openrouter">OpenRouter</option>
@@ -38,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 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>
@@ -85,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>
@@ -104,80 +104,80 @@
<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.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.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-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>
<option data-type="groq" value="llama-3.2-11b-vision-preview">llama-3.2-11b-vision-preview</option>
<option data-type="groq" value="llama-3.2-90b-vision-preview">llama-3.2-90b-vision-preview</option>
<option data-type="groq" value="llava-v1.5-7b-4096-preview">llava-v1.5-7b-4096-preview</option>
<option data-type="groq" value="meta-llama/llama-4-scout-17b-16e-instruct">meta-llama/llama-4-scout-17b-16e-instruct</option>
<option data-type="groq" value="meta-llama/llama-4-maverick-17b-128e-instruct">meta-llama/llama-4-maverick-17b-128e-instruct</option>
<option data-type="ollama" value="ollama_current" data-i18n="currently_selected">[Currently selected]</option>
<option data-type="ollama" value="ollama_custom" data-i18n="[Custom model]">[Custom model]</option>
<option data-type="ollama" value="bakllava">bakllava</option>
<option data-type="ollama" value="llava">llava</option>
<option data-type="ollama" value="llava-llama3">llava-llama3</option>
<option data-type="ollama" value="llava-phi3">llava-phi3</option>
<option data-type="ollama" value="moondream">moondream</option>
<option data-type="ollama" value="gemma3">gemma3</option>
<option data-type="ollama" value="minicpm-v">minicpm-v</option>
<option data-type="ollama" value="qwen2.5vl">qwen2.5vl</option>
<option data-type="ollama" value="granite3.2-vision">granite3.2-vision</option>
<option data-type="ollama" value="mistral-small3.1">mistral-small3.1</option>
<option data-type="ollama" value="mistral-small3.2">mistral-small3.2</option>
<option data-type="ollama" value="llama3.2-vision">llama3.2-vision</option>
<option data-type="ollama" value="llama4">llama4</option>
<option data-type="llamacpp" value="llamacpp_current" data-i18n="currently_loaded">[Currently loaded]</option>
<option data-type="ooba" value="ooba_current" data-i18n="currently_loaded">[Currently loaded]</option>
<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">
The model must be downloaded first! Do it with the <code>ollama pull</code> command or <a href="#" id="caption_ollama_pull">click here</a>.
<div>
The model must be downloaded first! Do it with the <code>ollama pull</code> command or <a href="#" id="caption_ollama_pull">click here</a>.
</div>
<div class="marginTop5">
<label for="caption_ollama_custom_model">
<span data-i18n="Custom Model Tag">Custom Model Tag</span>
<small data-i18n="(for [Custom model] option)">(for [Custom model] option)</small>
</label>
<input id="caption_ollama_custom_model" class="text_pole" type="text" placeholder="e.g. gemma3:latest" />
</div>
</div>
<label data-type="openai,anthropic,google,vertexai,mistral,xai" class="checkbox_label flexBasis100p" for="caption_allow_reverse_proxy" title="Allow using reverse proxy if defined and valid.">
<input id="caption_allow_reverse_proxy" type="checkbox" class="checkbox">
<span data-i18n="Allow reverse proxy">Allow reverse proxy</span>
</label>
<div class="flexBasis100p m-b-1">
<div class="flexBasis100p marginBot10">
<small><b data-i18n="Hint:">Hint:</b> <span data-i18n="Set your API keys and endpoints in the 'API Connections' tab first.">Set your API keys and endpoints in the 'API Connections' tab first.</span></small>
</div>
<div data-type="koboldcpp,ollama,vllm,llamacpp,ooba" class="flex-container flexFlowColumn">
<div data-type="koboldcpp,ollama,vllm,llamacpp,ooba" class="flex-container flexFlowColumn wide100p">
<label for="caption_altEndpoint_enabled" class="checkbox_label">
<input id="caption_altEndpoint_enabled" type="checkbox">
<span data-i18n="Use secondary URL">Use secondary URL</span>
@@ -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';
@@ -43,6 +43,7 @@ const CC_COMMANDS = [
'reasoning-template',
'prompt-post-processing',
'secret-id',
'regex-preset',
];
const TC_COMMANDS = [
@@ -60,6 +61,7 @@ const TC_COMMANDS = [
'start-reply-with',
'reasoning-template',
'secret-id',
'regex-preset',
];
const FANCY_NAMES = {
@@ -79,6 +81,7 @@ const FANCY_NAMES = {
'reasoning-template': 'Reasoning Template',
'prompt-post-processing': 'Prompt Post-Processing',
'secret-id': 'Secret',
'regex-preset': 'Regex Preset',
};
/**
@@ -164,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
*/
@@ -357,6 +366,14 @@ function makeFancyProfile(profile) {
}
}
if (key === 'regex-preset') {
const label = extension_settings.regex_presets?.find(p => p.id === profile[key])?.name;
if (label) {
acc[value] = label;
return acc;
}
}
acc[value] = profile[key];
return acc;
}, {});
@@ -673,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') {
@@ -704,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;
+45 -5
View File
@@ -63,10 +63,10 @@ mutationObserver.observe(document.body, {
});
const SORT = Object.freeze({
NAME_ASC: { value: 'nameAsc', field: 'name', order: 'asc', label: t`Sort By: Name (A-Z)` },
NAME_DESC: { value: 'nameDesc', field: 'name', order: 'desc', label: t`Sort By: Name (Z-A)` },
DATE_ASC: { value: 'dateAsc', field: 'date', order: 'asc', label: t`Sort By: Date (Oldest First)` },
DATE_DESC: { value: 'dateDesc', field: 'date', order: 'desc', label: t`Sort By: Date (Newest First)` },
NAME_ASC: { value: 'nameAsc', field: 'name', order: 'asc', label: t`Name (A-Z)` },
NAME_DESC: { value: 'nameDesc', field: 'name', order: 'desc', label: t`Name (Z-A)` },
DATE_DESC: { value: 'dateDesc', field: 'date', order: 'desc', label: t`Newest` },
DATE_ASC: { value: 'dateAsc', field: 'date', order: 'asc', label: t`Oldest` },
});
const defaultSettings = Object.freeze({
@@ -376,6 +376,11 @@ async function makeMovable(url) {
const titleText = document.createElement('span');
titleText.textContent = t`Image Gallery`;
dragTitle.append(titleText);
// Create a container for the controls
const controlsContainer = document.createElement('div');
controlsContainer.classList.add('flex-container', 'alignItemsCenter');
const sortSelect = document.createElement('select');
sortSelect.classList.add('gallery-sort-select');
@@ -394,7 +399,42 @@ async function makeMovable(url) {
});
sortSelect.value = getSortOrder();
dragTitle.append(sortSelect);
controlsContainer.appendChild(sortSelect);
// Create the "Add Image" button
const addImageButton = document.createElement('div');
addImageButton.classList.add('menu_button', 'menu_button_icon', 'interactable');
addImageButton.title = 'Add Image';
addImageButton.innerHTML = '<i class="fa-solid fa-plus fa-fw"></i><div>Add Image</div>';
// Create a hidden file input
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/*';
fileInput.multiple = true;
fileInput.style.display = 'none';
// Trigger file input when the button is clicked
addImageButton.addEventListener('click', () => {
fileInput.click();
});
// Handle file selection
fileInput.addEventListener('change', async () => {
const files = fileInput.files;
if (files.length > 0) {
for (const file of files) {
await uploadFile(file, url);
}
// Refresh the gallery
closeButton.trigger('click');
await showCharGallery();
}
});
controlsContainer.appendChild(addImageButton);
dragTitle.append(controlsContainer);
newElement.append(fileInput); // Append hidden file input to the main element
// add no-scrollbar class to this element
newElement.addClass('no-scrollbar');
+3 -2
View File
@@ -2,6 +2,7 @@
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
}
.gallery-folder-input {
@@ -26,13 +27,13 @@
text-overflow: ellipsis;
width: 100%;
opacity: 0.8;
background: none;
background-color: var(--black30a);
border: 1px solid var(--SmartThemeBorderColor);
background-image: url(/img/down-arrow.svg);
background-repeat: no-repeat;
background-position: right 6px center;
background-size: 8px 5px;
padding-right: 20px;
font-size: calc(var(--mainFontSize)* 0.9);
margin-bottom: 0;
}
+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
@@ -0,0 +1,263 @@
/* Styles for the debugger UI */
#regex_debugger_rules {
margin: 10px 0;
}
#regex_debugger_rules,
#regex_debugger_rules .sortable-list {
padding-left: 0;
}
.regex-debugger-rules-list {
position: relative;
}
.regex-debugger-rule {
display: flex;
align-items: center;
padding: 8px 10px;
border: 1px solid var(--SmartThemeBorderColor);
border-radius: 5px;
cursor: pointer;
background-color: var(--black30a);
gap: 5px;
margin-bottom: 5px;
}
#regex_debugger_run_test_header {
justify-content: space-between;
align-items: center;
}
#regex_debugger_expand_steps,
#regex_debugger_expand_final,
#regex_debugger_save_order {
position: absolute;
top: 0;
right: 0;
margin: 0;
}
.regex-debugger-rule:hover {
filter: brightness(1.1);
}
.regex-debugger-rule .handle {
cursor: grab;
margin-right: 5px;
}
.regex-debugger-rule .rule-details {
flex-grow: 1;
text-align: left;
display: flex;
align-items: baseline;
gap: 5px;
}
.regex-debugger-rule .rule-name {
font-weight: bold;
}
.regex-debugger-rule .rule-regex {
font-size: 0.8em;
opacity: 0.8;
font-family: var(--monoFontFamily);
}
.regex-debugger-rule .rule-scope {
font-size: 0.8em;
padding: 2px 6px;
border-radius: 5px;
background-color: var(--black30a);
margin-left: auto;
margin-right: 10px;
}
.regex-debugger-rule .menu_button {
margin: 0;
}
#regex_debugger_raw_input {
min-height: 1.8em;
}
#regex_debugger_steps_output {
min-height: 2em;
max-height: 300px;
overflow-y: auto;
border: 1px solid var(--SmartThemeBorderColor);
border-radius: 5px;
padding: 5px;
background-color: var(--black30a);
font-family: var(--monoFontFamily);
font-size: 0.9em;
}
#regex_debugger_final_output {
min-height: 2em;
max-height: 300px;
overflow-y: auto;
border: 1px solid var(--SmartThemeBorderColor);
border-radius: 5px;
padding: 5px;
background-color: var(--black30a);
white-space: pre-wrap;
word-break: break-word;
text-align: left;
}
.step-header {
margin-top: 10px;
margin-bottom: 5px;
}
.step-output {
white-space: pre-wrap;
word-break: break-all;
padding: 5px;
background-color: var(--black30a);
border-radius: 5px;
text-align: left;
}
/* Classes to replace inline styles */
.regex-debugger-no-rules {
padding: 10px;
text-align: center;
opacity: 0.8;
}
.regex-debugger-list-header {
font-weight: bold;
padding: 10px;
}
/* Styles for statistics */
.step-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.step-metrics {
font-size: 0.8em;
opacity: 0.8;
font-weight: normal;
}
.regex-debugger-summary {
padding: 8px;
margin-bottom: 10px;
border: 1px solid var(--SmartThemeBorderColor);
background-color: var(--black30a);
border-radius: 5px;
text-align: center;
font-size: 0.9em;
}
.regex-debugger-tester .results-header {
position: relative;
margin: 10px 0;
}
.regex-debugger-tester .radio_group {
text-align: left;
}
/* Styles for statistics and highlighting additions */
.step-header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
/* Allow wrapping on small screens */
}
.step-metrics {
font-size: 0.8em;
opacity: 0.8;
font-weight: normal;
white-space: nowrap;
/* Prevent metrics from breaking line */
margin-left: 10px;
}
.regex-debugger-summary {
padding: 8px;
margin-bottom: 10px;
border: 1px solid var(--SmartThemeBorderColor);
background-color: var(--black30a);
border-radius: 5px;
text-align: center;
font-size: 0.9em;
}
/* New highlight color for added text */
mark.green_hl {
background-color: #28a745;
/* A standard green color */
color: white;
}
/* New highlight color for deleted text */
mark.red_hl {
background-color: #dc3545;
/* A standard red color */
color: white;
text-decoration: line-through;
}
/* Styles for the expanded view with navigation */
.expanded-regex-container {
display: flex;
height: 75vh;
/* Give the container a good height */
overflow: hidden;
}
.expanded-regex-nav {
flex: 0 0 200px;
/* Fixed width for the nav bar */
border-right: 1px solid var(--SmartThemeBorderColor);
padding: 5px;
overflow-y: auto;
background-color: var(--black30a);
}
.expanded-regex-nav a {
display: block;
padding: 6px 8px;
text-decoration: none;
color: var(--SmartThemeMainColor);
border-radius: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.expanded-regex-nav a:hover {
background-color: var(--background_hover_color);
}
.expanded-regex-nav a.active {
background-color: var(--highlight_color);
color: var(--text_color_black);
}
.expanded-regex-content {
flex-grow: 1;
overflow-y: auto;
padding-left: 10px;
}
#regex_debugger_render_mode {
padding-right: 20px;
margin-top: 5px;
}
.regex-popup-content {
white-space: pre-wrap;
word-break: break-all;
text-align: left;
}
@@ -0,0 +1,179 @@
<div class="regex-debugger-container">
<!-- Rules List Column -->
<div class="regex-debugger-rules-list">
<h3>
<i class="fa-solid fa-list-ol"></i>
<span data-i18n="ext_regex_debugger_active_rules"
>Active Rules</span
>
</h3>
<div class="flex-container">
<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"
>
<i class="fa-solid fa-floppy-disk"></i>
<span data-i18n="ext_regex_debugger_save_order"
>Save Order</span
>
</button>
</div>
<ul id="regex_debugger_rules" class="sortable-list">
<!-- Rules will be populated here by JavaScript -->
</ul>
</div>
<!-- Testing Area Column -->
<div class="regex-debugger-tester">
<h3>
<i class="fa-solid fa-vial"></i>
<span data-i18n="ext_regex_debugger_testing_area"
>Testing Area</span
>
</h3>
<div class="regex-debugger-io">
<div class="regex-debugger-input">
<label
for="regex_debugger_raw_input"
data-i18n="ext_regex_debugger_raw_input"
>Raw Input</label
>
<textarea
id="regex_debugger_raw_input"
class="text_pole autoSetHeight"
rows="4"
></textarea>
</div>
<div
id="regex_debugger_run_test_header"
class="flex-container"
>
<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"
>
<i class="fa-solid fa-play"></i>
<span data-i18n="ext_regex_debugger_run_test"
>Run Test</span
>
</button>
<div class="flex-container gap10px">
<div class="radio_group">
<label
><input
type="radio"
name="display_mode"
value="replace"
checked
/>
<span data-i18n="ext_regex_debugger_display_replace"
>Replace</span
></label
>
<label
><input
type="radio"
name="display_mode"
value="highlight"
/>
<span
data-i18n="ext_regex_debugger_display_highlight"
>Highlight</span
></label
>
</div>
<select
id="regex_debugger_render_mode"
>
<option
value="text"
data-i18n="ext_regex_debugger_render_text"
>
Render as Text
</option>
<option
value="message"
data-i18n="ext_regex_debugger_render_message"
>
Render as Message
</option>
</select>
</div>
</div>
<div class="regex-debugger-results">
<div class="results-header">
<h4>
<i class="fa-solid fa-shoe-prints"></i>
<span data-i18n="ext_regex_debugger_step_by_step"
>Step-by-step Transformation</span
>
</h4>
<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>
</div>
</div>
<div id="regex_debugger_steps_output" class="results-box"></div>
<div class="results-header">
<h4>
<i class="fa-solid fa-flag-checkered"></i>
<span data-i18n="ext_regex_debugger_final_output"
>Final Output</span
>
</h4>
<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>
</div>
</div>
<div
id="regex_debugger_final_output"
class="results-box final-output"
></div>
</div>
</div>
</div>
</div>
<!-- Template for a single rule item -->
<template id="regex_debugger_rule_template">
<li class="regex-debugger-rule" draggable="true">
<i class="fa-solid fa-grip-vertical handle"></i>
<label class="checkbox">
<input type="checkbox" class="rule-enabled" checked />
</label>
<div class="rule-details">
<span class="rule-name"></span>
<code class="rule-regex"></code>
<small class="rule-scope"></small>
</div>
<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>
</template>
<!-- Template for a single transformation step -->
<template id="regex_debugger_step_template">
<div class="step-result">
<div class="step-header">
<strong></strong>
</div>
<pre class="step-output"></pre>
</div>
</template>
+55 -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>
@@ -26,8 +30,13 @@
<i class="fa-solid fa-edit"></i>
<small data-i18n="ext_regex_bulk_edit">Bulk Edit</small>
</label>
<div id="open_regex_debugger" class="menu_button menu_button_icon" data-i18n="[title]ext_regex_debugger_desc" title="Advanced Regex Debugger">
<i class="fa-solid fa-bug-slash"></i>
<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>
@@ -39,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>
@@ -49,7 +70,23 @@
</div>
</div>
<hr />
<div id="global_scripts_block" class="padding5">
<div id="regex_presets_block">
<div class="flex-container alignItemsBaseline">
<strong class="flex1" data-i18n="ext_regex_presets">Regex Presets</strong>
</div>
<small data-i18n="ext_regex_presets_desc">
Save and switch between groups of enabled regex scripts.
</small>
<div class="flex-container marginTop5">
<select id="regex_presets" class="text_pole flex1"></select>
<div id="regex_preset_create" class="menu_button fa-solid fa-file-circle-plus" data-i18n="[title]ext_regex_preset_create" title="Create a new regex preset"></div>
<div id="regex_preset_update" class="menu_button fa-solid fa-save" data-i18n="[title]ext_regex_preset_update" title="Update existing regex preset"></div>
<div id="regex_preset_apply" class="menu_button fa-solid fa-recycle" data-i18n="[title]ext_regex_preset_apply" title="Re-apply current preset"></div>
<div id="regex_preset_delete" class="menu_button fa-solid fa-trash" data-i18n="[title]ext_regex_preset_delete" title="Delete current preset"></div>
</div>
</div>
<hr />
<div id="global_scripts_block">
<div>
<strong data-i18n="ext_regex_global_scripts">Global Scripts</strong>
</div>
@@ -59,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">
@@ -73,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>
+39 -28
View File
@@ -1,3 +1,5 @@
@import "debugger.css";
.regex_settings .menu_button {
width: fit-content;
display: flex;
@@ -22,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 {
.enable_scoped:checked~.regex-toggle-on,
.enable_scoped:not(:checked)~.regex-toggle-off {
display: block;
}
.enable_scoped:checked ~ .regex-toggle-off {
.enable_scoped:checked~.regex-toggle-off,
.enable_scoped:not(:checked)~.regex-toggle-on {
display: none;
}
.enable_scoped:not(:checked) ~ .regex-toggle-on {
display: none;
}
.enable_scoped:not(:checked) ~ .regex-toggle-off {
display: block;
}
.regex-script-label {
align-items: baseline;
border: 1px solid var(--SmartThemeBorderColor);
@@ -90,19 +86,13 @@ input.enable_scoped {
cursor: pointer;
}
.disable_regex:checked ~ .regex-toggle-off {
display: block;
}
.disable_regex:checked ~ .regex-toggle-on {
.disable_regex:checked~.regex-toggle-on,
.disable_regex:not(:checked)~.regex-toggle-off {
display: none;
}
.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;
}
@@ -137,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;
}
@@ -145,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;
}
+20 -6
View File
@@ -22,12 +22,6 @@ export async function getMultimodalCaption(base64Img, prompt) {
throwIfInvalidModel(useReverseProxy);
const noPrefix = ['ollama'].includes(extension_settings.caption.multimodal_api);
if (noPrefix && base64Img.startsWith('data:image/')) {
base64Img = base64Img.split(',')[1];
}
// OpenRouter has a payload limit of ~2MB. Google is 4MB, but we love democracy.
// Ooba requires all images to be JPEGs. Koboldcpp just asked nicely.
const isOllama = extension_settings.caption.multimodal_api === 'ollama';
@@ -47,6 +41,9 @@ export async function getMultimodalCaption(base64Img, prompt) {
} else if (!safeMimeTypes.includes(mimeType)) {
base64Img = await createThumbnail(base64Img, null, null);
}
if (isOllama && base64Img.startsWith('data:image/')) {
base64Img = base64Img.split(',')[1];
}
const proxyUrl = useReverseProxy ? oai_settings.reverse_proxy : '';
const proxyPassword = useReverseProxy ? oai_settings.proxy_password : '';
@@ -72,6 +69,10 @@ export async function getMultimodalCaption(base64Img, prompt) {
requestBody.model = textgenerationwebui_settings.ollama_model;
}
if (extension_settings.caption.multimodal_model === 'ollama_custom') {
requestBody.model = extension_settings.caption.ollama_custom_model;
}
requestBody.server_url = extension_settings.caption.alt_endpoint_enabled
? extension_settings.caption.alt_endpoint_url
: textgenerationwebui_settings.server_urls[textgen_types.OLLAMA];
@@ -211,6 +212,10 @@ function throwIfInvalidModel(useReverseProxy) {
throw new Error('Ollama model is not set.');
}
if (multimodalApi === 'ollama' && multimodalModel === 'ollama_custom' && !extension_settings.caption.ollama_custom_model) {
throw new Error('Ollama custom model tag is not set.');
}
if (multimodalApi === 'llamacpp' && !textgenerationwebui_settings.server_urls[textgen_types.LLAMACPP] && !altEndpointEnabled) {
throw new Error('LlamaCPP server URL is not set.');
}
@@ -242,6 +247,14 @@ function throwIfInvalidModel(useReverseProxy) {
if (multimodalApi === 'moonshot' && !secret_state[SECRET_KEYS.MOONSHOT]) {
throw new Error('Moonshot AI API key is not set.');
}
if (multimodalApi === 'nanogpt' && !secret_state[SECRET_KEYS.NANOGPT]) {
throw new Error('NanoGPT API key is not set.');
}
if (multimodalApi === 'electronhub' && !secret_state[SECRET_KEYS.ELECTRONHUB]) {
throw new Error('Electron Hub API key is not set.');
}
}
/**
@@ -397,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>
@@ -57,7 +57,7 @@ import { callGenericPopup, Popup, POPUP_TYPE } from '../../popup.js';
import { commonEnumProviders } from '../../slash-commands/SlashCommandCommonEnumsProvider.js';
import { ToolManager } from '../../tool-calling.js';
import { MacrosParser } from '../../macros.js';
import { t } from '../../i18n.js';
import { t, translate } from '../../i18n.js';
import { oai_settings } from '../../openai.js';
export { MODULE_NAME };
@@ -82,6 +82,7 @@ const sources = {
pollinations: 'pollinations',
stability: 'stability',
huggingface: 'huggingface',
electronhub: 'electronhub',
nanogpt: 'nanogpt',
bfl: 'bfl',
falai: 'falai',
@@ -650,7 +651,7 @@ async function onDeleteStyleClick() {
return;
}
const confirmed = await callGenericPopup(`Are you sure you want to delete the style "${selectedStyle}"?`, POPUP_TYPE.CONFIRM, '', { okButton: 'Delete', cancelButton: 'Cancel' });
const confirmed = await callGenericPopup(t`Are you sure you want to delete the style "${selectedStyle}"?`, POPUP_TYPE.CONFIRM, '', { okButton: 'Delete', cancelButton: 'Cancel' });
if (!confirmed) {
return;
@@ -925,16 +926,16 @@ function onADetailerFaceChange() {
}
const resolutionOptions = {
sd_res_512x512: { width: 512, height: 512, name: '512x512 (1:1, icons, profile pictures)' },
sd_res_600x600: { width: 600, height: 600, name: '600x600 (1:1, icons, profile pictures)' },
sd_res_512x768: { width: 512, height: 768, name: '512x768 (2:3, vertical character card)' },
sd_res_768x512: { width: 768, height: 512, name: '768x512 (3:2, horizontal 35-mm movie film)' },
sd_res_960x540: { width: 960, height: 540, name: '960x540 (16:9, horizontal wallpaper)' },
sd_res_540x960: { width: 540, height: 960, name: '540x960 (9:16, vertical wallpaper)' },
sd_res_1920x1088: { width: 1920, height: 1088, name: '1920x1088 (16:9, 1080p, horizontal wallpaper)' },
sd_res_1088x1920: { width: 1088, height: 1920, name: '1088x1920 (9:16, 1080p, vertical wallpaper)' },
sd_res_1280x720: { width: 1280, height: 720, name: '1280x720 (16:9, 720p, horizontal wallpaper)' },
sd_res_720x1280: { width: 720, height: 1280, name: '720x1280 (9:16, 720p, vertical wallpaper)' },
sd_res_512x512: { width: 512, height: 512, name: translate('512x512 (1:1, icons, profile pictures)', 'sd_res_512x512') },
sd_res_600x600: { width: 600, height: 600, name: translate('600x600 (1:1, icons, profile pictures)', 'sd_res_600x600') },
sd_res_512x768: { width: 512, height: 768, name: translate('512x768 (2:3, vertical character card)', 'sd_res_512x768') },
sd_res_768x512: { width: 768, height: 512, name: translate('768x512 (3:2, horizontal 35-mm movie film)', 'sd_res_768x512') },
sd_res_960x540: { width: 960, height: 540, name: translate('960x540 (16:9, horizontal wallpaper)', 'sd_res_960x540') },
sd_res_540x960: { width: 540, height: 960, name: translate('540x960 (9:16, vertical wallpaper)', 'sd_res_540x960') },
sd_res_1920x1088: { width: 1920, height: 1088, name: translate('1920x1088 (16:9, 1080p, horizontal wallpaper)', 'sd_res_1920x1088') },
sd_res_1088x1920: { width: 1088, height: 1920, name: translate('1088x1920 (9:16, 1080p, vertical wallpaper)', 'sd_res_1088x1920') },
sd_res_1280x720: { width: 1280, height: 720, name: translate('1280x720 (16:9, 720p, horizontal wallpaper)', 'sd_res_1280x720') },
sd_res_720x1280: { width: 720, height: 1280, name: translate('720x1280 (9:16, 720p, vertical wallpaper)', 'sd_res_720x1280') },
sd_res_1024x1024: { width: 1024, height: 1024, name: '1024x1024 (1:1, SDXL)' },
sd_res_1152x896: { width: 1152, height: 896, name: '1152x896 (9:7, SDXL)' },
sd_res_896x1152: { width: 896, height: 1152, name: '896x1152 (7:9, SDXL)' },
@@ -1289,6 +1290,7 @@ async function onModelChange() {
sources.pollinations,
sources.stability,
sources.huggingface,
sources.electronhub,
sources.nanogpt,
sources.bfl,
sources.falai,
@@ -1506,6 +1508,9 @@ async function loadSamplers() {
case sources.huggingface:
samplers = ['N/A'];
break;
case sources.electronhub:
samplers = ['N/A'];
break;
case sources.nanogpt:
samplers = ['N/A'];
break;
@@ -1700,7 +1705,10 @@ 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();
break;
case sources.nanogpt:
models = await loadNanoGPTModels();
@@ -1806,6 +1814,24 @@ async function loadTogetherAIModels() {
return [];
}
async function loadElectronHubModels() {
if (!secret_state[SECRET_KEYS.ELECTRONHUB]) {
console.debug('Electron Hub API key is not set.');
return [];
}
const result = await fetch('/api/sd/electronhub/models', {
method: 'POST',
headers: getRequestHeaders(),
});
if (result.ok) {
return await result.json();
}
return [];
}
async function loadNanoGPTModels() {
if (!secret_state[SECRET_KEYS.NANOGPT]) {
console.debug('NanoGPT API key is not set.');
@@ -2131,6 +2157,9 @@ async function loadSchedulers() {
case sources.huggingface:
schedulers = ['N/A'];
break;
case sources.electronhub:
schedulers = ['N/A'];
break;
case sources.nanogpt:
schedulers = ['N/A'];
break;
@@ -2228,6 +2257,9 @@ async function loadVaes() {
case sources.huggingface:
vaes = ['N/A'];
break;
case sources.electronhub:
vaes = ['N/A'];
break;
case sources.nanogpt:
vaes = ['N/A'];
break;
@@ -2811,6 +2843,9 @@ async function sendGenerationRequest(generationType, prompt, additionalNegativeP
case sources.huggingface:
result = await generateHuggingFaceImage(prefixedPrompt, signal);
break;
case sources.electronhub:
result = await generateElectronHubImage(prefixedPrompt, signal);
break;
case sources.nanogpt:
result = await generateNanoGPTImage(prefixedPrompt, negativePrompt, signal);
break;
@@ -3013,6 +3048,56 @@ function getClosestAspectRatio(width, height, source) {
return closestAspectRatio;
}
/**
* Get closest size for Electron Hub
* @param {number} width - The width of the image
* @param {number} height - The height of the image
* @returns {Promise<string>} - The closest size
*/
async function getClosestSize(width, height) {
const response = await fetch('/api/sd/electronhub/sizes', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({
model: extension_settings.sd.model,
}),
});
if (!response.ok) {
const text = await response.text();
throw new Error(text);
}
const result = await response.json();
const sizesData = result.sizes;
const closestSize = sizesData.reduce((closest, size) => {
if (!size || typeof size !== 'string') {
return closest;
}
const sizeParts = size.split('x');
if (sizeParts.length !== 2) {
return closest;
}
const sizeWidth = Number(sizeParts[0]);
const sizeHeight = Number(sizeParts[1]);
const targetWidth = Number(width);
const targetHeight = Number(height);
if (isNaN(sizeWidth) || isNaN(sizeHeight) || isNaN(targetWidth) || isNaN(targetHeight)) {
return closest;
}
const sizeArea = sizeWidth * sizeHeight;
const targetArea = targetWidth * targetHeight;
const diff = Math.abs(sizeArea - targetArea);
return diff < closest.diff ? { size, diff } : closest;
}, { size: null, diff: Infinity });
const size = closestSize.size;
return size;
}
/**
* Generates an image using Stability AI.
* @param {string} prompt - The main instruction used to guide the image generation.
@@ -3564,6 +3649,35 @@ async function generateHuggingFaceImage(prompt, signal) {
}
}
/**
* Generates an image using the Electron Hub API.
* @param {string} prompt - The main instruction used to guide the image generation.
* @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request.
* @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete.
*/
async function generateElectronHubImage(prompt, signal) {
const size = await getClosestSize(extension_settings.sd.width, extension_settings.sd.height);
const result = await fetch('/api/sd/electronhub/generate', {
method: 'POST',
headers: getRequestHeaders(),
signal: signal,
body: JSON.stringify({
model: extension_settings.sd.model,
prompt: prompt,
size: size,
}),
});
if (result.ok) {
const data = await result.json();
return { format: 'jpg', data: data.image };
} else {
const text = await result.text();
throw new Error(text);
}
}
/**
* Generates an image using the NanoGPT API.
* @param {string} prompt - The main instruction used to guide the image generation.
@@ -3847,7 +3961,7 @@ async function onComfyNewWorkflowClick() {
}
async function onComfyDeleteWorkflowClick() {
const confirm = await callGenericPopup('Delete the workflow? This action is irreversible.', POPUP_TYPE.CONFIRM, '', { okButton: 'Delete', cancelButton: 'Cancel' });
const confirm = await callGenericPopup(t`Delete the workflow? This action is irreversible.`, POPUP_TYPE.CONFIRM, '', { okButton: t`Delete`, cancelButton: t`Cancel` });
if (!confirm) {
return;
}
@@ -4014,6 +4128,8 @@ function isValidState() {
return secret_state[SECRET_KEYS.STABILITY];
case sources.huggingface:
return secret_state[SECRET_KEYS.HUGGINGFACE];
case sources.electronhub:
return secret_state[SECRET_KEYS.ELECTRONHUB];
case sources.nanogpt:
return secret_state[SECRET_KEYS.NANOGPT];
case sources.bfl:
@@ -41,6 +41,7 @@
<option value="bfl">BFL (Black Forest Labs)</option>
<option value="comfy">ComfyUI</option>
<option value="drawthings">DrawThings HTTP API</option>
<option value="electronhub">Electron Hub</option>
<option value="extras">Extras API (deprecated)</option>
<option value="falai">FAL.AI</option>
<option value="google">Google AI</option>
@@ -89,12 +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 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>
@@ -139,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">
@@ -200,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
@@ -260,7 +264,7 @@
<span data-i18n="Click to set">Click to set</span>
</div>
</div>
<label class="checkbox_label marginBot5" for="sd_bfl_upsampling" title="Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation.">
<label class="checkbox_label marginBot5" for="sd_bfl_upsampling" data-i18n="[title]Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation." title="Whether to perform upsampling on the prompt. If active, automatically modifies the prompt for more creative generation.">
<input id="sd_bfl_upsampling" type="checkbox" />
<span data-i18n="Prompt Upsampling">
Prompt Upsampling
@@ -293,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
+4 -2
View File
@@ -182,9 +182,11 @@ function isGeneratingSwipe(messageId) {
return $(`#chat .mes[mesid="${messageId}"] .mes_text`).text() === '...';
}
async function translateImpersonate(text) {
async function translateImpersonate() {
const sendTextArea = $('#send_textarea');
const text = sendTextArea.val().toString();
const translatedText = await translate(text, extension_settings.translate.target_language);
$('#send_textarea').val(translatedText);
sendTextArea.val(translatedText);
}
/**
@@ -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();
}
//#################//
+79 -4
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,
@@ -637,11 +639,8 @@ async function processTtsQueue() {
}
if (extension_settings.tts.narrate_quoted_only) {
const special_quotes = /[“”«»「」『』""]/g; // Extend this regex to include other special quotes
text = text.replace(special_quotes, '"');
const matches = text.match(/".*?"/g); // Matches text inside double quotes, non-greedily
const partJoiner = (ttsProvider?.separator || ' ... ');
text = matches ? matches.join(partJoiner) : text;
text = joinQuotedBlocks(text, { separator: partJoiner, includeQuotes: true });
}
// Remove embedded images
@@ -702,6 +701,82 @@ async function processTtsQueue() {
}
}
/**
* Extract and join quoted blocks with proper matching pairs and nesting.
* - Captures outermost quotes and everything inside (including different inner quote styles).
* - Requires matching opener/closer style (e.g., “ ... ”, 「 ... 」, « ... », etc.).
* - Ignores incomplete/unclosed quotes (doesn't include them in the result).
* - Symmetric quotes like "..." and "..." are supported (not nesting the same symmetric style).
*
* @param {string} text - The text to process
* @param {object} [opts={}] - Optional options object
* @param {string} [opts.separator=' ... '] - String to join multiple quoted blocks
* @param {boolean} [opts.includeQuotes=true] - Keep the quote chars around the captured text
* @param {boolean} [opts.returnEmptyOnNoQuotes=false] - Return an empty string if no quotes are found
* @param {Array<[string,string]>} [opts.pairs] - Custom quote pairs; defaults cover EN/DE/FR/JP
* @returns {string} The joined quoted blocks, or the original text if no quotes found
*/
function joinQuotedBlocks(text, opts = {}) {
const {
separator = ' ... ',
includeQuotes = true,
returnEmptyOnNoQuotes = false,
pairs = [
// typographic doubles
['„', '“'], // DE low-high
['“', '”'], // EN
['«', '»'], // FR open « close »
['»', '«'], // Some locales open »
// typographic singles
['‘', '’'],
['‚', '‘'],
// Japanese corner quotes
['「', '」'],
['『', '』'],
// symmetric doubles
['"', '"'],
['"', '"'],
],
} = opts;
if (!text || typeof text !== 'string') return text;
const openToClose = Object.fromEntries(pairs);
const segments = [];
const stack = []; // [{ opener, expectedClose, start }]
for (let i = 0; i < text.length; i++) {
const ch = text[i];
const top = stack[stack.length - 1];
// Prefer closing the current open pair if the char matches its expected closer
if (top && ch === top.expectedClose) {
const finished = stack.pop();
if (stack.length === 0) {
// Only collect outermost quotes (contains all nested content)
segments.push(text.slice(finished.start, i + 1));
}
continue;
}
// Otherwise, see if this is a new opener
if (openToClose[ch]) {
stack.push({ opener: ch, expectedClose: openToClose[ch], start: i });
continue;
}
// If it's a stray closer that doesn't match current top, ignore
}
if (!segments.length) return returnEmptyOnNoQuotes ? '' : text;
const cleaned = includeQuotes
? segments
: segments.map(s => s.slice(1, -1)); // all defined pairs are single-char quotes
return cleaned.join(separator);
}
async function playFullConversation() {
resetTtsPlayback();
+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
@@ -11,7 +11,7 @@ const interactableSelectors = [
'.avatar-container', // Persona list blocks
'.tag .tag_remove', // Remove button in removable tags
'.bg_example', // Background elements in the background menu
'.bg_example .bg_button', // The inline buttons on the backgrounds
'.bg_example .jg-button, .bg_example .mobile-only-menu-toggle', // The inline buttons on the backgrounds
'#options a', // Option entries in the popup options menu
'.mes_buttons .mes_button', // Small inline buttons on the chat messages
'.extraMesButtons>div:not(.mes_button)', // The extra/extension buttons inline on the chat messages
+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';
+4
View File
@@ -1,3 +1,5 @@
import { initAccessibility } from './a11y.js';
/**
* CRSF token for requests.
*/
@@ -265,6 +267,8 @@ function configureDiscreetLogin() {
}
(async function () {
initAccessibility();
csrfToken = await getCsrfToken();
const userList = await getUserList();
+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(),
+515 -174
View File
File diff suppressed because it is too large Load Diff
+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());

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