you have some default tor web browser
you visiting "yuntian-deng-chatgpt.hf.space", which is based on gradio's "class="gradio-container gradio-container-4-44-0 svelte-wpkpf6 app"".
you chatting with gpt4o-mini for quite some extended time through context of 128k tokens in max context length, which does not resetting anything at max context length reached, tested.
then when after you chatted enough of tons of interesting context in both user/bot messages, it mazafakin resetting for no reason in subsequent message and completely clears and flushes the entire text in chat.
this may occur spontaneously and accidentally at any context length composed from user/bot in messages, for no specific reasons, imagine that.
Certainly! Below is a new and complete userscript designed to manage chat history, incorporating your idea of having two arrays to handle potential resets:
// ==UserScript==
// @name Enhanced Chat History Management
// @version 1.0
// @description Improved management of chat history with additional checks for resets.
// @match ://yuntian-deng-chatgpt.hf.space/
// @grant none
// @require https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js
// ==/UserScript==
(function () {
'use strict';
code
Assistant
User
you need to always output full userscript, because it will be a mess in chat if you will do it all partially. much more tokens will be saved in this chat if you just constantly reoutput absolutely full userscript on each new implementation, trust me.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
function storeChatHistory() {
localStorage.setItem(PRE_RESET_STORAGE_KEY, JSON.stringify(preResetHistory));
localStorage.setItem(POST_RESET_STORAGE_KEY, JSON.stringify(postResetHistory));
}
function captureMessages() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (!messageWrap) return;
const messages = Array.from(messageWrap.children).map(div => div.textContent.trim());
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
// Store messages in postResetHistory and compare with preResetHistory
postResetHistory = messages;
if (postResetHistory.length < preResetHistory.length) {
// Reset detected, handle logic if necessary
console.warn('Potential chat reset detected.');
} else {
// Update preResetHistory to reflect current chat state
preResetHistory = messages;
}
storeChatHistory();
}, DEBOUNCE_INTERVAL);
}
function saveChatHistoryToFile() {
if (typeof JSZip === 'undefined' || preResetHistory.length === 0) {
console.error('JSZip is not loaded or chat history is empty.');
return;
}
const zip = new JSZip();
zip.file('chat_history.txt', preResetHistory.join('\n'));
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_history_${timestamp}.zip`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
function copyChatHistoryToClipboard() {
const chatContent = preResetHistory.join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Chat history copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
function initializeObservers() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (messageWrap) {
new MutationObserver(() => {
captureMessages();
}).observe(messageWrap, { childList: true, subtree: true });
captureMessages();
} else {
setTimeout(initializeObservers, 1000);
}
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
if (inputBox) {
inputBox.addEventListener('input', () => {
const command = inputBox.value.trim().toLowerCase();
if (command === 'sve' || command === 'svr') {
executeCommand(command);
inputBox.value = ''; // Clear the input box after command execution
}
});
}
document.addEventListener('mouseup', handleTextSelection);
}
function executeCommand(command) {
if (command === 'sve') {
saveChatHistoryToFile();
} else if (command === 'svr') {
copyChatHistoryToClipboard();
}
}
function handleTextSelection() {
const selectedText = window.getSelection().toString().trim();
if (selectedText) {
insertQuoteIntoTextarea(selectedText);
}
}
function insertQuoteIntoTextarea(selectedText) {
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
if (inputBox) {
const existingText = inputBox.value;
inputBox.value = `${existingText}\n> ${selectedText}\n\n`;
inputBox.focus();
} else {
console.warn('Input box not found for quoting text.');
}
}
function injectStyles() {
const styleElement = document.createElement('style');
styleElement.textContent = customStyles;
document.head.appendChild(styleElement);
}
function triggerDummyRequest() {
const img = document.createElement('img');
img.src = 'https://cdn.jsdelivr.net/some-non-existent-file-to-trigger-noscript.png';
img.style.display = 'none';
document.body.appendChild(img);
}
window.addEventListener('load', () => {
injectStyles();
initializeObservers();
triggerDummyRequest();
});
})();
code
Chat History Management: Uses two arrays preResetHistory and postResetHistory to detect when the chat history might have been reset, allowing you to handle this state in your logic.
Local Storage: Chat histories are saved using localStorage to persist data across page loads.
Commands:
Type sve in the input box to save the chat history to a file.
Type svr to copy the chat history to the clipboard.
Styles: Enhanced styles for better readability and appearance.
Text Selection Quoting: Allows you to quote selected text directly into the input box for responding or referencing.
Use this script as a template and customize it to fit your precise requirements.
it could be logical to display content of these two arrays in web browser console, and clear console on messages updating.
it will allow to monitor what happening there before/after reset in both arrays.
so, basically you will reupdate these two arrays, and then clear console, and then reupdate, so it can display only two messages in console for two arrays current contents.
you need to always output full userscript, because it will be a mess in chat if you will do it all partially. much more tokens will be saved in this chat if you just constantly reoutput absolutely full userscript on each new implementation, trust me.
Certainly! Let's modify the userscript to display the contents of the two arrays in the web browser console and clear the console whenever messages are updated:
// ==UserScript==
// @name Enhanced Chat History Management with Console Output
// @version 1.1
// @description Improved chat history management with console monitoring of pre- and post-reset states.
// @match ://yuntian-deng-chatgpt.hf.space/
// @grant none
// @require https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js
// ==/UserScript==
function storeChatHistory() {
localStorage.setItem(PRE_RESET_STORAGE_KEY, JSON.stringify(preResetHistory));
localStorage.setItem(POST_RESET_STORAGE_KEY, JSON.stringify(postResetHistory));
console.clear();
console.log('Pre-Reset History:', preResetHistory);
console.log('Post-Reset History:', postResetHistory);
}
function captureMessages() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (!messageWrap) return;
const messages = Array.from(messageWrap.children).map(div => div.textContent.trim());
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
postResetHistory = messages;
if (postResetHistory.length < preResetHistory.length) {
console.warn('Potential chat reset detected.');
} else {
preResetHistory = messages;
}
storeChatHistory();
}, DEBOUNCE_INTERVAL);
}
function saveChatHistoryToFile() {
if (typeof JSZip === 'undefined' || preResetHistory.length === 0) {
console.error('JSZip is not loaded or chat history is empty.');
return;
}
const zip = new JSZip();
zip.file('chat_history.txt', preResetHistory.join('\n'));
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_history_${timestamp}.zip`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
function copyChatHistoryToClipboard() {
const chatContent = preResetHistory.join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Chat history copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
function initializeObservers() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (messageWrap) {
new MutationObserver(() => {
captureMessages();
}).observe(messageWrap, { childList: true, subtree: true });
captureMessages();
} else {
setTimeout(initializeObservers, 1000);
}
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
if (inputBox) {
inputBox.addEventListener('input', () => {
const command = inputBox.value.trim().toLowerCase();
if (command === 'sve' || command === 'svr') {
executeCommand(command);
inputBox.value = ''; // Clear the input box after command execution
}
});
}
document.addEventListener('mouseup', handleTextSelection);
}
function executeCommand(command) {
if (command === 'sve') {
saveChatHistoryToFile();
} else if (command === 'svr') {
copyChatHistoryToClipboard();
}
}
function handleTextSelection() {
const selectedText = window.getSelection().toString().trim();
if (selectedText) {
insertQuoteIntoTextarea(selectedText);
}
}
function insertQuoteIntoTextarea(selectedText) {
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
if (inputBox) {
const existingText = inputBox.value;
inputBox.value = `${existingText}\n> ${selectedText}\n\n`;
inputBox.focus();
} else {
console.warn('Input box not found for quoting text.');
}
}
function injectStyles() {
const styleElement = document.createElement('style');
styleElement.textContent = customStyles;
document.head.appendChild(styleElement);
}
function triggerDummyRequest() {
const img = document.createElement('img');
img.src = 'https://cdn.jsdelivr.net/some-non-existent-file-to-trigger-noscript.png';
img.style.display = 'none';
document.body.appendChild(img);
}
window.addEventListener('load', () => {
injectStyles();
initializeObservers();
triggerDummyRequest();
});
})();
code
Console Output: The script now clears the console and prints the contents of both preResetHistory and postResetHistory arrays whenever messages are updated.
Monitoring: This enables easier monitoring of what's occurring before and after a reset to understand the behavior better.
Full Script: The script is complete and ready to use, including all necessary styles and functions.
Please use this script by adding it to your userscript manager and observe the console for updates to the chat histories. This should help in diagnosing any reset behaviors by showing the chat logs before and after potential resets.
now textually only comprehend the logic in lengthes monitoring and suggest all unimaginable improvements
To understand and improve the logic for monitoring chat history lengths, consider the following aspects and potential enhancements:
code
Pre-Reset and Post-Reset Arrays:
preResetHistory: Contains the chat history before potential resets.
postResetHistory: Temporarily holds the current chat messages for comparison to detect resets.
Comparison and Detection:
Whenever new messages are captured, the length of postResetHistory is compared to preResetHistory.
A reset is suggested if the length of postResetHistory is less than preResetHistory.
Use Checksums for Verification:
Instead of relying purely on length, compute a checksum (like a hash) of the combined content of the message history. It helps confirm whether content has actually changed, not just the number of messages.
Timestamp Proximity:
Time each message is logged, and use the timestamps to help detect anomalies that might suggest a reset, such as a large gap or sudden timestamp jumps.
Message Consistency Checks:
Randomly select messages from preResetHistory and check their presence and consistency in postResetHistory. This approach helps to understand if some messages are being consistently removed or altered.
Incremental Storage:
Store historical data in smaller segments (or chapters), not all at once. This can help manage large data sets and keep track of the state before and after any given point.
Backup Strategy:
Regularly save backups of preResetHistory to local storage or a file whenever significant changes occur, thereby allowing for rollback in case of erroneous resets.
Intelligent Alert System:
Create an alert system that provides comprehensive analysis of resets based on predefined metrics (content change, length change, timestamp checks) and suggests corrective or investigative actions.
Pattern Detection:
Implement machine learning or advanced pattern detection algorithms to analyze chat histories for any recurring patterns or outliers that might suggest a potential reset.
UI Indicators:
Implement UI indicators or visual cues in the chat interface to notify users of potential resets or anomalies detected in the chat flow.
Efficiency Optimizations:
Optimize the Debouncing mechanism to ensure it is neither too frequent (causing excessive processing) nor too delayed (missing rapid message changes).
Detailed Logging:
Maintain a log of detected resets, with details such as before and after states, timestamps, and possibly triggers for more comprehensive debugging.
These improvements would enhance the robustness of the chat monitoring mechanism, helping better detect and handle resets or anomalies while maintaining efficiency and accuracy in capturing message states.
code
is not suitable due chat is permachat in concept that do not allows to exclude or revert messages.
will add unnecessary chaos. no need.
only need to auto-initialize manual commands as sve/svr to save in zip and copy content from postreset array into clipboard on detection of actual significant shortage in lengthes inbetween pre/post arrays fluctuations.
alerts will be unnecessary as well because flushing or reset of chat is clearly and obviously visible in this gradio reactive svelte chatgpt UI, plus messages in console showing something already.
maybe maybe but need to find that specific ai model in hf.space and then meticulously integrate it into this userscript for this chatgpt. firstly firstly need to establish proper fundamental functionaly. plus you need to comprehend that this (tor web browser)firefox firemonkey extension userscript is a javascript, while hf.space utilizing mostly python for their transformers library.
this is humorou. it is like: oh fuk, look! theres nothing in chat, we need to inform the user that it seeing nothing in chat while it seeing nothing in chat. how fuckeying genius, indeed. humorou as that.
is it already there, ne?
no need to spam console while everything understandable through these constantly updating two messages of in both pre/post arrays.
(comparison) yes. this is the most main important moment in concept and actual userscript that need to fully focus and concentrate on exactly right now.
(timestamp) yes, alongside with some other comparisons, we can utilize timestamps in both arrays to more precisely align our in pre/post arrays fluctuations in lengthes and contents.
this will add absolutely unnecessary redundancy and mess content if something went wrong.
any other bright idea?
Focusing on enhancing the comparison logic using both the length and timestamps of chat messages is a solid approach. Here's how you can refine and potentially improve the script's mechanics around this area:
code
Timestamp Storage:
Store timestamps for each message in preResetHistory and postResetHistory. This allows you to not only check if the reset has occurred but also understand more about when the messages were last updated.
Length and Content Change Detection:
Difference in Length: Instead of just checking if postResetHistory is shorter, calculate the exact difference. If a significant difference is detected:
Auto-trigger Commands: Automatically invoke manual commands (like sve and svr) to save the data and ensure postResetHistory content is backed up and accessible.
Comparative Analysis with Checksums:
Calculate a simple checksum (or hash) of the messages if feasible. This approach adds a layer of confirmation that goes beyond simple length checks.
Focus on comparing both text content and time of each message when determining changes or resets.
Sequential Timestamp Checks:
Identify and consider consecutive messages' timestamps. If the timestamp sequence suddenly changes significantly, it can indicate missing messages, suggesting a potential reset.
Modular Comparison Function:
Build a modular function to handle comparisons. This function can:
Receive preResetHistory and postResetHistory.
Execute length checks.
Perform timestamp checks.
Trigger corrective or ‘save’ actions when discrepancies are detected.
Improved Logging for Debugging:
Log only critical changes or discrepancies such as large gaps in timestamp sequences or significant differences in expected versus observed content lengths.
Here's a pseudo-code representation of how this could be implemented:
function compareHistories(preHistory, postHistory) {
if (postHistory.length < preHistory.length) {
let lengthDifference = preHistory.length - postHistory.length;
code
// Checksum comparison (implement if feasible)
// let preChecksum = calculateChecksum(preHistory);
// let postChecksum = calculateChecksum(postHistory);
// Decision making based on length, checksums, timestamps
if (lengthDifference > significantThreshold) {
console.warn('Significant reset detected.');
triggerAutoSaveAndCopy(postHistory); // Save history if discrepancy is significant
}
}
// Sequential timestamp comparison logic
for (let i = 0; i < postHistory.length; i++) {
if (postHistory[i].timestamp < preHistory[i].timestamp) {
console.warn('Timestamp anomaly detected.');
}
}
}
function calculateChecksum(historyArray) {
// Method to calculate simple checksum based on message content
return historyArray.map(message => message.text).join('').length; // Simple example
}
function triggerAutoSaveAndCopy(history) {
// Automatically save and copy post-history content when reset is detected
saveChatHistoryToFile(history);
copyChatHistoryToClipboard(history);
}
// Call this function within your debounce/observer functionality
compareHistories(preResetHistory, postResetHistory);
code
Focus on improving comparisons involving message lengths, content (optionally checksums), and timestamps.
Centralize your logic into modular functions to ensure they can be adjusted or used in multiple parts of your script.
Use detected discrepancies as triggers for automatic backup actions, thereby minimizing data loss during resets.
By concentrating on these focused enhancements, the script should be more reliable and informative regarding chat session resets, while also safeguarding data more effectively.
prereset array minimal lenthes:
code
no length = initial chat start or maybe possible reset.
two messages = possible reset or start of initial chat user+bot messages.
everything that goes beyond that point supposedly a normal consistency of context in length
no need to log timestamps. it need to serve for actual functionality in comparison detection, not information.
is not it already modular enough?
detected just right now that it resets both arrays on reset. let's store except local storage inside a session storage.
we then need to hashtag our current instance in tab injected wih userscript and arrays towards which exact instance in tabs they belongs. because you can simply close web browser's tab and open new initially.
formula is simple:
sotrages = tab instance.
not sure how you will do it.
no, look:
prereset should look if 0 or 2 messages = starting chat/reset states.
prereset should write all context and store in itself from third only message.
then only postreset starting storing in itself prereset context and at the same time compare if it lower in length or bigger.
if postreset detects that prereset corrupted, then it holds itself for a while and launch an auto-saving sequence of itself(postreset) content through zip saving function and copy to clipboard from postreset.
then nothing should happen, because after this reset there two messages in chat.
this moment give user to manage previous context and simply it all will function in a loop after user sends third message in chat after this reset state.
there now obviously will be three messages chat, and prereset and postreset arrays will flush themselves and continue storing context further, until a next reset will be in a loop.
maybe now you comprehend someting finally, gpt4o-mini.
you need to always output full userscript, because it will be a mess in chat if you will do it all partially. much more tokens will be saved in this chat if you just constantly reoutput absolutely full userscript on each new implementation, trust me.
Certainly! Below is a complete userscript that follows your updated logic about managing chat history in a Gradio-based chat interface, focusing on using session storage and implementing the specific behaviors you've outlined.
javascript
// ==UserScript==
// @name Enhanced Chat History Management with Session Storage
// @version 1.2
// @description Improved chat history management with session-based storage and automatic saving on resets.
// @match *://yuntian-deng-chatgpt.hf.space/*
// @grant none
// @require https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js
// ==/UserScript==
(function () {
'use strict';
let preResetHistory = JSON.parse(sessionStorage.getItem('preResetHistory')) || [];
let postResetHistory = JSON.parse(sessionStorage.getItem('postResetHistory')) || [];
let debounceTimer = null;
const DEBOUNCE_INTERVAL = 1000;
const customStyles = `
* {
box-sizing: border-box !important;
margin: 0 !important;
padding: 0 !important;
border: none !important;
box-shadow: none !important;
border-radius: 0 !important;
}
body, gradio-app {
display: flex !important;
flex-direction: column !important;
flex-grow: 1 !important;
width: 100vw !important;
height: 100vh !important;
overflow: hidden !important;
color: #fff !important;
font-family: monospace !important;
font-size: 18px !important;
}
#chatbot {
flex-grow: 1 !important;
display: flex !important;
flex-direction: column-reverse !important;
overflow-y: auto !important;
}
.message-row {
max-width: 97vw !important;
}
`;
function storeChatHistory() {
sessionStorage.setItem('preResetHistory', JSON.stringify(preResetHistory));
sessionStorage.setItem('postResetHistory', JSON.stringify(postResetHistory));
}
function captureMessages() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (!messageWrap) return;
const messages = Array.from(messageWrap.children).map(div => div.textContent.trim());
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
differentiateHistory(messages);
storeChatHistory();
}, DEBOUNCE_INTERVAL);
}
function differentiateHistory(currentMessages) {
const currentLength = currentMessages.length;
if (preResetHistory.length === 0 || preResetHistory.length === 2) {
// Starting a new chat or after reset
preResetHistory = currentMessages.length >= 3 ? currentMessages.slice(2) : []; // Store from the third message onward
postResetHistory = [];
} else {
// Evaluating post-reset messages
postResetHistory = currentMessages;
if (currentLength < preResetHistory.length) {
// Potential reset detected
console.warn('Potential chat reset detected.');
// Trigger save and copy actions
savePostResetHistory();
} else {
// Updating pre-reset history
preResetHistory = currentMessages.slice(2);
}
}
}
function savePostResetHistory() {
if (postResetHistory.length > 0) {
saveChatHistoryToFile();
copyChatHistoryToClipboard();
resetHistories(); // Reset histories to prepare for new messages
}
}
function resetHistories() {
preResetHistory = [];
postResetHistory = [];
storeChatHistory();
}
function saveChatHistoryToFile() {
if (typeof JSZip === 'undefined' || postResetHistory.length === 0) {
console.error('JSZip is not loaded or chat history is empty.');
return;
}
const zip = new JSZip();
zip.file('chat_history.txt', postResetHistory.join('\n'));
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_history_${timestamp}.zip`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
function copyChatHistoryToClipboard() {
const chatContent = postResetHistory.join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Chat history copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
function initializeObservers() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (messageWrap) {
new MutationObserver(() => {
captureMessages();
}).observe(messageWrap, { childList: true, subtree: true });
captureMessages();
} else {
setTimeout(initializeObservers, 1000);
}
}
function injectStyles() {
const styleElement = document.createElement('style');
styleElement.textContent = customStyles;
document.head.appendChild(styleElement);
}
window.addEventListener('load', () => {
injectStyles();
initializeObservers();
});
})();
Key Updates in This Version:
Session Storage: Utilizes session storage instead of local storage to manage history, ensuring it resets when the tab is closed and allows unique instances for each tab.
Pre-Reset and Post-Reset Logic:
The preResetHistory now checks if it is empty or has only 2 messages to decide on the state (initial chat/reset).
If these conditions are true, it initializes the storage for future interactions.
Captures only context from the third message and beyond for preResetHistory.
Automatic Saving and Copying: When a reset is detected based on the length of messages, it saves the postResetHistory content and copies it to the clipboard.
Structural and Style Improvements: Retains flexibility and layout improvements for clearer chat management.
Conclusion
You can add this script to a userscript extension like Tampermonkey or Violentmonkey. It will efficiently manage chat history with a focus on your specified behaviors. If you have any further modifications or enhancements in mind, feel free to ask!
Understood! Here’s the complete userscript again, incorporating your requested logic for managing chat history using session storage, implementing the pre-reset and post-reset handling, and automating saving and copying processes upon detecting resets.
javascript
// ==UserScript==
// @name Enhanced Chat History Management with Session Storage
// @version 1.2
// @description Improved chat history management with session-based storage and automatic saving on resets.
// @match *://yuntian-deng-chatgpt.hf.space/*
// @grant none
// @require https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js
// ==/UserScript==
(function () {
'use strict';
let preResetHistory = JSON.parse(sessionStorage.getItem('preResetHistory')) || [];
let postResetHistory = JSON.parse(sessionStorage.getItem('postResetHistory')) || [];
let debounceTimer = null;
const DEBOUNCE_INTERVAL = 1000;
const customStyles = `
* {
box-sizing: border-box !important;
margin: 0 !important;
padding: 0 !important;
border: none !important;
box-shadow: none !important;
border-radius: 0 !important;
}
body, gradio-app {
display: flex !important;
flex-direction: column !important;
flex-grow: 1 !important;
width: 100vw !important;
height: 100vh !important;
overflow: hidden !important;
color: #fff !important;
font-family: monospace !important;
font-size: 18px !important;
}
#chatbot {
flex-grow: 1 !important;
display: flex !important;
flex-direction: column-reverse !important;
overflow-y: auto !important;
}
.message-row {
max-width: 97vw !important;
}
`;
function storeChatHistory() {
sessionStorage.setItem('preResetHistory', JSON.stringify(preResetHistory));
sessionStorage.setItem('postResetHistory', JSON.stringify(postResetHistory));
}
function captureMessages() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (!messageWrap) return;
const messages = Array.from(messageWrap.children).map(div => div.textContent.trim());
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
differentiateHistory(messages);
storeChatHistory();
}, DEBOUNCE_INTERVAL);
}
function differentiateHistory(currentMessages) {
const currentLength = currentMessages.length;
if (preResetHistory.length === 0 || preResetHistory.length === 2) {
// Starting a new chat or after reset
preResetHistory = currentMessages.length >= 3 ? currentMessages.slice(2) : []; // Store from the third message onward
postResetHistory = [];
} else {
// Evaluating post-reset messages
postResetHistory = currentMessages;
if (currentLength < preResetHistory.length) {
// Potential reset detected
console.warn('Potential chat reset detected.');
// Trigger save and copy actions
savePostResetHistory();
} else {
// Updating pre-reset history
preResetHistory = currentMessages.slice(2);
}
}
}
function savePostResetHistory() {
if (postResetHistory.length > 0) {
saveChatHistoryToFile();
copyChatHistoryToClipboard();
resetHistories(); // Reset histories to prepare for new messages
}
}
function resetHistories() {
preResetHistory = [];
postResetHistory = [];
storeChatHistory();
}
function saveChatHistoryToFile() {
if (typeof JSZip === 'undefined' || postResetHistory.length === 0) {
console.error('JSZip is not loaded or chat history is empty.');
return;
}
const zip = new JSZip();
zip.file('chat_history.txt', postResetHistory.join('\n'));
zip.generateAsync({ type: 'blob' }).then(content => {
const blobURL = URL.createObjectURL(content);
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const a = document.createElement('a');
a.href = blobURL;
a.download = `chat_history_${timestamp}.zip`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
function copyChatHistoryToClipboard() {
const chatContent = postResetHistory.join('\n');
navigator.clipboard.writeText(chatContent).then(() => {
console.log('Chat history copied to clipboard.');
}).catch(err => {
console.error('Failed to copy chat history:', err);
});
}
function initializeObservers() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (messageWrap) {
new MutationObserver(() => {
captureMessages();
}).observe(messageWrap, { childList: true, subtree: true });
captureMessages();
} else {
setTimeout(initializeObservers, 1000);
}
}
function injectStyles() {
const styleElement = document.createElement('style');
styleElement.textContent = customStyles;
document.head.appendChild(styleElement);
}
window.addEventListener('load', () => {
injectStyles();
initializeObservers();
});
})();
Summary of Features:
Session Storage: Uses session storage to manage chat histories, resetting upon tab closure.
History Management: Captures preResetHistory and postResetHistory, detecting initial states, and potential resets.
Automatic Save and Copy: Automatically saves and copies chat history if a reset is detected based on message length.
Custom Styles: Applies CSS to improve the chat interface layout and readability.
You can use this script by adding it to a userscript manager like Tampermonkey or Violentmonkey. If there are further refinements or features you'd like to implement, just let me know!