* Performance improvements due to using chatElement instead of $('#chat').
* Reverts change `hideSwipeButtons()` change.
https://github.com/SillyTavern/SillyTavern/pull/4576#discussion_r2394996102
* I’ve been working on a PR for issue #1731: [Swipes on every AI message, not just the last one](https://github.com/SillyTavern/SillyTavern/issues/1731). I’d appreciate feedback to avoid unnecessary effort.
Currently, I have User and Assistant branches working.
I have not touched `/api/chats/save` or '/api/chats/get', so branches do not persist.
To keep `context.chat` unmodified (so extensions and the rest of the code remain unaffected), I’ve stored branches in `chatTree`:
```javascript
chatTree = {
branch_id: 1,
branch: [
{ mes: "Hi" },
{ mes: "Hello", branch_id: 0, branch: [...] },
]
}
```
When a message is swiped, chatTree is updated via `saveChatToTree()`, then the next branch is loaded using get`ChatFromTree()`.
Questions:
According to Cohee: [This requires reorganizations in the file format for chats, not viable in the short term.](https://github.com/SillyTavern/SillyTavern/issues/1731#issuecomment-1937845036)
I'm hesitant to proceed. May I store chatTree.json files alongside the existing .jsonl chats?
Should I create a new /save endpoint, modify the existing one, or discontinue using .jsonl for saving.
Known issues:
Branches do not persist on refresh.
Swiping multiple messages at once throws `Cannot read properties of undefined (reading 'mes')
`. This will be fixed in the UI.
Branches persist between chats/characters. This will be fixed when loading a chat.
The Swipe arrows overlap with messages.
No animation plays when swiping then editing a user message.
* Fixed bug.
Gemini:
The calculation of mesId is fragile and contains a bug. The fallback chat[chat.length - 1] is a message object, and Number(object) will result in NaN. This will break the swipe functionality if the preceding expressions are falsy. Additionally, chat.indexOf(message) will almost always point to the last message in the chat, which is incorrect when swiping on an earlier message.
A more robust approach is recommended to reliably get the message ID from the clicked element.
const mesId = Number($(this).closest('.mes').attr('mesid'));
* Fixes swipes on long chats.
* chatTree is now persistent. Fixed bugs.
* Fixed bugs.
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2390042262
The logic to rename the chat tree file (.json) is currently in an unreachable else block. The if condition !fs.existsSync(pathToOriginalFile) || fs.existsSync(pathToRenamedFile) will almost always evaluate to true after the preceding copyFileSync and unlinkSync operations, because pathToOriginalFile will no longer exist. This prevents the chat tree file from being renamed, which breaks the persistence of message branches when a chat is renamed.
The scrollChatToMessage function is implemented incorrectly. Calling .scrollTop() without any arguments on a jQuery object retrieves the current vertical scroll position; it does not scroll the element into view. This function will not have the intended effect of scrolling the chat to the specified message.
* Fixed bugs. https://github.com/SillyTavern/SillyTavern/pull/4573#pullrequestreview-3282889120
There's a typo in the property name being deleted. It should be branch to match the data structure you've defined, not branches. This error will prevent the pruning logic from working correctly, potentially leading to corrupted or bloated chatTree data.
The modified treeData is not being saved here. Instead, the global chatTree is being sent in the request. This will cause any renames of group members within message branches to be lost upon saving. You should send treeData, which contains the modifications.
This function may have performance issues on large chats due to multiple structuredClone calls within a loop. swipelessMessage is created from a deep clone, and then it's deep-cloned again for every swipe. While this ensures data integrity, it is inefficient. Consider refactoring to reduce the number of deep-cloning operations, for instance, by creating swipelessMessage once per message and deep-cloning it only when creating a new branch for a swipe.
* Fix warning. https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2390183161
The logic for renaming the chat tree file seems to have a flaw. The condition !fs.existsSync(pathToOriginalTreeFile) || fs.existsSync(pathToRenamedTreeFile) will be true if the original tree file does not exist. In this case, a warning is logged. However, it's a valid scenario for a chat to not have a corresponding tree file, so no warning should be logged. The current logic could lead to confusing log messages.
* Refactored chatTree into `public/scripts/chat-tree.js`.
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2390269514
* Displaying swipes on past messages and the entire chat tree functionality is now an opt-in toggle.
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2390273599
* Only allow one concurrent swipe.
Fixed:
Swiping multiple messages at once throws Cannot read properties of undefined (reading 'mes') .
* Fixed bugs.
Now `swipe_id >= swipes.length` is set to swipes.length.
* Fixed bug.
Swiping a user message did not re-show swipe buttons after the generation finished.
* Moved `Show Swipes for All Messages` Toggle to `Chat/Message Handling`.
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2395008961
* `JSON.stringify doesn't add spaces by default`
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2395047031
* Fixed "Tree file left behind when renaming chats"
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2395546142
* Fixed "Guard chatTree recursion in group member rename"
https://github.com/SillyTavern/SillyTavern/pull/4573#pullrequestreview-3290587129
* Re-implement: https://github.com/SillyTavern/SillyTavern/pull/4576#discussion_r2395506501
* Moved chat trees to a separate directory. https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2395045583
Enabled chat tree backups.
* Removed structuredClone() for improved performance.
* Fixed bugs.
Characters are now correctly renamed in the chatTree.
Directories are now recursively created.
* Reverts `hideSwipeButtons` to original functionality when `show_swipes_for_all_messages` is false.
https://github.com/SillyTavern/SillyTavern/pull/4576#discussion_r2395375718
* Added `refreshSwipeButtons`.
Updated `showSwipeButtons` and `hideSwipeButtons`.
Fixed bugs.
* Fixed.
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2400143193
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2400143202
* Added `clamp` to util.js.
Refactored `swipe`.
* Fixed bugs.
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2400685914
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2400685911
* Fixed bugs.
* Fixed swipe animations.
* Fixed bug by setting ids with `Number`.
* Delete swipes, and bugfixes.
* Merged `refactor/swipe`.
* Fixed bug created in `Delete swipes, and bugfixes.`.
* Merged from origin/staging.
* Merged changes from refactor/swipe.
* Fixed bug and refactored `syncWithSwipeId`.
* Merged from `origin/staging`.
* Fixed merge.
* Fixed overlapping message generations.
* Warn user, and refresh chat.
* Added metadata to chatTree file.
* Fixed "a sacrifice for the sake of simplicity." https://github.com/SillyTavern/SillyTavern/pull/2752#issuecomment-2323512022
Gemini:
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2464165990
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2464165991
* Improved swipeGenerate's animation.
* Added `SWIPE_SOURCE` constant.
* await `switchSwipesAllMessages`.
* Added `swipeState`.
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4573#issuecomment-3449690308
* Done:
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466884547
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466884547
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466894947
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466902075
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466911245
https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466938169
* Removed `NEUTRAL_CHAT_TREE_KEY`
* Moved backups
* Fixed `/send` and fixed a bug in `sendMessageAs`.
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466913570
* Fixes usage of `ENOENT`: https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466929980
* Removed LLM attribution.
* Updated link and warning.
* Removed debugging comments.
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4573#discussion_r2466905341
* Replaced `isSwipingAllowed` with `swipeState`.
* Backported many changes from feat/chat-tree.
* Refactored `showSwipeButtons` and `hideSwipeButtons` into `refreshSwipeButtons`
* Refactored `showSwipeButtons` and `hideSwipeButtons` into `refreshSwipeButtons`
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2472109888
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2472113323
* Merged from `refactor/backport-chat-tree`.
* Proposed fix for https://github.com/SillyTavern/SillyTavern/issues/4709
Reverts commit: https://github.com/SillyTavern/SillyTavern/commit/1b3db273891c1ba8c781d2f691ad2e41937ca2aa
On PR: https://github.com/SillyTavern/SillyTavern/pull/2940
* Proposed fix for https://github.com/SillyTavern/SillyTavern/issues/4709
Reverts commit: https://github.com/SillyTavern/SillyTavern/commit/1b3db273891c1ba8c781d2f691ad2e41937ca2aa
On PR: https://github.com/SillyTavern/SillyTavern/pull/2940
* Fixed regenerate and continue while editing the last message.
* Added swipesHidden.
Messages can now be designated as non-swipeable with `message.extra.swipeable`.
* Use `.hidden` and classes instead of `.css` to display swipe chevrons.
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3465749700
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2476136375
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2476140043
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3465776056
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3465794330
* Fixed bug.
* Fixed broken JQuery animation.
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2479003956
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2479011525
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2479014001
* Fixed active arrow transition.
* Fixed swipe shake direction.
* Fixed truthy check.
* Added temporary link to documentation PR.
* Moved `switchSwipesAllMessages`
* Fixed failed generations deleting the branch.
Fixed `forceSwipeId`.
Always call `saveChatConditional` if the `swipe_id` has changed.
* ESLint.
* Fixed bug.
Better `syncSwipeToMes` error handling.
* Backported changes from `feat/chat-tree`
Added failed swipe animation.
Fixed `newSwipeId`.
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4712#pullrequestreview-3406878337
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2483143387
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2483143387
* Added `showSwipes: false` to `showMoreMessages`.
And a few more performance improvements.
* Fixed animations.
* Added `'.mes'` to `.children`.
* Significantly improved `animateSwipeTransition` performance on large chats.
* Improved `syncSwipeToMes` error handling.
* Significantly improved `animateSwipeTransition` performance on large chats.
* Improved `syncSwipeToMes` error handling.
* Corrected Merge.
* Corrected Merge.
* Improved: `redisplayChat`
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2484177521
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2484215469
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2484217230
* Added a temporary implementation of `branchChat`.
* Fixed bug when generating a swipe.
* Fixed bug in `branchChat`.
* Fixed Off by one error due to `chatElement.children()` selecting `show_more_messages`.
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3478331073
* Fixed Off by one error due to `chatElement.children()` selecting `show_more_messages`.
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3478331073
* Cleaned system messages array and moved `swipeable`
* Removed CSS nesting.
* Fixed merge.
* Improved `syncSwipeToMes` error handling.
* Matched `swipes-counter` fade to chevrons.
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3478192184
* Wrapped `transition-behavior: allow-discrete;` in `@supports`.
* Fixed types.
* Improved swipeability feedback and functions.
* Improved `refreshSwipeButtons` performance again.
* Swapped `.attr` to `.prop`.
* Fixed: `@supports (transition-behavior: allow-discrete)`
* Fixed and clarified typo.
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495919425
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495923036
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495927019
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495930080
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495943870
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495950927
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495954387
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495974324
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495974683
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495957181
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495960920
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495968137
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495968922
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495959430
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495924599
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495918468
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495931979
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495933092
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2495939511
* Improved `refreshSwipeButtons` performance by skipping 'swipes-counter' updates by default.
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2496382916
https://github.com/SillyTavern/SillyTavern/pull/4712#discussion_r2496379401
* Removed chevron fade-in on Cohee's request: https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3493829978
* Set most system messages to `swipeable: false`.
* Implemented `OVERSWIPE_BEHAVIOR`.
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3499706714
* Fix formatting, make comments IDE friendly
* IDE friendly enum comments
* Move animation frames to a dedicated file
* Do not compare with -1
* overswipeBehavior => getOverswipeBehavior
* Formatting fix
* Don't let regenerate on is_system
* Fixed canceled generations in pristine chats.
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3499819670
* Fixed `AUTO_SWIPE` when `animation_duration = 0`.
* Fixed mistake in `redisplayChat`.
* Holding the swipe button speeds up `swipeDuration`.
* Fixed 'animationend' never ending.
Altered resetTime.
* Swapped from `saveChatConditional` to `saveChatDebounced` in `swipe`.
* Skip the animation if it's faster than 50ms instead of 10ms.
* Typo.
* Fixed:
https://github.com/SillyTavern/SillyTavern/pull/4712#pullrequestreview-3457198109
* Adjust duration reset cooldown
* Add quotes to selector
* Specify type for message parameter in swipe function
* Add type for swipe UI event
* Disabled fade-in during printMessages.
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3539315919
* Typo.
* Added quotes to selector .
* Reduce reset time 500 -> 350
* Loops do not cause a generation so their chevrons should not have increased opacity.
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3543692019
* Revert reset time
* Renamed `heldSwipes` to `recentSwipes`.
* Autofix the swipes array during `updateSwipeCounter`.
* User messages should not have swipes.
* Chevrons should always be shown on pristine greetings: https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3557893373
* Improve formatting
* Fixed: https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3559617088
* Show `pristineGreetingSwipeNotice` once.
* `clearMessageData` when swipe-regenerating a message.
* accountStorage is already imported in the module
* Removed `await`.
* Removed pristine greeting notice.
https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3560758598
* Removed redundant functions in `StreamingProcessor` and fixed streamed replies missing counters.
* Moved `markUIGenStopped` after `eventSource.emit`.
Swapped to `saveChatDebounced` to fix: https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3567014810.
* Save a structuredClone of `chat` to prevent an invalid chat from being saved.
* Only `structuredClone` `chat` on `saveChatDebounced`.
* Revert "Only `structuredClone` `chat` on `saveChatDebounced`."
This reverts commit 49498b7aa1.
* Revert "Save a structuredClone of `chat` to prevent an invalid chat from being saved."
This reverts commit 5f137ed138.
* Prevent `saveChatDebounced` from saving while the swipe is in progress.
See: https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3567077312
* Fixed animation never ending: https://github.com/SillyTavern/SillyTavern/pull/4712#issuecomment-3567106213
* `forceMesId` and `forceSwipeId` are not objects.
* Fixed Reduced Motion causing a warning when swiping back.
* Only hide `.mes_buttons` when generating.
* Fix eslint
* Reset duration on switching direction
---------
Co-authored-by: user <user@exmaple.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
669 lines
24 KiB
JavaScript
669 lines
24 KiB
JavaScript
import {
|
|
addOneMessage,
|
|
characters,
|
|
chat,
|
|
deleteCharacterChatByName,
|
|
displayVersion,
|
|
doNewChat,
|
|
event_types,
|
|
eventSource,
|
|
getCharacters,
|
|
getCurrentChatId,
|
|
getRequestHeaders,
|
|
getSystemMessageByType,
|
|
getThumbnailUrl,
|
|
is_send_press,
|
|
neutralCharacterName,
|
|
newAssistantChat,
|
|
openCharacterChat,
|
|
printCharactersDebounced,
|
|
renameGroupOrCharacterChat,
|
|
saveSettingsDebounced,
|
|
selectCharacterById,
|
|
setActiveCharacter,
|
|
setActiveGroup,
|
|
system_avatar,
|
|
system_message_types,
|
|
this_chid,
|
|
unshallowCharacter,
|
|
updateRemoteChatName,
|
|
} from '../script.js';
|
|
import { getRegexedString, regex_placement } from './extensions/regex/engine.js';
|
|
import { deleteGroupChatByName, getGroupAvatar, groups, is_group_generating, openGroupById, openGroupChat } from './group-chats.js';
|
|
import { t } from './i18n.js';
|
|
import { callGenericPopup, POPUP_TYPE } from './popup.js';
|
|
import { getMessageTimeStamp } from './RossAscends-mods.js';
|
|
import { renderTemplateAsync } from './templates.js';
|
|
import { accountStorage } from './util/AccountStorage.js';
|
|
import { sortMoments, timestampToMoment } from './utils.js';
|
|
|
|
const assistantAvatarKey = 'assistant';
|
|
const defaultAssistantAvatar = 'default_Assistant.png';
|
|
|
|
const DEFAULT_DISPLAYED = 3;
|
|
const MAX_DISPLAYED = 15;
|
|
|
|
export function getPermanentAssistantAvatar() {
|
|
const assistantAvatar = accountStorage.getItem(assistantAvatarKey);
|
|
if (assistantAvatar === null) {
|
|
return defaultAssistantAvatar;
|
|
}
|
|
|
|
const character = characters.find(x => x.avatar === assistantAvatar);
|
|
if (character === undefined) {
|
|
accountStorage.removeItem(assistantAvatarKey);
|
|
return defaultAssistantAvatar;
|
|
}
|
|
|
|
return assistantAvatar;
|
|
}
|
|
|
|
/**
|
|
* Opens a welcome screen if no chat is currently active.
|
|
* @param {object} param Additional parameters
|
|
* @param {boolean} [param.force] If true, forces clearing of the welcome screen.
|
|
* @param {boolean} [param.expand] If true, expands the recent chats section.
|
|
* @returns {Promise<void>}
|
|
*/
|
|
export async function openWelcomeScreen({ force = false, expand = false } = {}) {
|
|
const currentChatId = getCurrentChatId();
|
|
if (currentChatId !== undefined || (chat.length > 0 && !force)) {
|
|
return;
|
|
}
|
|
|
|
const recentChats = await getRecentChats();
|
|
const chatAfterFetch = getCurrentChatId();
|
|
if (chatAfterFetch !== currentChatId) {
|
|
console.debug('Chat changed while fetching recent chats.');
|
|
return;
|
|
}
|
|
|
|
if (chatAfterFetch === undefined && force) {
|
|
console.debug('Forcing welcome screen open.');
|
|
chat.splice(0, chat.length);
|
|
$('#chat').empty();
|
|
}
|
|
|
|
await sendWelcomePanel(recentChats, expand);
|
|
await unshallowPermanentAssistant();
|
|
sendAssistantMessage();
|
|
sendWelcomePrompt();
|
|
}
|
|
|
|
/**
|
|
* Makes sure the assistant character has all data loaded.
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async function unshallowPermanentAssistant() {
|
|
const assistantAvatar = getPermanentAssistantAvatar();
|
|
const characterId = characters.findIndex(x => x.avatar === assistantAvatar);
|
|
if (characterId === -1) {
|
|
return;
|
|
}
|
|
|
|
await unshallowCharacter(String(characterId));
|
|
}
|
|
|
|
/**
|
|
* Returns a greeting message for the assistant based on the character.
|
|
* @param {Character} character Character data
|
|
* @returns {string} Greeting message
|
|
*/
|
|
function getAssistantGreeting(character) {
|
|
const defaultGreeting = t`If you're connected to an API, try asking me something!` + '\n***\n' + t`**Hint:** Set any character as your welcome page assistant from their "More..." menu.`;
|
|
|
|
if (!character) {
|
|
return defaultGreeting;
|
|
}
|
|
|
|
return getRegexedString(character.first_mes || '', regex_placement.AI_OUTPUT) || defaultGreeting;
|
|
}
|
|
|
|
function sendAssistantMessage() {
|
|
const currentAssistantAvatar = getPermanentAssistantAvatar();
|
|
const character = characters.find(x => x.avatar === currentAssistantAvatar);
|
|
const name = character ? character.name : neutralCharacterName;
|
|
const avatar = character ? getThumbnailUrl('avatar', character.avatar) : system_avatar;
|
|
const greeting = getAssistantGreeting(character);
|
|
|
|
const message = {
|
|
name: name,
|
|
force_avatar: avatar,
|
|
mes: greeting,
|
|
is_system: false,
|
|
is_user: false,
|
|
send_date: getMessageTimeStamp(),
|
|
extra: {
|
|
type: system_message_types.ASSISTANT_MESSAGE,
|
|
swipeable: false,
|
|
},
|
|
};
|
|
|
|
chat.push(message);
|
|
addOneMessage(message, { scroll: false });
|
|
}
|
|
|
|
function sendWelcomePrompt() {
|
|
const message = getSystemMessageByType(system_message_types.WELCOME_PROMPT);
|
|
chat.push(message);
|
|
addOneMessage(message, { scroll: false });
|
|
}
|
|
|
|
/**
|
|
* Sends the welcome panel to the chat.
|
|
* @param {RecentChat[]} chats List of recent chats
|
|
* @param {boolean} [expand=false] If true, expands the recent chats section
|
|
*/
|
|
async function sendWelcomePanel(chats, expand = false) {
|
|
try {
|
|
const chatElement = document.getElementById('chat');
|
|
const sendTextArea = document.getElementById('send_textarea');
|
|
if (!chatElement) {
|
|
console.error('Chat element not found');
|
|
return;
|
|
}
|
|
const templateData = {
|
|
chats,
|
|
empty: !chats.length,
|
|
version: displayVersion,
|
|
more: chats.some(chat => chat.hidden),
|
|
};
|
|
const template = await renderTemplateAsync('welcomePanel', templateData);
|
|
const fragment = document.createRange().createContextualFragment(template);
|
|
fragment.querySelectorAll('.welcomePanel').forEach((root) => {
|
|
const recentHiddenClass = 'recentHidden';
|
|
const recentHiddenKey = 'WelcomePage_RecentChatsHidden';
|
|
if (accountStorage.getItem(recentHiddenKey) === 'true') {
|
|
root.classList.add(recentHiddenClass);
|
|
}
|
|
root.querySelectorAll('.showRecentChats').forEach((button) => {
|
|
button.addEventListener('click', () => {
|
|
root.classList.remove(recentHiddenClass);
|
|
accountStorage.setItem(recentHiddenKey, 'false');
|
|
});
|
|
});
|
|
root.querySelectorAll('.hideRecentChats').forEach((button) => {
|
|
button.addEventListener('click', () => {
|
|
root.classList.add(recentHiddenClass);
|
|
accountStorage.setItem(recentHiddenKey, 'true');
|
|
});
|
|
});
|
|
});
|
|
fragment.querySelectorAll('.recentChat').forEach((item) => {
|
|
item.addEventListener('click', () => {
|
|
const avatarId = item.getAttribute('data-avatar');
|
|
const groupId = item.getAttribute('data-group');
|
|
const fileName = item.getAttribute('data-file');
|
|
if (avatarId && fileName) {
|
|
void openRecentCharacterChat(avatarId, fileName);
|
|
}
|
|
if (groupId && fileName) {
|
|
void openRecentGroupChat(groupId, fileName);
|
|
}
|
|
});
|
|
});
|
|
const hiddenChats = fragment.querySelectorAll('.recentChat.hidden');
|
|
fragment.querySelectorAll('button.showMoreChats').forEach((button) => {
|
|
const showRecentChatsTitle = t`Show more recent chats`;
|
|
const hideRecentChatsTitle = t`Show less recent chats`;
|
|
|
|
button.setAttribute('title', showRecentChatsTitle);
|
|
button.addEventListener('click', () => {
|
|
const rotate = button.classList.contains('rotated');
|
|
hiddenChats.forEach((chatItem) => {
|
|
chatItem.classList.toggle('hidden', rotate);
|
|
});
|
|
button.classList.toggle('rotated', !rotate);
|
|
button.setAttribute('title', rotate ? showRecentChatsTitle : hideRecentChatsTitle);
|
|
});
|
|
});
|
|
fragment.querySelectorAll('button.openTemporaryChat').forEach((button) => {
|
|
button.addEventListener('click', async () => {
|
|
await newAssistantChat({ temporary: true });
|
|
if (sendTextArea instanceof HTMLTextAreaElement) {
|
|
sendTextArea.focus();
|
|
}
|
|
});
|
|
});
|
|
fragment.querySelectorAll('.recentChat.group').forEach((groupChat) => {
|
|
const groupId = groupChat.getAttribute('data-group');
|
|
const group = groups.find(x => x.id === groupId);
|
|
if (group) {
|
|
const avatar = groupChat.querySelector('.avatar');
|
|
if (!avatar) {
|
|
return;
|
|
}
|
|
const groupAvatar = getGroupAvatar(group);
|
|
$(avatar).replaceWith(groupAvatar);
|
|
}
|
|
});
|
|
fragment.querySelectorAll('.recentChat .renameChat').forEach((renameButton) => {
|
|
renameButton.addEventListener('click', (event) => {
|
|
event.stopPropagation();
|
|
const chatItem = renameButton.closest('.recentChat');
|
|
if (!chatItem) {
|
|
return;
|
|
}
|
|
const avatarId = chatItem.getAttribute('data-avatar');
|
|
const groupId = chatItem.getAttribute('data-group');
|
|
const fileName = chatItem.getAttribute('data-file');
|
|
if (avatarId && fileName) {
|
|
void renameRecentCharacterChat(avatarId, fileName);
|
|
}
|
|
if (groupId && fileName) {
|
|
void renameRecentGroupChat(groupId, fileName);
|
|
}
|
|
});
|
|
});
|
|
fragment.querySelectorAll('.recentChat .deleteChat').forEach((deleteButton) => {
|
|
deleteButton.addEventListener('click', (event) => {
|
|
event.stopPropagation();
|
|
const chatItem = deleteButton.closest('.recentChat');
|
|
if (!chatItem) {
|
|
return;
|
|
}
|
|
const avatarId = chatItem.getAttribute('data-avatar');
|
|
const groupId = chatItem.getAttribute('data-group');
|
|
const fileName = chatItem.getAttribute('data-file');
|
|
if (avatarId && fileName) {
|
|
void deleteRecentCharacterChat(avatarId, fileName);
|
|
}
|
|
if (groupId && fileName) {
|
|
void deleteRecentGroupChat(groupId, fileName);
|
|
}
|
|
});
|
|
});
|
|
chatElement.append(fragment.firstChild);
|
|
if (expand) {
|
|
chatElement.querySelectorAll('button.showMoreChats').forEach((button) => {
|
|
if (button instanceof HTMLButtonElement) {
|
|
button.click();
|
|
}
|
|
});
|
|
}
|
|
} catch (error) {
|
|
console.error('Welcome screen error:', error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Opens a recent character chat.
|
|
* @param {string} avatarId Avatar file name
|
|
* @param {string} fileName Chat file name
|
|
*/
|
|
async function openRecentCharacterChat(avatarId, fileName) {
|
|
const characterId = characters.findIndex(x => x.avatar === avatarId);
|
|
if (characterId === -1) {
|
|
console.error(`Character not found for avatar ID: ${avatarId}`);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await selectCharacterById(characterId);
|
|
setActiveCharacter(avatarId);
|
|
saveSettingsDebounced();
|
|
const currentChatId = getCurrentChatId();
|
|
if (currentChatId === fileName) {
|
|
console.debug(`Chat ${fileName} is already open.`);
|
|
return;
|
|
}
|
|
await openCharacterChat(fileName);
|
|
} catch (error) {
|
|
console.error('Error opening recent chat:', error);
|
|
toastr.error(t`Failed to open recent chat. See console for details.`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Opens a recent group chat.
|
|
* @param {string} groupId Group ID
|
|
* @param {string} fileName Chat file name
|
|
*/
|
|
async function openRecentGroupChat(groupId, fileName) {
|
|
const group = groups.find(x => x.id === groupId);
|
|
if (!group) {
|
|
console.error(`Group not found for ID: ${groupId}`);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await openGroupById(groupId);
|
|
setActiveGroup(groupId);
|
|
saveSettingsDebounced();
|
|
const currentChatId = getCurrentChatId();
|
|
if (currentChatId === fileName) {
|
|
console.debug(`Chat ${fileName} is already open.`);
|
|
return;
|
|
}
|
|
await openGroupChat(groupId, fileName);
|
|
} catch (error) {
|
|
console.error('Error opening recent group chat:', error);
|
|
toastr.error(t`Failed to open recent group chat. See console for details.`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Renames a recent character chat.
|
|
* @param {string} avatarId Avatar file name
|
|
* @param {string} fileName Chat file name
|
|
*/
|
|
async function renameRecentCharacterChat(avatarId, fileName) {
|
|
const characterId = characters.findIndex(x => x.avatar === avatarId);
|
|
if (characterId === -1) {
|
|
console.error(`Character not found for avatar ID: ${avatarId}`);
|
|
return;
|
|
}
|
|
try {
|
|
const popupText = await renderTemplateAsync('chatRename');
|
|
const newName = await callGenericPopup(popupText, POPUP_TYPE.INPUT, fileName);
|
|
if (!newName || typeof newName !== 'string' || newName === fileName) {
|
|
console.log('No new name provided, aborting');
|
|
return;
|
|
}
|
|
await renameGroupOrCharacterChat({
|
|
characterId: String(characterId),
|
|
oldFileName: fileName,
|
|
newFileName: newName,
|
|
loader: false,
|
|
});
|
|
await updateRemoteChatName(characterId, newName);
|
|
await refreshWelcomeScreen();
|
|
toastr.success(t`Chat renamed.`);
|
|
} catch (error) {
|
|
console.error('Error renaming recent character chat:', error);
|
|
toastr.error(t`Failed to rename recent chat. See console for details.`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Renames a recent group chat.
|
|
* @param {string} groupId Group ID
|
|
* @param {string} fileName Chat file name
|
|
*/
|
|
async function renameRecentGroupChat(groupId, fileName) {
|
|
const group = groups.find(x => x.id === groupId);
|
|
if (!group) {
|
|
console.error(`Group not found for ID: ${groupId}`);
|
|
return;
|
|
}
|
|
try {
|
|
const popupText = await renderTemplateAsync('chatRename');
|
|
const newName = await callGenericPopup(popupText, POPUP_TYPE.INPUT, fileName);
|
|
if (!newName || newName === fileName) {
|
|
console.log('No new name provided, aborting');
|
|
return;
|
|
}
|
|
await renameGroupOrCharacterChat({
|
|
groupId: String(groupId),
|
|
oldFileName: fileName,
|
|
newFileName: String(newName),
|
|
loader: false,
|
|
});
|
|
await refreshWelcomeScreen();
|
|
toastr.success(t`Group chat renamed.`);
|
|
} catch (error) {
|
|
console.error('Error renaming recent group chat:', error);
|
|
toastr.error(t`Failed to rename recent group chat. See console for details.`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Deletes a recent character chat.
|
|
* @param {string} avatarId Avatar file name
|
|
* @param {string} fileName Chat file name
|
|
*/
|
|
async function deleteRecentCharacterChat(avatarId, fileName) {
|
|
const characterId = characters.findIndex(x => x.avatar === avatarId);
|
|
if (characterId === -1) {
|
|
console.error(`Character not found for avatar ID: ${avatarId}`);
|
|
return;
|
|
}
|
|
try {
|
|
const confirm = await callGenericPopup(t`Delete the Chat File?`, POPUP_TYPE.CONFIRM);
|
|
if (!confirm) {
|
|
console.log('Deletion cancelled by user');
|
|
return;
|
|
}
|
|
await deleteCharacterChatByName(String(characterId), fileName);
|
|
await refreshWelcomeScreen();
|
|
toastr.success(t`Chat deleted.`);
|
|
} catch (error) {
|
|
console.error('Error deleting recent character chat:', error);
|
|
toastr.error(t`Failed to delete recent chat. See console for details.`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Deletes a recent group chat.
|
|
* @param {string} groupId Group ID
|
|
* @param {string} fileName Chat file name
|
|
*/
|
|
async function deleteRecentGroupChat(groupId, fileName) {
|
|
const group = groups.find(x => x.id === groupId);
|
|
if (!group) {
|
|
console.error(`Group not found for ID: ${groupId}`);
|
|
return;
|
|
}
|
|
try {
|
|
const confirm = await callGenericPopup(t`Delete the Chat File?`, POPUP_TYPE.CONFIRM);
|
|
if (!confirm) {
|
|
console.log('Deletion cancelled by user');
|
|
return;
|
|
}
|
|
await deleteGroupChatByName(groupId, fileName);
|
|
await refreshWelcomeScreen();
|
|
toastr.success(t`Group chat deleted.`);
|
|
} catch (error) {
|
|
console.error('Error deleting recent group chat:', error);
|
|
toastr.error(t`Failed to delete recent group chat. See console for details.`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Reopens the welcome screen and restores the scroll position.
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async function refreshWelcomeScreen() {
|
|
const chatElement = document.getElementById('chat');
|
|
if (!chatElement) {
|
|
console.error('Chat element not found');
|
|
return;
|
|
}
|
|
|
|
const scrollTop = chatElement.scrollTop;
|
|
const scrollHeight = chatElement.scrollHeight;
|
|
const expand = chatElement.querySelectorAll('button.showMoreChats.rotated').length > 0;
|
|
|
|
await openWelcomeScreen({ force: true, expand });
|
|
|
|
// Restore scroll position
|
|
chatElement.scrollTop = scrollTop + (chatElement.scrollHeight - scrollHeight);
|
|
}
|
|
|
|
/**
|
|
* Gets the list of recent chats from the server.
|
|
* @returns {Promise<RecentChat[]>} List of recent chats
|
|
*
|
|
* @typedef {object} RecentChat
|
|
* @property {string} file_name Name of the chat file
|
|
* @property {string} chat_name Name of the chat (without extension)
|
|
* @property {string} file_size Size of the chat file
|
|
* @property {number} chat_items Number of items in the chat
|
|
* @property {string} mes Last message content
|
|
* @property {string} last_mes Timestamp of the last message
|
|
* @property {string} avatar Avatar URL
|
|
* @property {string} char_thumbnail Thumbnail URL
|
|
* @property {string} char_name Character or group name
|
|
* @property {string} date_short Date in short format
|
|
* @property {string} date_long Date in long format
|
|
* @property {string} group Group ID (if applicable)
|
|
* @property {boolean} is_group Indicates if the chat is a group chat
|
|
* @property {boolean} hidden Chat will be hidden by default
|
|
*/
|
|
async function getRecentChats() {
|
|
const response = await fetch('/api/chats/recent', {
|
|
method: 'POST',
|
|
headers: getRequestHeaders(),
|
|
body: JSON.stringify({ max: MAX_DISPLAYED }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.warn('Failed to fetch recent character chats');
|
|
return [];
|
|
}
|
|
|
|
/** @type {RecentChat[]} */
|
|
const data = await response.json();
|
|
|
|
if (!Array.isArray(data) || data.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const dataWithEntities = data
|
|
.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes)))
|
|
.map(chat => ({ chat, character: characters.find(x => x.avatar === chat.avatar), group: groups.find(x => x.id === chat.group) }))
|
|
.filter(t => t.character || t.group);
|
|
|
|
dataWithEntities.forEach(({ chat, character, group }, index) => {
|
|
const chatTimestamp = timestampToMoment(chat.last_mes);
|
|
chat.char_name = character?.name || group?.name || '';
|
|
chat.date_short = chatTimestamp.format('l');
|
|
chat.date_long = chatTimestamp.format('LL LT');
|
|
chat.chat_name = chat.file_name.replace('.jsonl', '');
|
|
chat.char_thumbnail = character ? getThumbnailUrl('avatar', character.avatar) : system_avatar;
|
|
chat.is_group = !!group;
|
|
chat.hidden = index >= DEFAULT_DISPLAYED;
|
|
chat.avatar = chat.avatar || '';
|
|
chat.group = chat.group || '';
|
|
});
|
|
|
|
return dataWithEntities.map(t => t.chat);
|
|
}
|
|
|
|
export async function openPermanentAssistantChat({ tryCreate = true, created = false } = {}) {
|
|
const avatar = getPermanentAssistantAvatar();
|
|
const characterId = characters.findIndex(x => x.avatar === avatar);
|
|
if (characterId === -1) {
|
|
if (!tryCreate) {
|
|
console.error(`Character not found for avatar ID: ${avatar}. Cannot create.`);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
console.log(`Character not found for avatar ID: ${avatar}. Creating new assistant.`);
|
|
await createPermanentAssistant();
|
|
return openPermanentAssistantChat({ tryCreate: false, created: true });
|
|
}
|
|
catch (error) {
|
|
console.error('Error creating permanent assistant:', error);
|
|
toastr.error(t`Failed to create ${neutralCharacterName}. See console for details.`);
|
|
return;
|
|
}
|
|
}
|
|
|
|
try {
|
|
await selectCharacterById(characterId);
|
|
if (!created) {
|
|
await doNewChat({ deleteCurrentChat: false });
|
|
}
|
|
console.log(`Opened permanent assistant chat for ${neutralCharacterName}.`, getCurrentChatId());
|
|
} catch (error) {
|
|
console.error('Error opening permanent assistant chat:', error);
|
|
toastr.error(t`Failed to open permanent assistant chat. See console for details.`);
|
|
}
|
|
}
|
|
|
|
async function createPermanentAssistant() {
|
|
if (is_group_generating || is_send_press) {
|
|
throw new Error(t`Cannot create while generating.`);
|
|
}
|
|
|
|
const formData = new FormData();
|
|
formData.append('ch_name', neutralCharacterName);
|
|
formData.append('file_name', defaultAssistantAvatar.replace('.png', ''));
|
|
formData.append('creator_notes', t`Automatically created character. Feel free to edit.`);
|
|
|
|
try {
|
|
const avatarResponse = await fetch(system_avatar);
|
|
const avatarBlob = await avatarResponse.blob();
|
|
formData.append('avatar', avatarBlob, defaultAssistantAvatar);
|
|
} catch (error) {
|
|
console.warn('Error fetching system avatar. Fallback image will be used.', error);
|
|
}
|
|
|
|
const fetchResult = await fetch('/api/characters/create', {
|
|
method: 'POST',
|
|
headers: getRequestHeaders({ omitContentType: true }),
|
|
body: formData,
|
|
cache: 'no-cache',
|
|
});
|
|
|
|
if (!fetchResult.ok) {
|
|
throw new Error(t`Creation request did not succeed.`);
|
|
}
|
|
|
|
await getCharacters();
|
|
}
|
|
|
|
export async function openPermanentAssistantCard() {
|
|
const avatar = getPermanentAssistantAvatar();
|
|
const characterId = characters.findIndex(x => x.avatar === avatar);
|
|
if (characterId === -1) {
|
|
toastr.info(t`Assistant not found. Try sending a chat message.`);
|
|
return;
|
|
}
|
|
|
|
await selectCharacterById(characterId);
|
|
}
|
|
|
|
/**
|
|
* Assigns a character as the assistant.
|
|
* @param {string?} characterId Character ID
|
|
*/
|
|
export function assignCharacterAsAssistant(characterId) {
|
|
if (characterId === undefined) {
|
|
return;
|
|
}
|
|
/** @type {Character} */
|
|
const character = characters[characterId];
|
|
if (!character) {
|
|
return;
|
|
}
|
|
|
|
const currentAssistantAvatar = getPermanentAssistantAvatar();
|
|
if (currentAssistantAvatar === character.avatar) {
|
|
if (character.avatar === defaultAssistantAvatar) {
|
|
toastr.info(t`${character.name} is a system assistant. Choose another character.`);
|
|
return;
|
|
}
|
|
|
|
toastr.info(t`${character.name} is no longer your assistant.`);
|
|
accountStorage.removeItem(assistantAvatarKey);
|
|
return;
|
|
}
|
|
|
|
accountStorage.setItem(assistantAvatarKey, character.avatar);
|
|
printCharactersDebounced();
|
|
toastr.success(t`Set ${character.name} as your assistant.`);
|
|
}
|
|
|
|
export function initWelcomeScreen() {
|
|
const events = [event_types.CHAT_CHANGED, event_types.APP_READY];
|
|
for (const event of events) {
|
|
eventSource.makeFirst(event, openWelcomeScreen);
|
|
}
|
|
|
|
eventSource.on(event_types.CHARACTER_MANAGEMENT_DROPDOWN, (target) => {
|
|
if (target !== 'set_as_assistant') {
|
|
return;
|
|
}
|
|
assignCharacterAsAssistant(this_chid);
|
|
});
|
|
|
|
eventSource.on(event_types.CHARACTER_RENAMED, (oldAvatar, newAvatar) => {
|
|
if (oldAvatar === getPermanentAssistantAvatar()) {
|
|
accountStorage.setItem(assistantAvatarKey, newAvatar);
|
|
}
|
|
});
|
|
}
|