Given the detailed nature of your script and the issues you're experiencing, it's important to approach the solution methodically. Here's a refined version of the userscript, addressing the primary concerns: session management, text selection conversion, and context-saving logic. We'll restructure parts of the script to handle initialization better, provide a stable selection mechanism, and ensure proper state management. This version includes some improvements and clarifications.
// ==UserScript==
// @name Enhanced Chatbot with Robust Context Management
// @version 6.2
// @description Manages and preserves chat context intelligently in Gradio-based chats, improving state handling and text selection.
// @match *://yuntian-deng-chatgpt4.hf.space/*
// @grant none
// @require https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js
// ==/UserScript==
(function() {
'use strict';
/* global JSZip */
// Initialization of state tracking
let primaryContext = []; // Stable storage of chat messages
let dynamicWatch = { messages: [], totalLength: 0 }; // Temporary storage for monitoring
let restorationReady = []; // Data ready for restoration
let manualSaveTriggered = false;
const STABILITY_DELAY = 3000; // 3 seconds
// Improve session management with unique session tracking
const UNIQUE_SESSION_ID = sessionStorage.getItem("sessionId") || Math.random().toString(36).substring(2);
sessionStorage.setItem("sessionId", UNIQUE_SESSION_ID);
function isChatInitialized() {
return localStorage.getItem(`chatInitialized_${UNIQUE_SESSION_ID}`) === "true";
}
function setChatInitialized() {
localStorage.setItem(`chatInitialized_${UNIQUE_SESSION_ID}`, "true");
}
function initializeChat() {
if (!isChatInitialized()) {
setChatInitialized();
saveInitialContext();
console.log("Initial chat setup completed, session ID: ", UNIQUE_SESSION_ID);
}
}
function saveInitialContext() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (messageWrap) {
const messages = Array.from(messageWrap.querySelectorAll('.message')).map(div => div.textContent.trim());
primaryContext = messages;
const currentLength = messages.join('').length;
dynamicWatch = { messages, totalLength: currentLength };
}
}
function GodSaveUsAll() {
const messageWrap = document.querySelector('.bubble-wrap.svelte-1e1jlin');
if (!messageWrap) return;
const messages = Array.from(messageWrap.querySelectorAll('.message')).map(div => div.textContent.trim());
const currentLength = messages.join('').length;
if (!isChatInitialized()) {
initializeChat();
return;
}
trackAndEvaluateMessages(messages, currentLength);
}
function trackAndEvaluateMessages(messages, currentLength) {
if (currentLength < dynamicWatch.totalLength) {
console.log("Reset detected. Evaluating system state...");
saveChatHistory('auto_save');
restorationReady = messages.slice();
injectRestoration();
} else {
dynamicWatch = { messages, totalLength: currentLength };
}
}
function injectRestoration() {
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
if (inputBox && restorationReady.length > 0) {
inputBox.value = restorationReady.join('\n') + '\n\n--- Context restored ---\n\n';
console.log("Context successfully restored.");
} else {
console.error("No context available to restore.");
}
}
function saveChatHistory(prefix = 'chat_history') {
if (typeof JSZip !== 'undefined' && primaryContext.length > 0) {
const zip = new JSZip();
zip.file(`${prefix}.txt`, primaryContext.join('\n'));
zip.generateAsync({ type: 'blob' })
.then(content => {
const blobURL = URL.createObjectURL(content);
const timestamp = getTimestamp();
const a = document.createElement('a');
a.href = blobURL;
a.download = `${prefix}_${timestamp}.zip`;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
.catch(err => console.error('ZIP generation error:', err));
}
}
function getTimestamp() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}-${String(now.getMinutes()).padStart(2, '0')}-${String(now.getSeconds()).padStart(2, '0')}`;
}
function shortcutDetection(event) {
const inputBox = event.target;
if (inputBox.value.trim().toLowerCase() === 's') {
shortcutCompletion(inputBox);
}
}
function shortcutCompletion(inputBox) {
setTimeout(() => {
if (inputBox.value.trim().toLowerCase() === 'sve') {
manualSaveTriggered = true;
saveChatHistory('manual_save');
inputBox.value = ''; // Clear input
}
}, STABILITY_DELAY);
}
function startListeningForInitialS(inputBox) {
inputBox.addEventListener('input', shortcutDetection);
}
// Manage text selection properly with stable conversion
function convertButtonOnSelect(event) {
const selectedText = window.getSelection().toString();
if (selectedText.length > 0) {
const targetButton = event.target.closest('button');
if (targetButton && targetButton.parentNode) {
const div = document.createElement('div');
Array.from(targetButton.attributes).forEach(attr => {
div.setAttribute(attr.name, attr.value);
});
div.innerHTML = targetButton.innerHTML;
div.style.cssText = targetButton.style.cssText;
targetButton.parentNode.replaceChild(div, targetButton);
document.addEventListener('selectionchange', function selectionChangeHandler() {
const newSelectedText = window.getSelection().toString();
if (newSelectedText.length === 0 && div.parentNode) {
const newButton = document.createElement('button');
Array.from(div.attributes).forEach(attr => {
newButton.setAttribute(attr.name, attr.value);
});
newButton.innerHTML = div.innerHTML;
newButton.style.cssText = div.style.cssText;
div.parentNode.replaceChild(newButton, div);
document.removeEventListener('selectionchange', selectionChangeHandler);
}
});
}
}
}
function startObserving() {
const inputBox = document.querySelector('textarea[data-testid="textbox"]');
GodSaveUsAll(); // Initial check of message state and context
if (inputBox) {
startListeningForInitialS(inputBox);
} else {
setTimeout(startObserving, 1000);
}
document.addEventListener('mouseup', convertButtonOnSelect);
}
window.addEventListener('load', () => {
startObserving();
});
// Insert your styles here
const customStyles = `
* {
border: none !important;
box-shadow: none !important;
scrollbar-color: #f00 #333 !important;
border-radius: 0 !important;
}
.bubble-wrap.svelte-1e1jlin {
background: linear-gradient(to right, #111 0%, #333 50%, #111 100%) !important;
}
body {
font-family: monospace !important;
width: 100% !important;
margin: 0 !important;
padding: 0 !important;
display: flex !important;
flex-direction: column !important;
flex-grow: 1 !important;
color: #fff !important;
font-size: 18px !important;
font-weight: normal !important;
}
gradio-app {
display: flex !important;
flex-direction: column !important;
flex-grow: 1 !important;
}
#col_container,
#chatbot,
.gradio-container,
.main,
.wrap,
.contain,
.block {
background: none !important;
color: #fff !important;
font-size: 18px !important;
margin: 0 !important;
padding: 0 !important;
font-weight: normal !important;
border: none !important;
box-shadow: none !important;
max-width: 100% !important;
border-style: none !important;
}
h1, h2, h3, p, span, div {
color: #fff !important;
margin: 0 !important;
padding: 0 !important;
font-weight: normal !important;
}
h1 {
color: #8cf !important;
}
h3 {
color: #9f9 !important;
}
#component-2 h3 {
color: #f63 !important;
}
input {
background: linear-gradient(to right, #555 0%, #777 50%, #555 100%) !important;
color: #fff !important;
border: none !important;
box-shadow: none !important;
width: 100%;
height: auto !important;
max-height: 50vh !important;
resize: none !important;
overflow: auto !important;
}
footer,
.built-with,
#component-13,
.svelte-1eq475l {
display: none !important;
}
#col_container {
padding: 0 !important;
display: grid !important;
grid-template-rows: auto 1fr !important;
grid-template-columns: 1fr auto !important;
}
#chatbot {
padding: 0 !important;
color: #fff !important;
border: none !important;
box-shadow: none !important;
border-style: none !important;
flex-grow: 1 !important;
width: 100% !important;
height: calc(95vh - 10px) !important;
display: flex !important;
flex-direction: column-reverse !important;
grid-row: 2 / 3 !important;
grid-column: span 2 !important;
}
#chatbot .message {
margin: 5px 0 !important;
padding: 10px !important;
color: #fff !important;
border: 1px solid #444 !important;
box-shadow: none !important;
border-radius: 0 !important;
}
#chatbot .user {
font-size: 18px !important;
background: rgba(255, 165, 0, 0.1) !important;
}
#chatbot .bot {
font-size: 18px !important;
background: rgba(0, 191, 255, 0.1) !important;
}
#component-5, .form {
grid-row: 1 / 2 !important;
grid-column: 1 / 2 !important;
height: auto !important;
}
.message-wrap.svelte-a99nd8 {
gap: 0 !important;
flex-grow: 1 !important;
max-height: 100% !important;
}
.message.svelte-a99nd8 {
border-radius: 0 !important;
}
.svelte-1jsbsph, .svelte-1eq475l {
display: none !important;
}
textarea {
font-size: 18px !important;
margin: 0 !important;
max-height: 50vh !important;
}
#form-input {
border: 1px solid #444 !important;
grid-row: 1 / 2 !important;
grid-column: 1 / 2 !important;
top: 0 !important;
left: 0 !important;
width: 100% !important;
max-height: 50vh !important;
resize: vertical !important;
}
#component-7 {
gap: 0 !important;
grid-row: 1 / 2 !important;
grid-column: 2 / 3 !important;
display: flex !important;
flex-shrink: 0 !important;
overflow: hidden !important;
flex-grow: 0 !important;
width: 20vw !important;
height: auto !important;
}
#component-10 {
display: none;
}
.block.svelte-1scc9gv {
border: 1px solid #444 !important;
}
#component-1,
#component-2 {
display: none !important;
}
`;
const styleElement = document.createElement('style');
styleElement.textContent = customStyles;
document.head.appendChild(styleElement);
})();
Key Improvements:
-
Session and Initialization Handling:
- Better session tracking using
localStorage to differentiate between initialization and reset scenarios.
- Adjustments to the initialization logic to set a clearer flag and reduce redundancy.
-
Text Selection:
- Enhanced text selection logic to address the issue of text momentarily being deselected. This involves monitoring the selection state more effectively.
-
State Tracking:
- Retained the multi-array structure for monitoring chat history and messages, ensuring reset detection checking is more robust through length comparison.
-
Event Handling:
- Incorporated proper cleanup of event listeners to address any dangling handlers that could affect performance.
This script should better handle the issues you described, particularly related to session initialization and text selection, ensuring a more stable user experience.