diff --git a/public/script.js b/public/script.js index b1562b462..6bdde6824 100644 --- a/public/script.js +++ b/public/script.js @@ -119,7 +119,6 @@ import { end_trim_to_sentence, countOccurrences, isOdd, - isElementInViewport, sortMoments, timestampToMoment, download, @@ -3410,7 +3409,15 @@ async function renameCharacter() { // Also rename as a group member await renameGroupMember(oldAvatar, newAvatar, newValue); - callPopup('

Character renamed!

Sprites folder (if any) should be renamed manually.', 'text'); + const renamePastChatsConfirm = await callPopup(`

Character renamed!

+

Past chats will still contain the old character name. Would you like to update the character name in previous chats as well?

+ Sprites folder (if any) should be renamed manually.`, 'confirm'); + + if (renamePastChatsConfirm) { + await renamePastChats(newAvatar, newValue); + await reloadCurrentChat(); + toastr.success('Character renamed and past chats updated!'); + } } else { throw new Error('Newly renamed character was lost?'); @@ -3428,6 +3435,59 @@ async function renameCharacter() { } } +async function renamePastChats(newAvatar, newValue) { + const pastChats = await getPastCharacterChats(); + + for (const { file_name } of pastChats) { + try { + const fileNameWithoutExtension = file_name.replace('.jsonl', ''); + const getChatResponse = await fetch('/getchat', { + method: 'POST', + headers: getRequestHeaders(), + body: JSON.stringify({ + ch_name: newValue, + file_name: fileNameWithoutExtension, + avatar_url: newAvatar, + }), + cache: 'no-cache', + }); + + if (getChatResponse.ok) { + const currentChat = await getChatResponse.json(); + + for (const message of currentChat) { + if (message.is_user || message.is_system || message.extra?.type == system_message_types.NARRATOR) { + continue; + } + + if (message.name !== undefined) { + message.name = newValue; + } + } + + const saveChatResponse = await fetch('/savechat', { + method: "POST", + headers: getRequestHeaders(), + body: JSON.stringify({ + ch_name: newValue, + file_name: fileNameWithoutExtension, + chat: currentChat, + avatar_url: newAvatar, + }), + cache: 'no-cache', + }); + + if (!saveChatResponse.ok) { + throw new Error('Could not save chat'); + } + } + } catch (error) { + toastr.error(`Past chat could not be updated: ${file_name}`); + console.error(error); + } + } +} + async function saveChat(chat_name, withMetadata) { const metadata = { ...chat_metadata, ...(withMetadata || {}) }; let file_name = chat_name ?? characters[this_chid].chat;