-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlmsys-optimize-usage.js
More file actions
431 lines (388 loc) · 13.5 KB
/
Copy pathlmsys-optimize-usage.js
File metadata and controls
431 lines (388 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// ==UserScript==
// @name lmsys-enhancer
// @namespace http://tampermonkey.net/
// @version 0.7
// @description Optimize your experience on the chat.lmsys.org with the `lmsys-enhancer` Tampermonkey script.
// @author joshlee
// @match https://chat.lmsys.org/
// @icon https://www.google.com/s2/favicons?sz=64&domain=lmsys.org
// @grant none
// @license MIT
// ==/UserScript==
const scriptConfig = {
model: "gpt-4-turbo",
loadLatestSession: true,
firstMeetSessionHash: true,
firstSend: true,
currentSessionHash: "",
dataKey: "session_hash_history",
mainColor: "#DE6B2F",
drawerWidth: 250,
position: {
main: "#component-1",
changeModel: "#model_selector_row label",
directChat: ".tab-nav.scroll-hide button:nth-child(3)",
maxOutputTokenInput: "//span[text()='Max output tokens']/../../input",
maxOutputTokenBar: "//span[text()='Max output tokens']/../../../../input",
sendBtn: '//button[text()="Send"]',
unnecessaryList: ["#component-93", "#component-83"],
},
};
const originalSend = WebSocket.prototype.send;
var itemList;
function $x(xpathToExecute) {
var result = [];
var nodesSnapshot = document.evaluate(
xpathToExecute,
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
for (var i = 0; i < nodesSnapshot.snapshotLength; i++) {
result.push(nodesSnapshot.snapshotItem(i));
}
return result;
}
function removeUselessElements() {
// Remove unnecessary notices and components
document
.querySelectorAll("#notice_markdown")
.forEach((elem) => elem.remove());
scriptConfig.position.unnecessaryList.forEach((v) => {
const componentToRemove = document.querySelector(v);
if (componentToRemove) componentToRemove.remove();
});
}
function setMaxOutputToken(maxValue = 4096) {
// Set the maximum token output to the desired value
const [, , input] = $x(scriptConfig.position.maxOutputTokenInput);
const [, , bar] = $x(scriptConfig.position.maxOutputTokenBar);
if (!input || !bar) {
console.error("Set max output token failure!");
return;
}
input.value = String(maxValue);
bar.max = String(maxValue);
bar.value = String(maxValue);
const changeEvent = new Event("change", { bubbles: true, cancelable: true });
bar.dispatchEvent(changeEvent);
}
function changeModel(model) {
document.querySelector(scriptConfig.position.changeModel).click();
document.querySelector(`li[data-value=${model}]`).dispatchEvent(
new MouseEvent("mousedown", {
view: window,
bubbles: true,
cancelable: true,
})
);
}
function hackWsSend(data) {
let d = JSON.parse(data);
// get session_hash
if (d.session_hash) {
// first create session
if (scriptConfig.firstMeetSessionHash) {
scriptConfig.currentSessionHash = d.session_hash;
scriptConfig.firstMeetSessionHash = false;
}
if (
scriptConfig.loadLatestSession &&
d.fn_index === 38 &&
getLastestSessionToggleBtn()
) {
// skip creat new session
d.fn_index = 41;
d.data = [null, scriptConfig.model, ""];
originalSend.call(this, data);
toggleLastestSession();
return;
}
// first send message
if (scriptConfig.firstSend && d.fn_index === 39) {
saveCurrentSession();
scriptConfig.firstSend = false;
}
// modify session_hash
if (scriptConfig.currentSessionHash) {
d.session_hash = scriptConfig.currentSessionHash;
data = JSON.stringify(d);
}
}
originalSend.call(this, data);
}
function createSessionItem(text, sessionHash) {
var itemContainer = document.createElement("div");
itemContainer.style.display = "flex";
itemContainer.style.justifyContent = "space-between";
itemContainer.style.alignItems = "center";
itemContainer.style.padding = "10px";
itemContainer.style.borderBottom = "1px solid #ccc";
itemContainer.className = "session-item-container";
itemContainer.setAttribute("data-session-hash", sessionHash);
var itemText = document.createElement("div");
itemText.textContent = text;
itemContainer.appendChild(itemText);
// Create toggle session button
var toggleButton = document.createElement("button");
toggleButton.textContent = "⇢";
toggleButton.style.marginLeft = "5px";
toggleButton.style.padding = "5px 10px";
toggleButton.style.border = "none";
toggleButton.style.borderRadius = "4px";
toggleButton.style.backgroundColor = "#4CAF50";
toggleButton.style.color = "white";
toggleButton.style.cursor = "pointer";
// Button hover effect
toggleButton.addEventListener("mouseover", function () {
this.style.backgroundColor = "#45a049";
});
toggleButton.addEventListener("mouseout", function () {
this.style.backgroundColor = "#4CAF50";
});
toggleButton.addEventListener("click", function () {
scriptConfig.currentSessionHash = sessionHash;
clickSendBtn();
});
itemContainer.appendChild(toggleButton);
// Create Delete button
var deleteButton = document.createElement("button");
deleteButton.textContent = "✖";
deleteButton.style.marginLeft = "5px";
deleteButton.style.padding = "5px 10px";
deleteButton.style.border = "none";
deleteButton.style.borderRadius = "4px";
deleteButton.style.backgroundColor = "#f44336";
deleteButton.style.color = "white";
deleteButton.style.cursor = "pointer";
// Button hover effect
deleteButton.addEventListener("mouseover", function () {
this.style.backgroundColor = "#e53935";
});
deleteButton.addEventListener("mouseout", function () {
this.style.backgroundColor = "#f44336";
});
deleteButton.addEventListener("click", function () {
removeSessionHash(sessionHash);
itemContainer.remove();
});
itemContainer.appendChild(deleteButton);
itemContainer.highlight = function () {
itemContainer.classList.add("highlighted-session");
toggleButton.classList.add("disabled-button");
deleteButton.classList.add("disabled-button");
};
itemContainer.unhighlight = function () {
itemContainer.classList.remove("highlighted-session");
toggleButton.classList.remove("disabled-button");
deleteButton.classList.remove("disabled-button");
};
if (sessionHash === scriptConfig.currentSessionHash) {
itemContainer.highlight();
}
itemList.appendChild(itemContainer);
updateHighlightedSessions();
}
function createHistorySessionElement() {
// Create Float Button
var floatButton = document.createElement("button");
floatButton.textContent = "☰";
floatButton.style.position = "fixed";
floatButton.style.left = "20px";
floatButton.style.top = "50%";
floatButton.style.transform = "translateY(-50%)";
floatButton.style.zIndex = "9999";
floatButton.style.padding = "15px";
floatButton.style.borderRadius = "100%";
floatButton.style.backgroundColor = "#212936";
floatButton.style.color = "white";
floatButton.style.border = "none";
floatButton.style.boxShadow = "0 2px 5px rgba(0,0,0,0.3)";
floatButton.style.transition = "left 0.3s ease";
floatButton.style.cursor = "pointer";
floatButton.addEventListener("click", function () {
if (drawer.style.left === `-${scriptConfig.drawerWidth}px`) {
drawer.style.left = "0";
floatButton.style.left = `${scriptConfig.drawerWidth}px`;
} else {
drawer.style.left = `-${scriptConfig.drawerWidth}px`;
floatButton.style.left = "20px";
}
});
document.body.appendChild(floatButton);
// Create drawer container
var drawer = document.createElement("div");
drawer.style.position = "fixed";
drawer.style.left = "-250px";
drawer.style.top = "0";
drawer.style.width = `${scriptConfig.drawerWidth}px`;
drawer.style.height = "100%";
drawer.style.backgroundColor = "#212936";
drawer.style.transition = "0.3s";
drawer.style.zIndex = "9998";
drawer.style.padding = "15px";
drawer.style.boxSizing = "border-box";
drawer.style.color = "white";
drawer.style.overflowY = "auto";
document.body.appendChild(drawer);
// Create Deawer Title
var drawerTitle = document.createElement("h2");
drawerTitle.textContent = "History Session";
drawerTitle.style.padding = "10px";
drawerTitle.style.marginTop = "0";
drawerTitle.style.color = "white";
drawerTitle.style.backgroundColor = "#2c3e50";
drawerTitle.style.borderBottom = "1px solid #ccc";
drawer.appendChild(drawerTitle);
// Create session item container
itemList = document.createElement("div");
drawer.appendChild(itemList);
// Click outside the drawer to turn off the drawer's function
document.addEventListener("click", function (event) {
// Check if the click is happening outside of the drawer or floating button
if (!drawer.contains(event.target) && !floatButton.contains(event.target)) {
updateHighlightedSessions();
// Opened
if (drawer.style.left === "0px") {
drawer.style.left = `-${scriptConfig.drawerWidth}px`; // hidden
floatButton.style.left = "20px"; // restore
}
}
});
// Create New Chat Button
const newChatButton = document.createElement("button");
newChatButton.textContent = "New Chat";
newChatButton.style.position = "absolute";
newChatButton.style.bottom = "20px";
newChatButton.style.left = "50%";
newChatButton.style.transform = "translateX(-50%)";
newChatButton.style.padding = "10px 30px";
newChatButton.style.border = "none";
newChatButton.style.borderRadius = "5px";
newChatButton.style.backgroundColor = scriptConfig.mainColor;
newChatButton.style.color = "white";
newChatButton.style.cursor = "pointer";
newChatButton.addEventListener("click", function () {
handleNewChatClick();
});
drawer.appendChild(newChatButton);
loadSessionHashHistory();
}
function handleNewChatClick() {
scriptConfig.currentSessionHash = Math.random().toString(36).substring(2);
scriptConfig.firstMeetSessionHash = true;
scriptConfig.firstSend = true;
scriptConfig.loadLatestSession = false;
clickSendBtn();
}
// Update the highlighted state of the session list
function updateHighlightedSessions() {
const sessionItems = itemList.getElementsByClassName(
"session-item-container"
);
for (const item of sessionItems) {
item.unhighlight(); // remove all highlight state
}
const newItem = itemList.querySelector(
`[data-session-hash="${scriptConfig.currentSessionHash}"]`
);
if (newItem) {
newItem.highlight();
return;
}
}
function getLastestSessionToggleBtn() {
const gotoBtn = document.querySelectorAll(
".session-item-container button"
)[0];
return gotoBtn;
}
function toggleLastestSession() {
scriptConfig.firstSend = false;
scriptConfig.firstMeetSessionHash = false;
getLastestSessionToggleBtn().click();
}
function loadSessionHashHistory() {
itemList.innerHTML = "";
const list = JSON.parse(localStorage.getItem(scriptConfig.dataKey)) || [];
for (let i = list.length - 1; i >= 0; i--) {
let e = list[i];
createSessionItem(e.time, e.session_hash);
}
updateHighlightedSessions();
}
function getCurrentFormattedTime() {
const now = new Date();
const year = now.getFullYear().toString(); // year
const month = (now.getMonth() + 1).toString().padStart(2, "0"); // month
const date = now.getDate().toString().padStart(2, "0"); // day
const hours = now.getHours().toString().padStart(2, "0"); // hout
const minutes = now.getMinutes().toString().padStart(2, "0");
return `${year}-${month}-${date} ${hours}:${minutes}`;
}
function removeSessionHash(targetSessionHash) {
const list = JSON.parse(localStorage.getItem(scriptConfig.dataKey));
let filteredList = list.filter(
(item) => item.session_hash !== targetSessionHash
);
localStorage.setItem(scriptConfig.dataKey, JSON.stringify(filteredList));
}
function clickSendBtn() {
$x(scriptConfig.position.sendBtn)[2].click();
}
function saveCurrentSession() {
const value = localStorage.getItem(scriptConfig.dataKey);
let list = [];
if (value) {
list = JSON.parse(value);
}
list.push({
time: getCurrentFormattedTime(),
session_hash: scriptConfig.currentSessionHash,
});
localStorage.setItem(scriptConfig.dataKey, JSON.stringify(list));
loadSessionHashHistory();
}
function initialize() {
window.alert = null;
WebSocket.prototype.send = hackWsSend;
document.querySelector(scriptConfig.position.directChat).click();
removeUselessElements();
setMaxOutputToken();
changeModel(scriptConfig.model);
}
(function main() {
// Add a style to highlight the current session
const style = document.createElement("style");
style.type = "text/css";
style.innerHTML = `
.highlighted-session {
background-color: #e0e0e0;
color: #333;
border-left: 3px solid #ffeb3b;
}
.disabled-button {
pointer-events: none;
opacity: 0.6;
}
`;
document.head.appendChild(style);
createHistorySessionElement();
// Create a MutationObserver instance and pass the callback function
const observer = new MutationObserver((mutations, observer) => {
// Find the target element using its ID (you may adjust the selector according to your needs)
const targetElement = document.querySelector(scriptConfig.position.main);
if (targetElement) {
// If the target element exists, execute the optimize function and stop observing
initialize();
observer.disconnect(); // Stop observing
}
});
// Configuration for the observer:
const observerConfig = { childList: true, subtree: true };
// Select the node that will be observed for mutations
const targetNode = document.body; // You may specify a more specific parent node to reduce the scope of observation
// Call the observer's observe method to start observing the target node
observer.observe(targetNode, observerConfig);
})();