-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
415 lines (361 loc) Β· 15 KB
/
index.html
File metadata and controls
415 lines (361 loc) Β· 15 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenWebUI Chat Cleaner & Repair</title>
<link rel="manifest" href="./manifest.json">
<meta name="theme-color" content="#3b82f6">
<link rel="icon" type="image/png" href="./assets/icon-192.png">
<style>
:root {
--bg-color: #f4f4f9;
--card-bg: #ffffff;
--primary: #3b82f6;
--primary-hover: #2563eb;
--text-main: #1f2937;
--text-sub: #6b7280;
--border: #e5e7eb;
--success: #10b981;
--error: #ef4444;
--warning: #f59e0b;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: var(--bg-color);
color: var(--text-main);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
padding: 20px;
}
.container {
background: var(--card-bg);
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
width: 100%;
max-width: 600px;
text-align: center;
}
h1 { font-size: 1.5rem; margin-bottom: 0.5rem; color: var(--text-main); }
p { color: var(--text-sub); margin-bottom: 2rem; font-size: 0.95rem; }
.drop-zone {
border: 2px dashed var(--border);
border-radius: 8px;
padding: 2rem;
transition: all 0.2s ease;
cursor: pointer;
margin-bottom: 1.5rem;
}
.drop-zone:hover, .drop-zone.dragover {
border-color: var(--primary);
background-color: rgba(59, 130, 246, 0.05);
}
.drop-zone p { margin: 0; pointer-events: none; }
input[type="file"] { display: none; }
.options {
margin-bottom: 1.5rem;
text-align: left;
background: #f8fafc;
padding: 1rem;
border-radius: 8px;
border: 1px solid var(--border);
}
.checkbox-wrapper {
display: flex;
align-items: center;
gap: 10px;
cursor: pointer;
user-select: none;
}
.checkbox-wrapper input { width: 18px; height: 18px; cursor: pointer; }
.checkbox-wrapper span { font-size: 0.95rem; color: var(--text-main); }
button {
background-color: var(--primary);
color: white;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 6px;
font-weight: 500;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.2s;
width: 100%;
}
button:hover { background-color: var(--primary-hover); }
button:disabled { background-color: var(--text-sub); cursor: not-allowed; opacity: 0.7; }
#status { margin-top: 1rem; font-size: 0.95rem; font-weight: 500; min-height: 1.2em; }
.status-success { color: var(--success); }
.status-error { color: var(--error); }
.stats {
margin-top: 1rem;
font-size: 0.85rem;
color: var(--text-main);
background: #f1f5f9;
padding: 1rem;
border-radius: 6px;
text-align: left;
display: none;
max-height: 300px;
overflow-y: auto;
border: 1px solid var(--border);
}
.log-entry { margin-bottom: 8px; padding-bottom: 8px; border-bottom: 1px solid #e2e8f0; }
.log-entry:last-child { border-bottom: none; }
.log-title { font-weight: 600; color: var(--primary); }
.log-detail { margin-left: 10px; color: var(--text-sub); }
.badge {
display: inline-block;
padding: 2px 6px;
border-radius: 4px;
font-size: 0.75rem;
font-weight: 600;
margin-left: 5px;
}
.badge-fix { background: #dbeafe; color: #1e40af; }
.badge-clean { background: #dcfce7; color: #166534; }
.badge-warn { background: #fef3c7; color: #92400e; }
.footer {
margin-top: 2rem;
padding-top: 1.5rem;
border-top: 1px solid var(--border);
font-size: 0.85rem;
color: var(--text-sub);
display: flex;
justify-content: center;
align-items: center;
gap: 15px;
}
.footer a { color: var(--text-sub); text-decoration: none; }
.footer a:hover { color: var(--primary); text-decoration: underline; }
</style>
</head>
<body>
<div class="container">
<h1>OpenWebUI Chat Cleaner & Repair</h1>
<p>Fix "Loading..." errors, detached nodes, and sync issues.</p>
<div class="drop-zone" id="dropZone">
<p>Click or Drag JSON file here</p>
<input type="file" id="fileInput" accept=".json">
</div>
<div class="options">
<label class="checkbox-wrapper">
<input type="checkbox" id="pruneMode">
<span><strong>Prune Unused Branches</strong> (Cleaner Mode)</span>
</label>
<div style="font-size: 0.8rem; color: #6b7280; margin-top: 5px; margin-left: 28px;">
Unchecked: Repairs broken pointers and links without deleting history.<br>
Checked: Repairs AND removes all unused conversation branches.
</div>
</div>
<button id="actionBtn" disabled>Upload JSON to Begin</button>
<div id="status"></div>
<div id="stats" class="stats"></div>
<div class="footer">
<span> Copyright (C) 2025 @fractuscontext </span>
<span>β’</span>
<span>GPL-3.0-or-later</span>
<span>β’</span>
<a href="https://github.com/fractuscontext/openwebui-chat-repair" target="_blank">View on GitHub</a>
</div>
</div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then(() => console.log('PWA: Ready for offline use.'))
.catch(err => console.error('PWA: Service Worker failed', err));
});
}
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const actionBtn = document.getElementById('actionBtn');
const statusDiv = document.getElementById('status');
const statsDiv = document.getElementById('stats');
const pruneModeCheckbox = document.getElementById('pruneMode');
let parsedInputData = null;
let originalFileName = 'fixed_chat.json';
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
if (e.dataTransfer.files.length) handleFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener('change', (e) => {
if (e.target.files.length) handleFile(e.target.files[0]);
});
function handleFile(file) {
if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
showStatus('Please upload a valid JSON file.', 'status-error');
return;
}
originalFileName = file.name;
showStatus('Reading file...', '');
actionBtn.disabled = true;
statsDiv.style.display = 'none';
const reader = new FileReader();
reader.onload = (event) => {
try {
parsedInputData = JSON.parse(event.target.result);
showStatus(`Loaded "${file.name}". Ready to repair.`, 'status-success');
actionBtn.textContent = "Repair & Download JSON";
actionBtn.disabled = false;
} catch (error) {
showStatus('Error parsing JSON. Is the file valid?', 'status-error');
parsedInputData = null;
}
};
reader.readAsText(file);
}
actionBtn.addEventListener('click', () => {
if (!parsedInputData) return;
showStatus('Processing...', '');
actionBtn.disabled = true;
try {
const isPruneMode = pruneModeCheckbox.checked;
const { cleanedData, logs } = processAllChats(parsedInputData, isPruneMode);
statsDiv.innerHTML = logs.join('');
statsDiv.style.display = 'block';
showStatus('Processing Complete! Downloading...', 'status-success');
const suffix = isPruneMode ? '_clean.json' : '_repaired.json';
downloadFile(cleanedData, originalFileName.replace('.json', suffix));
} catch (err) {
console.error(err);
showStatus('An error occurred during processing.', 'status-error');
} finally {
actionBtn.disabled = false;
}
});
function processAllChats(data, pruneMode) {
const logs = [];
const inputData = Array.isArray(data) ? data : [data];
const cleanedData = inputData.map((item, index) => processSingleChat(item, pruneMode, index, logs));
return { cleanedData, logs };
}
function processSingleChat(item, pruneMode, index, globalLogs) {
if (!item?.chat?.history?.messages) {
globalLogs.push(`<div class="log-entry"><span class="log-title">Item ${index + 1}</span>: Invalid structure</div>`);
return item;
}
const chatTitle = item.chat.title || `Untitled Chat ${index + 1}`;
const history = item.chat.history;
let workingMessages = JSON.parse(JSON.stringify(history.messages));
const logDetails = [];
const sanitizeResult = sanitizeGraph(workingMessages);
workingMessages = sanitizeResult.messages;
if (sanitizeResult.brokenLinks > 0) logDetails.push(`Fixed ${sanitizeResult.brokenLinks} links`);
const bestId = findBestCurrentId(history.currentId, workingMessages);
let pointerFixed = (bestId !== history.currentId || !workingMessages[history.currentId]);
if (pointerFixed) logDetails.push(`Restored pointer`);
if (pruneMode) {
const pruneResult = pruneUnusedBranches(workingMessages, bestId);
workingMessages = pruneResult.messages;
if (pruneResult.removedCount > 0) logDetails.push(`Pruned ${pruneResult.removedCount} nodes`);
}
const linearHistory = buildLinearHistory(workingMessages, bestId);
let badges = "";
if (pointerFixed) badges += `<span class="badge badge-fix">Repaired</span>`;
if (pruneMode) badges += `<span class="badge badge-clean">Pruned</span>`;
if (sanitizeResult.brokenLinks > 0) badges += `<span class="badge badge-warn">Sanitized</span>`;
globalLogs.push(`
<div class="log-entry">
<span class="log-title">${escapeHtml(chatTitle)}</span> ${badges || '<span class="badge">Healthy</span>'}
<div class="log-detail">${logDetails.join(', ') || 'No issues found'}</div>
</div>
`);
return {
...item,
chat: {
...item.chat,
messages: linearHistory,
history: { ...history, currentId: bestId, messages: workingMessages }
}
};
}
function sanitizeGraph(messages) {
let brokenLinks = 0;
Object.keys(messages).forEach(key => {
const msg = messages[key];
if (msg.childrenIds) {
const len = msg.childrenIds.length;
msg.childrenIds = msg.childrenIds.filter(cid => messages[cid]);
if (msg.childrenIds.length !== len) brokenLinks++;
}
if (msg.parentId && !messages[msg.parentId]) {
msg.parentId = null;
brokenLinks++;
}
});
return { messages, brokenLinks };
}
function findBestCurrentId(currentId, messages) {
const roots = Object.keys(messages).filter(id => !messages[id].parentId);
if (roots.length === 0) return currentId;
let bestRoot = roots[0];
let maxBranchSize = -1;
roots.forEach(rootId => {
const visited = new Set();
const queue = [rootId];
visited.add(rootId);
let head = 0;
while(head < queue.length && head < 50000){
const current = queue[head++];
const children = messages[current]?.childrenIds || [];
for(const cid of children) {
if(!visited.has(cid) && messages[cid]) { visited.add(cid); queue.push(cid); }
}
}
if (visited.size > maxBranchSize) { maxBranchSize = visited.size; bestRoot = rootId; }
});
let bestLeaf = bestRoot;
let latestTimestamp = -1;
const q = [bestRoot];
const seen = new Set([bestRoot]);
let h = 0;
while(h < q.length && h < 50000){
const cid = q[h++];
const node = messages[cid];
if(node.timestamp > latestTimestamp) { latestTimestamp = node.timestamp; bestLeaf = cid; }
for(const child of (node.childrenIds || [])) {
if(!seen.has(child) && messages[child]) { seen.add(child); q.push(child); }
}
}
return bestLeaf;
}
function pruneUnusedBranches(messages, leafId) {
const kept = new Set();
let p = leafId;
while(p && messages[p]) { kept.add(p); p = messages[p].parentId; }
const clean = {};
kept.forEach(id => {
const m = { ...messages[id] };
if (m.childrenIds) m.childrenIds = m.childrenIds.filter(cid => kept.has(cid));
clean[id] = m;
});
return { messages: clean, removedCount: Object.keys(messages).length - kept.size };
}
function buildLinearHistory(messages, leafId) {
const history = [];
let p = leafId;
while(p && messages[p]) { history.unshift(messages[p]); p = messages[p].parentId; }
return history;
}
function downloadFile(data, filename) {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = filename;
document.body.appendChild(a); a.click();
document.body.removeChild(a); URL.revokeObjectURL(url);
}
function showStatus(msg, type) { statusDiv.textContent = msg; statusDiv.className = type; }
function escapeHtml(text) { return text ? text.replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":"'"}[m])) : text; }
</script>
</body>
</html>