chatshelf 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +152 -2
- package/bin/chatshelf.mjs +45 -0
- package/package.json +44 -4
- package/public/app.js +1536 -0
- package/public/index.html +371 -0
- package/public/style.css +610 -0
- package/server.mjs +732 -0
- package/sources.mjs +674 -0
package/public/app.js
ADDED
|
@@ -0,0 +1,1536 @@
|
|
|
1
|
+
const $ = (id) => document.getElementById(id);
|
|
2
|
+
const PAGE = 150;
|
|
3
|
+
const DAY = 864e5;
|
|
4
|
+
const root = document.documentElement;
|
|
5
|
+
const openToolsOnLoad = location.hash === '#tools';
|
|
6
|
+
let deepLink = location.hash.startsWith('#s=') ? decodeURIComponent(location.hash.slice(3)) : '';
|
|
7
|
+
|
|
8
|
+
const state = {
|
|
9
|
+
projects: [], sessions: [], byUid: new Map(), home: '', root: '', view: 'overview', shown: PAGE,
|
|
10
|
+
sort: 'new', sessTab: 'all', projTab: 'all', selected: new Set(), detail: null, mover: null,
|
|
11
|
+
msgs: [], hits: [], hitIdx: 0, loaded: false, src: '', sources: [], bookmarks: [], bmIndex: new Map(), external: [], extIndex: new Map(), focusMsg: '',
|
|
12
|
+
pins: new Set(), chatMarks: new Map(), bmTab: 'all',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// ---------- helpers ----------
|
|
16
|
+
async function api(path, body) {
|
|
17
|
+
const res = await fetch(path, {
|
|
18
|
+
method: body ? 'POST' : 'GET',
|
|
19
|
+
headers: { 'X-Token': window.CSM_TOKEN, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
20
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
21
|
+
});
|
|
22
|
+
const data = await res.json().catch(() => ({}));
|
|
23
|
+
if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);
|
|
24
|
+
return data;
|
|
25
|
+
}
|
|
26
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
27
|
+
const short = (p) => (p && state.home && p.startsWith(state.home) ? '~' + p.slice(state.home.length) : p || '');
|
|
28
|
+
const base = (p) => (p ? p.split('/').filter(Boolean).pop() || '/' : '');
|
|
29
|
+
const encode = (p) => p.replace(/\/+$/, '').replace(/[^a-zA-Z0-9]/g, '-');
|
|
30
|
+
const expand = (p) => (p === '~' ? state.home : p.startsWith('~/') ? state.home + p.slice(1) : p);
|
|
31
|
+
const shq = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
32
|
+
const plural = (n, w) => `${n.toLocaleString()} ${w}${n === 1 ? '' : 's'}`;
|
|
33
|
+
const date = (ms) => new Date(ms).toLocaleString(undefined, { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' });
|
|
34
|
+
const size = (b) => (b > 1e9 ? (b / 1e9).toFixed(1) + ' GB' : b > 1e6 ? (b / 1e6).toFixed(1) + ' MB' : Math.max(1, Math.round(b / 1e3)) + ' KB');
|
|
35
|
+
const motionOn = () => root.classList.contains('motion');
|
|
36
|
+
function ago(ms) {
|
|
37
|
+
const m = Math.round((Date.now() - ms) / 6e4);
|
|
38
|
+
if (m < 10) return 'Now';
|
|
39
|
+
if (m < 60) return `${m}m ago`;
|
|
40
|
+
if (m < 1440) return `${Math.round(m / 60)}h ago`;
|
|
41
|
+
if (m < 43200) return `${Math.round(m / 1440)}d ago`;
|
|
42
|
+
return new Date(ms).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
|
43
|
+
}
|
|
44
|
+
function hl(text, q) {
|
|
45
|
+
const s = String(text ?? '');
|
|
46
|
+
if (!q) return esc(s);
|
|
47
|
+
const i = s.toLowerCase().indexOf(q);
|
|
48
|
+
if (i < 0) return esc(s);
|
|
49
|
+
return esc(s.slice(0, i)) + '<mark>' + esc(s.slice(i, i + q.length)) + '</mark>' + esc(s.slice(i + q.length));
|
|
50
|
+
}
|
|
51
|
+
const use = (n, cls = '') => `<svg class="ic ${cls}" aria-hidden="true"><use href="#i-${n}"/></svg>`;
|
|
52
|
+
const ICON = {
|
|
53
|
+
folder: use('folder'),
|
|
54
|
+
pin: use('pin'),
|
|
55
|
+
bookmark: use('bookmark'),
|
|
56
|
+
clock: '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="8"/><path d="M12 8v4l2.5 2"/></svg>',
|
|
57
|
+
branch: '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="6" cy="5" r="2"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="8" r="2"/><path d="M6 7v10M18 10c0 4-6 3-12 7"/></svg>',
|
|
58
|
+
warn: '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4 2.5 20h19Z"/><path d="M12 10v4M12 17h.01"/></svg>',
|
|
59
|
+
check: '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/></svg>',
|
|
60
|
+
reply: '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 14 4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 6 6v5"/></svg>',
|
|
61
|
+
};
|
|
62
|
+
let toastTimer;
|
|
63
|
+
function toast(msg) {
|
|
64
|
+
const t = $('toast');
|
|
65
|
+
t.textContent = msg;
|
|
66
|
+
t.classList.remove('show');
|
|
67
|
+
void t.offsetWidth;
|
|
68
|
+
t.classList.add('show');
|
|
69
|
+
clearTimeout(toastTimer);
|
|
70
|
+
toastTimer = setTimeout(() => t.classList.remove('show'), 4500);
|
|
71
|
+
}
|
|
72
|
+
async function copy(text, btn) {
|
|
73
|
+
await navigator.clipboard.writeText(text);
|
|
74
|
+
const label = btn.querySelector('span') || btn;
|
|
75
|
+
const old = label.textContent;
|
|
76
|
+
label.textContent = 'Copied';
|
|
77
|
+
btn.classList.add('done');
|
|
78
|
+
setTimeout(() => { label.textContent = old; btn.classList.remove('done'); }, 1500);
|
|
79
|
+
}
|
|
80
|
+
const resumeCmd = (cwd, id) => `cd ${shq(cwd)} && claude --resume ${id}`;
|
|
81
|
+
const timeChip = (ms) => {
|
|
82
|
+
const a = ago(ms);
|
|
83
|
+
return `<span class="chip${a === 'Now' ? ' now' : ''}">${ICON.clock}${a}</span>`;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
// ---------- GitHub (public project) ----------
|
|
87
|
+
const REPO = 'heyKhoaiz/chatshelf';
|
|
88
|
+
const REPO_URL = `https://github.com/${REPO}`;
|
|
89
|
+
// Shows the star count next to "Star on GitHub". Uses GitHub's public API (no account, nothing about you is sent),
|
|
90
|
+
// cached for 6 hours, and stays hidden when offline.
|
|
91
|
+
async function loadStars() {
|
|
92
|
+
const show = (n) => { if (typeof n === 'number') { $('ghCount').textContent = n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n); $('ghCount').hidden = false; } };
|
|
93
|
+
try {
|
|
94
|
+
const c = JSON.parse(localStorage.getItem('chatshelf-stars') || 'null');
|
|
95
|
+
if (c && Date.now() - c.at < 6 * 36e5) { show(c.n); return; }
|
|
96
|
+
const res = await fetch(`https://api.github.com/repos/${REPO}`, { headers: { Accept: 'application/vnd.github+json' }, referrerPolicy: 'no-referrer' });
|
|
97
|
+
if (!res.ok) return;
|
|
98
|
+
const n = (await res.json()).stargazers_count;
|
|
99
|
+
localStorage.setItem('chatshelf-stars', JSON.stringify({ n, at: Date.now() }));
|
|
100
|
+
show(n);
|
|
101
|
+
} catch { /* offline: leave the plain button */ }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---------- tools ----------
|
|
105
|
+
const TOOLS = {
|
|
106
|
+
claude: { label: 'Claude Code', short: 'Claude' },
|
|
107
|
+
codex: { label: 'Codex', short: 'Codex' },
|
|
108
|
+
cursor: { label: 'Cursor', short: 'Cursor' },
|
|
109
|
+
copilot: { label: 'Copilot Chat', short: 'Copilot' },
|
|
110
|
+
opencode: { label: 'OpenCode', short: 'OpenCode' },
|
|
111
|
+
gemini: { label: 'Gemini CLI', short: 'Gemini' },
|
|
112
|
+
chatgpt: { label: 'ChatGPT', short: 'ChatGPT' },
|
|
113
|
+
claudeai: { label: 'claude.ai', short: 'claude.ai' },
|
|
114
|
+
};
|
|
115
|
+
// Who answered in a chat from each tool, and the avatar mark to show.
|
|
116
|
+
const ASSISTANT = { claude: ['Claude', '✳'], claudeai: ['Claude', '✳'], codex: ['Codex', 'C'], cursor: ['Cursor', 'Cu'], copilot: ['Copilot', 'Co'], opencode: ['OpenCode', 'O'], gemini: ['Gemini', 'G'], chatgpt: ['ChatGPT', 'G'] };
|
|
117
|
+
const assistantOf = (src) => ASSISTANT[src] || ['Assistant', 'A'];
|
|
118
|
+
const toolLabel = (id) => (TOOLS[id] || { label: id }).label;
|
|
119
|
+
const toolBadge = (id) => `<span class="src s-${esc(id)}">${esc((TOOLS[id] || { short: id }).short)}</span>`;
|
|
120
|
+
const projName = (p) => base(p.cwd) || (p.source === 'claude' ? p.key : 'No folder');
|
|
121
|
+
const claudeProjects = () => state.projects.filter((p) => p.source === 'claude');
|
|
122
|
+
|
|
123
|
+
// How to pick a chat back up, per tool.
|
|
124
|
+
function resumeInfo(s) {
|
|
125
|
+
const p = s.project;
|
|
126
|
+
const q = p.cwd ? shq(p.cwd) : '';
|
|
127
|
+
const inDir = (c) => (q ? `cd ${q} && ${c}` : c);
|
|
128
|
+
switch (s.source) {
|
|
129
|
+
case 'claude': return { kind: 'terminal', label: 'Resume in terminal', cmd: inDir(`claude --resume ${s.id}`), open: 'Open in terminal' };
|
|
130
|
+
case 'codex': return { kind: 'terminal', label: 'Resume with Codex', cmd: inDir(`codex resume ${s.id}`), open: 'Open in terminal', note: 'Needs the Codex CLI. Chats started in the Codex VS Code extension also show up in its history panel.' };
|
|
131
|
+
case 'cursor': return { kind: 'app', label: 'Continue in Cursor', cmd: q ? `cursor ${q}` : 'cursor', open: 'Open in Cursor', note: 'Opens the project. The chat is in Cursor’s chat history.' };
|
|
132
|
+
case 'copilot': return { kind: 'app', label: 'Continue in VS Code', cmd: q ? `code ${q}` : 'code', open: 'Open in VS Code', note: 'Opens the project. The chat is in the Copilot Chat history of that workspace.' };
|
|
133
|
+
case 'opencode': return { kind: 'terminal', label: 'Continue in OpenCode', cmd: inDir('opencode'), open: 'Open in terminal', note: 'Opens OpenCode in the project; pick this chat from its session list.' };
|
|
134
|
+
case 'gemini': return { kind: 'terminal', label: 'Continue in Gemini CLI', cmd: inDir('gemini'), open: 'Open in terminal', note: 'Opens Gemini CLI in the project folder.' };
|
|
135
|
+
case 'chatgpt': return { kind: 'url', label: 'Continue on the web', cmd: s.url || '', open: 'Open on chatgpt.com', url: s.url };
|
|
136
|
+
case 'claudeai': return { kind: 'url', label: 'Continue on the web', cmd: s.url || '', open: 'Open on claude.ai', url: s.url };
|
|
137
|
+
default: return { kind: 'none', label: 'Resume', cmd: '', open: 'Open' };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---------- motion (power3-out easing, blur-to-sharp rise, word-by-word headings) ----------
|
|
142
|
+
function splitWords(el) {
|
|
143
|
+
if (!el || el.dataset.split === el.textContent) return;
|
|
144
|
+
const text = el.textContent;
|
|
145
|
+
el.setAttribute('aria-label', text);
|
|
146
|
+
let n = 0;
|
|
147
|
+
el.innerHTML = text.split(/(\s+)/).map((w) => (/^\s+$/.test(w) || !w ? w : `<span class="w" aria-hidden="true" style="--i:${n++}">${esc(w)}</span>`)).join('');
|
|
148
|
+
el.dataset.split = el.textContent;
|
|
149
|
+
}
|
|
150
|
+
function replay(el, cls = 'in') {
|
|
151
|
+
if (!el || !motionOn()) return;
|
|
152
|
+
el.classList.remove(cls);
|
|
153
|
+
void el.offsetWidth;
|
|
154
|
+
el.classList.add(cls);
|
|
155
|
+
}
|
|
156
|
+
function stagger(container, selector = ':scope > *', max = 14) {
|
|
157
|
+
if (!container || !motionOn()) return;
|
|
158
|
+
[...container.querySelectorAll(selector)].slice(0, max).forEach((el, i) => {
|
|
159
|
+
el.style.setProperty('--i', i);
|
|
160
|
+
replay(el, 'rv');
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
function countUp(el) {
|
|
164
|
+
const target = Number(el.dataset.n);
|
|
165
|
+
if (!motionOn() || !Number.isFinite(target) || target === 0) return;
|
|
166
|
+
const t0 = performance.now();
|
|
167
|
+
const dur = 900;
|
|
168
|
+
const step = (t) => {
|
|
169
|
+
const p = Math.min(1, (t - t0) / dur);
|
|
170
|
+
el.textContent = Math.round(target * (1 - Math.pow(1 - p, 3))).toLocaleString();
|
|
171
|
+
if (p < 1) requestAnimationFrame(step);
|
|
172
|
+
};
|
|
173
|
+
requestAnimationFrame(step);
|
|
174
|
+
}
|
|
175
|
+
function animateView(view) {
|
|
176
|
+
if (!motionOn()) return;
|
|
177
|
+
const sec = $(`view-${view}`);
|
|
178
|
+
sec.querySelectorAll('.split').forEach((h) => { splitWords(h); replay(h); });
|
|
179
|
+
sec.querySelectorAll('.rv-text').forEach((el) => replay(el));
|
|
180
|
+
if (!state.loaded) return;
|
|
181
|
+
if (view === 'overview') {
|
|
182
|
+
stagger($('stats'));
|
|
183
|
+
$('stats').querySelectorAll('.stat-num').forEach(countUp);
|
|
184
|
+
stagger($('pinned'));
|
|
185
|
+
stagger($('recent'), ':scope > *', 8);
|
|
186
|
+
stagger(document.querySelector('.right'), ':scope > .panel');
|
|
187
|
+
replay($('heat'));
|
|
188
|
+
replay($('topProjects'));
|
|
189
|
+
} else if (view === 'sessions') {
|
|
190
|
+
stagger($('list'), ':scope > .row, :scope > .date-head', 16);
|
|
191
|
+
} else if (view === 'projects') {
|
|
192
|
+
replay($('projSummary'), 'rv');
|
|
193
|
+
replay($('projSummary').querySelector('.segbar'));
|
|
194
|
+
stagger($('projects'), ':scope > .tr, :scope > .group-head', 16);
|
|
195
|
+
} else if (view === 'backups') {
|
|
196
|
+
stagger($('backups'));
|
|
197
|
+
} else if (view === 'bookmarks') {
|
|
198
|
+
stagger($('bmList'), ':scope > .bm-group', 10);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ---------- skeletons ----------
|
|
203
|
+
function skeletons() {
|
|
204
|
+
const line = (w) => `<span class="sk" style="width:${w}"></span>`;
|
|
205
|
+
const row = () => `<div class="row skel">${line('46%')}<span class="sk chip-sk"></span>${line('30%')}</div>`;
|
|
206
|
+
$('stats').innerHTML = Array.from({ length: 4 }, () => `<div class="stat skel"><div class="stat-top">${line('40%')}${line('70%')}</div><div class="stat-foot">${line('60%')}</div></div>`).join('');
|
|
207
|
+
$('recent').innerHTML = Array.from({ length: 6 }, row).join('');
|
|
208
|
+
$('list').innerHTML = Array.from({ length: 8 }, row).join('');
|
|
209
|
+
$('today').textContent = 'Reading your sessions…';
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ---------- pins ----------
|
|
213
|
+
// Chat bookmarks (whole sessions). `state.pins` holds the uids of bookmarked chats for quick lookups.
|
|
214
|
+
function computePins() {
|
|
215
|
+
state.pins = new Set(state.sessions.filter((s) => state.chatMarks.has(s.id)).map((s) => s.uid));
|
|
216
|
+
}
|
|
217
|
+
async function togglePin(uid) {
|
|
218
|
+
const s = state.byUid.get(uid);
|
|
219
|
+
if (!s) return;
|
|
220
|
+
const existing = state.chatMarks.get(s.id);
|
|
221
|
+
try {
|
|
222
|
+
if (existing) {
|
|
223
|
+
await api('/api/bookmarks/delete', { id: existing.id });
|
|
224
|
+
state.chatMarks.delete(s.id);
|
|
225
|
+
toast('Chat bookmark removed');
|
|
226
|
+
} else {
|
|
227
|
+
const { bookmark } = await api('/api/bookmarks', { kind: 'chat', sessionId: s.id, title: s.title, cwd: s.project.cwd, note: '' });
|
|
228
|
+
state.chatMarks.set(s.id, bookmark);
|
|
229
|
+
toast(`Bookmarked chat "${s.title.slice(0, 50)}"`);
|
|
230
|
+
}
|
|
231
|
+
} catch (e) { toast(e.message); return; }
|
|
232
|
+
computePins();
|
|
233
|
+
renderAll();
|
|
234
|
+
if (state.detail && state.detail.uid === uid) syncPinButton();
|
|
235
|
+
}
|
|
236
|
+
// One-time move of old browser-only pins into chat bookmarks on disk.
|
|
237
|
+
async function migratePins() {
|
|
238
|
+
const old = JSON.parse(localStorage.getItem('csm-pins') || '[]');
|
|
239
|
+
if (!old.length) return;
|
|
240
|
+
for (const uid of old) {
|
|
241
|
+
const s = state.byUid.get(uid);
|
|
242
|
+
if (!s || state.chatMarks.has(s.id)) continue;
|
|
243
|
+
try {
|
|
244
|
+
const { bookmark } = await api('/api/bookmarks', { kind: 'chat', sessionId: s.id, title: s.title, cwd: s.project.cwd, note: '' });
|
|
245
|
+
state.chatMarks.set(s.id, bookmark);
|
|
246
|
+
} catch { return; }
|
|
247
|
+
}
|
|
248
|
+
localStorage.removeItem('csm-pins');
|
|
249
|
+
computePins();
|
|
250
|
+
renderAll();
|
|
251
|
+
}
|
|
252
|
+
const pinnedSessions = () => state.sessions.filter((s) => state.pins.has(s.uid));
|
|
253
|
+
|
|
254
|
+
// ---------- data ----------
|
|
255
|
+
async function load() {
|
|
256
|
+
try {
|
|
257
|
+
const [data, bm] = await Promise.all([api('/api/projects'), api('/api/bookmarks').catch(() => ({ bookmarks: [] }))]);
|
|
258
|
+
setBookmarks(bm.bookmarks);
|
|
259
|
+
setExternal(bm.external);
|
|
260
|
+
state.home = data.home;
|
|
261
|
+
state.root = data.root;
|
|
262
|
+
$('backupRoot').textContent = short(data.backupRoot);
|
|
263
|
+
state.projects = data.projects.map((p) => ({ ...p, bytes: p.sessions.reduce((n, s) => n + s.size, 0) }));
|
|
264
|
+
state.sessions = state.projects.flatMap((p) => p.sessions.map((s) => ({
|
|
265
|
+
...s,
|
|
266
|
+
project: p,
|
|
267
|
+
uid: `${p.key}|${s.id}`,
|
|
268
|
+
hay: [s.title, p.cwd, p.key, s.id, s.branch, toolLabel(s.source), ...s.prompts].join('\n').toLowerCase(),
|
|
269
|
+
})));
|
|
270
|
+
state.sessions.sort((a, b) => b.mtime - a.mtime);
|
|
271
|
+
state.byUid = new Map(state.sessions.map((s) => [s.uid, s]));
|
|
272
|
+
computePins();
|
|
273
|
+
for (const u of [...state.selected]) if (!state.byUid.has(u)) state.selected.delete(u);
|
|
274
|
+
const first = !state.loaded;
|
|
275
|
+
state.loaded = true;
|
|
276
|
+
renderAll();
|
|
277
|
+
if (first) animateView(state.view);
|
|
278
|
+
if (deepLink) { openDetail(deepLink); deepLink = ''; }
|
|
279
|
+
if (first && openToolsOnLoad) openSources();
|
|
280
|
+
migratePins();
|
|
281
|
+
} catch (e) {
|
|
282
|
+
$('today').textContent = '';
|
|
283
|
+
$('recent').innerHTML = emptyState('Could not read sessions', esc(e.message), '<button type="button" class="btn" data-reload>Try again</button>');
|
|
284
|
+
$('list').innerHTML = $('recent').innerHTML;
|
|
285
|
+
} finally {
|
|
286
|
+
['stats', 'recent', 'list'].forEach((id) => $(id).removeAttribute('aria-busy'));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function emptyState(title, text, action = '') {
|
|
291
|
+
return `<div class="empty"><div class="empty-ic">${use('search')}</div><p class="empty-title">${esc(title)}</p><p class="small muted">${text}</p>${action}</div>`;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function renderAll() {
|
|
295
|
+
const missing = state.projects.filter((p) => p.missing);
|
|
296
|
+
$('navSessions').textContent = state.sessions.length.toLocaleString();
|
|
297
|
+
$('navMissing').hidden = !missing.length;
|
|
298
|
+
$('navMissing').textContent = missing.length;
|
|
299
|
+
const sel = $('proj');
|
|
300
|
+
const current = sel.value;
|
|
301
|
+
sel.innerHTML = '<option value="">All projects</option>' + state.projects
|
|
302
|
+
.filter((p) => p.sessions.length)
|
|
303
|
+
.map((p) => `<option value="${esc(p.key)}">${esc(projName(p))} · ${esc(toolLabel(p.source))} (${p.sessions.length})</option>`)
|
|
304
|
+
.join('');
|
|
305
|
+
sel.value = state.projects.some((p) => p.key === current) ? current : '';
|
|
306
|
+
renderSidePins();
|
|
307
|
+
renderTools();
|
|
308
|
+
renderOverview();
|
|
309
|
+
renderBookmarks();
|
|
310
|
+
renderSessions();
|
|
311
|
+
renderProjects();
|
|
312
|
+
renderBulk();
|
|
313
|
+
if (state.view === 'backups') renderBackups();
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function renderSidePins() {
|
|
317
|
+
const pins = pinnedSessions().slice(0, 6);
|
|
318
|
+
$('sidePinned').hidden = !pins.length;
|
|
319
|
+
$('sidePinnedList').innerHTML = pins.map((s) => `<button type="button" class="side-pin" data-session="${esc(s.uid)}">${ICON.bookmark}<span>${esc(s.title)}</span></button>`).join('');
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ---------- overview ----------
|
|
323
|
+
function weekStats(fromMs, toMs) {
|
|
324
|
+
const s = state.sessions.filter((x) => x.mtime >= fromMs && x.mtime < toMs);
|
|
325
|
+
return { sessions: s.length, prompts: s.reduce((n, x) => n + x.promptCount, 0), projects: new Set(s.map((x) => x.project.key)).size };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function renderOverview() {
|
|
329
|
+
const now = Date.now();
|
|
330
|
+
const h = new Date().getHours();
|
|
331
|
+
const hello = h < 12 ? 'Good morning' : h < 18 ? 'Good afternoon' : 'Good evening';
|
|
332
|
+
if ($('hello').getAttribute('aria-label') !== hello) { $('hello').textContent = hello; delete $('hello').dataset.split; if (motionOn()) splitWords($('hello')); }
|
|
333
|
+
$('today').textContent = new Date().toLocaleString(undefined, { weekday: 'long', month: 'long', day: 'numeric' });
|
|
334
|
+
|
|
335
|
+
const thisW = weekStats(now - 7 * DAY, now + DAY);
|
|
336
|
+
const lastW = weekStats(now - 14 * DAY, now - 7 * DAY);
|
|
337
|
+
const pct = lastW.prompts ? Math.round(((thisW.prompts - lastW.prompts) / lastW.prompts) * 100) : null;
|
|
338
|
+
const missing = state.projects.filter((p) => p.missing);
|
|
339
|
+
const hidden = missing.reduce((n, p) => n + p.sessions.length, 0);
|
|
340
|
+
const withSessions = new Set(state.projects.filter((p) => p.sessions.length && p.cwd).map((p) => p.cwd)).size;
|
|
341
|
+
|
|
342
|
+
const stat = (num, label, delta, foot, view) => `
|
|
343
|
+
<${view ? `button type="button" data-view="${view}"` : 'div'} class="stat">
|
|
344
|
+
<div class="stat-top"><div class="stat-num" data-n="${num}">${num.toLocaleString()}</div><div class="stat-label">${label}</div></div>
|
|
345
|
+
<div class="stat-foot">${delta}<span>${foot}</span></div>
|
|
346
|
+
</${view ? 'button' : 'div'}>`;
|
|
347
|
+
const chip = (txt, cls = '') => `<span class="delta ${cls}">${txt}</span>`;
|
|
348
|
+
$('stats').innerHTML =
|
|
349
|
+
stat(state.sessions.length, 'Chats saved', chip(`+${thisW.sessions}`, thisW.sessions ? '' : 'flat'), 'this week', 'sessions') +
|
|
350
|
+
stat(thisW.prompts, 'Prompts this week',
|
|
351
|
+
pct === null ? chip('new', 'flat') : chip(`${pct >= 0 ? '+' : ''}${pct}%`, pct >= 0 ? '' : 'flat'), `vs. ${lastW.prompts.toLocaleString()} last week`) +
|
|
352
|
+
stat(withSessions, 'Projects', chip(`${thisW.projects}`, thisW.projects ? '' : 'flat'), 'active this week', 'projects') +
|
|
353
|
+
stat(missing.length, 'Missing folders', missing.length ? chip(`${hidden}`, 'warn') : chip('OK'),
|
|
354
|
+
missing.length ? 'sessions hidden' : 'all folders found', 'projects');
|
|
355
|
+
|
|
356
|
+
const pins = pinnedSessions();
|
|
357
|
+
$('pinnedBlock').hidden = !pins.length;
|
|
358
|
+
$('pinned').innerHTML = pins.slice(0, 4).map((s) => sessionRow(s, '', false)).join('');
|
|
359
|
+
|
|
360
|
+
const recent = state.sessions.filter((s) => s.promptCount > 0 && !state.pins.has(s.uid)).slice(0, 8);
|
|
361
|
+
$('recent').innerHTML = recent.map((s) => sessionRow(s, '', false)).join('') ||
|
|
362
|
+
emptyState('No sessions yet', 'Run <code>claude</code> in any folder and your chats will show up here.');
|
|
363
|
+
|
|
364
|
+
// heatmap: 16 weeks ending this week, by day last used
|
|
365
|
+
const counts = new Map();
|
|
366
|
+
for (const s of state.sessions) {
|
|
367
|
+
const d = new Date(s.mtime); d.setHours(0, 0, 0, 0);
|
|
368
|
+
counts.set(d.getTime(), (counts.get(d.getTime()) || 0) + 1);
|
|
369
|
+
}
|
|
370
|
+
const today = new Date(); today.setHours(0, 0, 0, 0);
|
|
371
|
+
const end = new Date(today); end.setDate(end.getDate() + (6 - end.getDay()));
|
|
372
|
+
const start = new Date(end); start.setDate(start.getDate() - 16 * 7 + 1);
|
|
373
|
+
const vals = [];
|
|
374
|
+
for (let d = new Date(start), i = 0; d <= end; d.setDate(d.getDate() + 1), i++) vals.push({ t: d.getTime(), n: counts.get(d.getTime()) || 0, future: d > today, c: Math.floor(i / 7) });
|
|
375
|
+
const max = Math.max(1, ...vals.map((v) => v.n));
|
|
376
|
+
const level = (n) => (n === 0 ? 0 : Math.min(4, Math.ceil((n / max) * 4)));
|
|
377
|
+
$('heat').innerHTML = vals.map((v) => `<i data-l="${level(v.n)}" ${v.n ? `data-day="${ymd(v.t)}"` : ''} class="${v.future ? 'future' : ''}" style="--c:${v.c}" title="${new Date(v.t).toDateString()}: ${plural(v.n, 'session')}"></i>`).join('');
|
|
378
|
+
const active = vals.filter((v) => v.n && !v.future).length;
|
|
379
|
+
$('heat').setAttribute('aria-label', `Sessions per day over the last 16 weeks. Active on ${active} days.`);
|
|
380
|
+
$('heatFoot').innerHTML = `${ICON.check}<b>${thisW.sessions}</b> <span class="muted">this week · active ${active} of the last 112 days</span>`;
|
|
381
|
+
|
|
382
|
+
$('attention').innerHTML = missing.length
|
|
383
|
+
? missing.map((p) => `<div class="row">
|
|
384
|
+
<div class="row-title">${esc(base(p.cwd))}</div>
|
|
385
|
+
<div class="row-meta"><span class="mono-s">${esc(short(p.cwd))}</span></div>
|
|
386
|
+
<div class="row-side"><span class="chip danger">${ICON.warn}${plural(p.sessions.length, 'session')}</span><button type="button" class="btn accent sm" data-move="${esc(p.key)}">Fix</button></div>
|
|
387
|
+
</div>`).join('')
|
|
388
|
+
: `<div class="good">${ICON.check}Every project folder still exists.</div>`;
|
|
389
|
+
|
|
390
|
+
const top = state.projects.filter((p) => p.sessions.length && p.cwd).sort((a, b) => b.sessions.length - a.sessions.length).slice(0, 5);
|
|
391
|
+
const most = top[0] ? top[0].sessions.length : 1;
|
|
392
|
+
$('topProjects').innerHTML = top.map((p, i) => `<button type="button" class="row" data-show="${esc(p.key)}">
|
|
393
|
+
<div class="row-title">${esc(projName(p))} ${toolBadge(p.source)}</div>
|
|
394
|
+
<div class="row-side"><span class="muted small">${plural(p.sessions.length, 'chat')}</span></div>
|
|
395
|
+
<div class="bar-mini"><span style="width:${Math.max(4, (p.sessions.length / most) * 100)}%; --i:${i}"></span></div>
|
|
396
|
+
</button>`).join('');
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// ---------- sessions ----------
|
|
400
|
+
function sessionRow(s, q, selectable) {
|
|
401
|
+
const p = s.project;
|
|
402
|
+
const match = q && !s.title.toLowerCase().includes(q) ? s.prompts.find((x) => x.toLowerCase().includes(q)) : '';
|
|
403
|
+
const pinned = state.pins.has(s.uid);
|
|
404
|
+
const inner = `
|
|
405
|
+
<span class="row-title">${pinned && !selectable ? `<span class="pin-dot" title="Bookmarked chat">${ICON.bookmark}</span>` : ''}${hl(s.title, q)}</span>
|
|
406
|
+
<span class="row-meta">
|
|
407
|
+
${toolBadge(s.source)}<span class="proj">${ICON.folder}${hl(projName(p), q)}</span>
|
|
408
|
+
${s.branch ? `<span class="sep">·</span><span class="proj">${ICON.branch}${esc(s.branch)}</span>` : ''}
|
|
409
|
+
<span class="sep">·</span><span>${s.promptCount ? plural(s.promptCount, 'prompt') : 'empty'}</span>
|
|
410
|
+
${p.missing ? `<span class="sep">·</span><span class="danger-t">${ICON.warn}folder missing</span>` : ''}
|
|
411
|
+
</span>
|
|
412
|
+
${match ? `<span class="row-last">${ICON.reply}<span>“${hl(match.slice(0, 140), q)}”</span></span>`
|
|
413
|
+
: s.last ? `<span class="row-last" title="Your last prompt">${ICON.reply}<span>${esc(s.last.slice(0, 140))}</span></span>` : ''}
|
|
414
|
+
<span class="row-side">${timeChip(s.mtime)}</span>`;
|
|
415
|
+
if (!selectable) return `<button type="button" class="row${p.missing ? ' missing' : ''}" data-session="${esc(s.uid)}">${inner}</button>`;
|
|
416
|
+
const checked = state.selected.has(s.uid);
|
|
417
|
+
return `<div class="row selectable${checked ? ' is-selected' : ''}${p.missing ? ' missing' : ''}${pinned ? ' is-pinned' : ''}" data-uid="${esc(s.uid)}">
|
|
418
|
+
${s.source !== 'claude' ? '<span class="check" aria-hidden="true"></span>' : `<label class="check"><input type="checkbox" data-select="${esc(s.uid)}" ${checked ? 'checked' : ''} aria-label="Select: ${esc(s.title.slice(0, 60))}"></label>`}
|
|
419
|
+
<button type="button" class="row-open" data-session="${esc(s.uid)}">${inner}</button>
|
|
420
|
+
<button type="button" class="pin-btn" data-pin="${esc(s.uid)}" aria-pressed="${pinned}" aria-label="${pinned ? 'Remove chat bookmark' : 'Bookmark chat'}: ${esc(s.title.slice(0, 60))}" title="${pinned ? 'Remove chat bookmark' : 'Bookmark chat'}">${ICON.bookmark}</button>
|
|
421
|
+
</div>`;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function filteredSessions() {
|
|
425
|
+
const q = $('q').value.trim().toLowerCase();
|
|
426
|
+
const key = $('proj').value;
|
|
427
|
+
const showEmpty = $('showEmpty').checked;
|
|
428
|
+
const weekAgo = Date.now() - 7 * DAY;
|
|
429
|
+
const range = dateBounds();
|
|
430
|
+
const pool = state.sessions.filter((s) => (!state.src || s.source === state.src) && (!key || s.project.key === key) && (!range || (s.mtime >= range[0] && s.mtime < range[1])) && (!q || s.hay.includes(q)));
|
|
431
|
+
const visible = pool.filter((s) => showEmpty || s.promptCount > 0);
|
|
432
|
+
const counts = {
|
|
433
|
+
all: visible.length,
|
|
434
|
+
pinned: visible.filter((s) => state.pins.has(s.uid)).length,
|
|
435
|
+
week: visible.filter((s) => s.mtime >= weekAgo).length,
|
|
436
|
+
missing: visible.filter((s) => s.project.missing).length,
|
|
437
|
+
};
|
|
438
|
+
const emptyHidden = pool.length - visible.length;
|
|
439
|
+
let rows = state.sessTab === 'pinned' ? visible.filter((s) => state.pins.has(s.uid))
|
|
440
|
+
: state.sessTab === 'week' ? visible.filter((s) => s.mtime >= weekAgo)
|
|
441
|
+
: state.sessTab === 'missing' ? visible.filter((s) => s.project.missing) : visible;
|
|
442
|
+
if (state.sort === 'old') rows = rows.slice().reverse();
|
|
443
|
+
if (state.sort === 'big') rows = rows.slice().sort((a, b) => b.promptCount - a.promptCount);
|
|
444
|
+
return { rows, q, counts, emptyHidden };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ---------- date filter ----------
|
|
448
|
+
const ymd = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
|
|
449
|
+
function dateBounds() {
|
|
450
|
+
const v = $('dateRange').value;
|
|
451
|
+
if (!v) return null;
|
|
452
|
+
const today = new Date(); today.setHours(0, 0, 0, 0);
|
|
453
|
+
const t0 = today.getTime();
|
|
454
|
+
if (v === 'today') return [t0, Infinity];
|
|
455
|
+
if (v === 'yesterday') return [t0 - DAY, t0];
|
|
456
|
+
if (v === 'year') return [new Date(today.getFullYear(), 0, 1).getTime(), Infinity];
|
|
457
|
+
if (v === 'custom') {
|
|
458
|
+
const f = $('dateFrom').value;
|
|
459
|
+
const t = $('dateTo').value;
|
|
460
|
+
const from = f ? new Date(`${f}T00:00`).getTime() : -Infinity;
|
|
461
|
+
const to = t ? new Date(`${t}T00:00`).getTime() + DAY : Infinity;
|
|
462
|
+
return from > to ? [to - DAY, from + DAY] : [from, to];
|
|
463
|
+
}
|
|
464
|
+
return [t0 - (Number(v) - 1) * DAY, Infinity];
|
|
465
|
+
}
|
|
466
|
+
function dateLabel() {
|
|
467
|
+
const v = $('dateRange').value;
|
|
468
|
+
if (!v) return '';
|
|
469
|
+
if (v !== 'custom') return $('dateRange').selectedOptions[0].textContent;
|
|
470
|
+
const fmt = (x) => new Date(`${x}T00:00`).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
|
|
471
|
+
const f = $('dateFrom').value;
|
|
472
|
+
const t = $('dateTo').value;
|
|
473
|
+
if (f && t) return f === t ? fmt(f) : `${fmt(f)} – ${fmt(t)}`;
|
|
474
|
+
return f ? `from ${fmt(f)}` : t ? `until ${fmt(t)}` : 'any date';
|
|
475
|
+
}
|
|
476
|
+
function setDateFilter(range, from = '', to = '') {
|
|
477
|
+
$('dateRange').value = range;
|
|
478
|
+
$('dateFrom').value = from;
|
|
479
|
+
$('dateTo').value = to;
|
|
480
|
+
$('dateCustom').hidden = range !== 'custom';
|
|
481
|
+
state.shown = PAGE;
|
|
482
|
+
renderSessions();
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function dayLabel(ms) {
|
|
486
|
+
const d = new Date(ms); d.setHours(0, 0, 0, 0);
|
|
487
|
+
const today = new Date(); today.setHours(0, 0, 0, 0);
|
|
488
|
+
const diff = Math.round((today - d) / DAY);
|
|
489
|
+
if (diff <= 0) return 'Today';
|
|
490
|
+
if (diff === 1) return 'Yesterday';
|
|
491
|
+
if (diff < 7) return 'Previous 7 days';
|
|
492
|
+
if (diff < 30) return 'Previous 30 days';
|
|
493
|
+
return new Date(ms).toLocaleDateString(undefined, { month: 'long', year: 'numeric' });
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function renderSessions() {
|
|
497
|
+
const { rows, q, counts, emptyHidden } = filteredSessions();
|
|
498
|
+
$('sessTabs').innerHTML = [['all', 'All'], ['pinned', 'Bookmarked'], ['missing', 'Folder missing']]
|
|
499
|
+
.filter(([k]) => k === 'all' || counts[k] || state.sessTab === k)
|
|
500
|
+
.map(([k, label]) => `<button type="button" data-sesstab="${k}" aria-pressed="${state.sessTab === k}">${label} <span>${counts[k]}</span></button>`).join('');
|
|
501
|
+
$('count').textContent = `Showing ${Math.min(rows.length, state.shown).toLocaleString()} of ${plural(rows.length, 'session')}` + (dateBounds() ? ` · ${dateLabel()}` : '') +
|
|
502
|
+
(emptyHidden && !$('showEmpty').checked ? ` · ${emptyHidden} empty hidden` : '');
|
|
503
|
+
const visible = rows.slice(0, state.shown);
|
|
504
|
+
$('selectAll').checked = visible.length > 0 && visible.every((s) => state.selected.has(s.uid));
|
|
505
|
+
$('selectAll').indeterminate = !$('selectAll').checked && visible.some((s) => state.selected.has(s.uid));
|
|
506
|
+
|
|
507
|
+
let html = '';
|
|
508
|
+
let group = '';
|
|
509
|
+
for (const s of visible) {
|
|
510
|
+
if (state.sort !== 'big') {
|
|
511
|
+
const g = dayLabel(s.mtime);
|
|
512
|
+
if (g !== group) { group = g; html += `<h3 class="date-head eyebrow">${esc(g)}</h3>`; }
|
|
513
|
+
}
|
|
514
|
+
html += sessionRow(s, q, true);
|
|
515
|
+
}
|
|
516
|
+
const filtered = q || $('proj').value || state.sessTab !== 'all' || state.src || dateBounds();
|
|
517
|
+
$('list').innerHTML = html || (state.sessions.length
|
|
518
|
+
? emptyState(q ? `No sessions match “${q}”` : 'Nothing here', q
|
|
519
|
+
? 'Try fewer words, a folder name, or part of a session ID. Search also looks inside every prompt you typed.'
|
|
520
|
+
: 'Try another tab or project filter.', filtered ? '<button type="button" class="btn ghost" data-clear-filters>Clear filters</button>' : '')
|
|
521
|
+
: emptyState('No sessions found', 'Run <code>claude</code> in a folder and come back.'));
|
|
522
|
+
$('more').hidden = rows.length <= state.shown;
|
|
523
|
+
$('more').textContent = `Show more (${(rows.length - state.shown).toLocaleString()} left)`;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function renderBulk() {
|
|
527
|
+
const n = state.selected.size;
|
|
528
|
+
$('bulk').hidden = n === 0 || state.view !== 'sessions';
|
|
529
|
+
if (!n) return;
|
|
530
|
+
const sel = state.sessions.filter((s) => state.selected.has(s.uid));
|
|
531
|
+
const projects = new Set(sel.map((s) => s.project.key)).size;
|
|
532
|
+
$('bulkCount').textContent = plural(n, 'session');
|
|
533
|
+
$('bulkMeta').textContent = `selected · from ${plural(projects, 'project')} · ${size(sel.reduce((a, s) => a + s.size, 0))}`;
|
|
534
|
+
$('bulkGoLabel').textContent = `Move ${plural(n, 'session')}`;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// ---------- projects ----------
|
|
538
|
+
function renderProjects() {
|
|
539
|
+
const all = claudeProjects();
|
|
540
|
+
const missing = all.filter((p) => p.missing);
|
|
541
|
+
const ok = all.filter((p) => p.exists);
|
|
542
|
+
const other = all.filter((p) => !p.missing && !p.exists);
|
|
543
|
+
const cells = all.slice().sort((a, b) => Number(a.missing) - Number(b.missing) || Number(b.exists) - Number(a.exists))
|
|
544
|
+
.map((p, i) => `<i class="${p.missing ? 'm' : p.exists ? 'o' : 'u'}" style="--i:${i}" title="${esc(short(p.cwd) || p.key)}"></i>`).join('');
|
|
545
|
+
$('projSummary').innerHTML = `
|
|
546
|
+
<div class="sum-main">
|
|
547
|
+
<p class="eyebrow">Projects · storage</p>
|
|
548
|
+
<div class="sum-num"><span>${plural(all.length, 'project')}</span><span class="muted small">${size(all.reduce((n, p) => n + p.bytes, 0))} of sessions</span></div>
|
|
549
|
+
<div class="segbar" role="img" aria-label="${ok.length} found, ${other.length} memory only, ${missing.length} missing">${cells}</div>
|
|
550
|
+
<div class="legend">
|
|
551
|
+
<span><i class="o"></i>${ok.length} folder found</span>
|
|
552
|
+
<span><i class="u"></i>${other.length} memory only</span>
|
|
553
|
+
<span><i class="m"></i>${missing.length} folder missing <span class="muted">${plural(missing.reduce((n, p) => n + p.sessions.length, 0), 'session')}</span></span>
|
|
554
|
+
</div>
|
|
555
|
+
</div>
|
|
556
|
+
<div class="sum-side">
|
|
557
|
+
<p class="eyebrow">Why sessions vanish</p>
|
|
558
|
+
<p class="small">Claude stores chats under the folder's path. Rename <code>app</code> to <code>app-v2</code> and the chats stay filed under <code>app</code>.</p>
|
|
559
|
+
</div>`;
|
|
560
|
+
|
|
561
|
+
$('projTabs').innerHTML = [['all', 'All', all.length], ['missing', 'Needs you', missing.length], ['ok', 'Healthy', ok.length]]
|
|
562
|
+
.map(([k, label, n]) => `<button type="button" data-projtab="${k}" aria-pressed="${state.projTab === k}">${label} <span>${n}</span></button>`).join('');
|
|
563
|
+
|
|
564
|
+
const maxBytes = Math.max(1, ...all.map((p) => p.bytes));
|
|
565
|
+
const row = (p) => `
|
|
566
|
+
<div class="tr${p.missing ? ' missing' : ''}">
|
|
567
|
+
<div class="td-folder">
|
|
568
|
+
<span class="ficon ${p.missing ? 'm' : p.exists ? 'o' : 'u'}">${p.missing ? ICON.warn : ICON.folder}</span>
|
|
569
|
+
<div class="min0"><div class="row-title">${esc(base(p.cwd) || p.key)}</div><div class="mono-s">${esc(short(p.cwd) || 'no sessions, memory only')}</div></div>
|
|
570
|
+
</div>
|
|
571
|
+
<div class="td-num">${p.sessions.length}</div>
|
|
572
|
+
<div class="td-date">${p.updated ? ago(p.updated) : '—'}</div>
|
|
573
|
+
<div class="td-bar"><span class="meter"><span style="width:${Math.max(2, (p.bytes / maxBytes) * 100)}%"></span></span><span class="small muted">${p.bytes ? size(p.bytes) : '—'}</span></div>
|
|
574
|
+
<div class="td-status">${p.missing ? `<span class="chip danger">${ICON.warn}Folder missing</span>` : p.exists ? `<span class="chip ok">${ICON.check}Found</span>` : '<span class="chip">Memory only</span>'}</div>
|
|
575
|
+
<div class="td-act">
|
|
576
|
+
${p.sessions.length ? `<button type="button" class="btn ghost sm" data-show="${esc(p.key)}">Sessions</button>` : ''}
|
|
577
|
+
<button type="button" class="btn ${p.missing ? 'accent' : 'ghost'} sm" data-move="${esc(p.key)}">${p.missing ? 'Fix' : 'Move'}</button>
|
|
578
|
+
</div>
|
|
579
|
+
</div>`;
|
|
580
|
+
const group = (label, note, list) => (list.length
|
|
581
|
+
? `<div class="group-head"><span class="eyebrow">${label} · ${list.length}</span><span class="muted small">${note}</span></div>${list.map(row).join('')}`
|
|
582
|
+
: '');
|
|
583
|
+
const t = state.projTab;
|
|
584
|
+
$('projects').innerHTML = `
|
|
585
|
+
<div class="thead"><span>Folder</span><span>Sessions</span><span>Last used</span><span>Storage</span><span>Status</span><span></span></div>
|
|
586
|
+
${t !== 'ok' ? group('Needs you', 'Folder renamed or deleted: move its sessions to the new folder', missing) : ''}
|
|
587
|
+
${t !== 'missing' ? group('Healthy', 'Folder exists: claude --resume finds these', ok) : ''}
|
|
588
|
+
${t === 'all' ? group('Memory only', 'No sessions left, only project memory', other) : ''}
|
|
589
|
+
${t === 'missing' && !missing.length ? `<div class="good pad">${ICON.check}Nothing needs you. Every project folder still exists.</div>` : ''}`;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// ---------- backups ----------
|
|
593
|
+
async function renderBackups() {
|
|
594
|
+
$('backups').innerHTML = '<div class="row skel"><span class="sk" style="width:40%"></span><span class="sk" style="width:60%"></span></div>';
|
|
595
|
+
try {
|
|
596
|
+
const { backups } = await api('/api/backups');
|
|
597
|
+
$('backups').innerHTML = backups.map((b) => `
|
|
598
|
+
<div class="row">
|
|
599
|
+
<div class="row-title">${esc(base(b.from) || b.key)}${b.to ? ` <span class="muted">→</span> ${esc(base(b.to))}` : ''}</div>
|
|
600
|
+
<div class="row-meta"><span>${date(Date.parse(b.at))}</span><span class="sep">·</span><span>${plural(b.sessions, 'session')}</span><span class="sep">·</span><span class="mono-s">${esc(short(b.from))}${b.to ? ` → ${esc(short(b.to))}` : ''}</span></div>
|
|
601
|
+
<div class="row-side"><button type="button" class="btn ghost sm" data-restore="${esc(b.name)}">Restore</button></div>
|
|
602
|
+
</div>`).join('') || emptyState('No backups yet', 'A backup is saved automatically before every move, so you can always put things back.');
|
|
603
|
+
if (state.view === 'backups') stagger($('backups'));
|
|
604
|
+
} catch (e) {
|
|
605
|
+
$('backups').innerHTML = emptyState('Could not load backups', esc(e.message));
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// ---------- markdown (escape first, then add a small safe subset) ----------
|
|
610
|
+
function inline(s) {
|
|
611
|
+
const codes = [];
|
|
612
|
+
let t = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; });
|
|
613
|
+
t = esc(t);
|
|
614
|
+
t = t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (_, txt, url) => `<a href="${url}" target="_blank" rel="noopener noreferrer">${txt}</a>`);
|
|
615
|
+
t = t.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
|
|
616
|
+
t = t.replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');
|
|
617
|
+
return t.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${esc(codes[Number(i)])}</code>`);
|
|
618
|
+
}
|
|
619
|
+
const indentOf = (l) => l.match(/^\s*/)[0].length;
|
|
620
|
+
const ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
|
|
621
|
+
function codeBlock(code, lang) {
|
|
622
|
+
return `<div class="code"><div class="code-head"><span>${esc(lang || 'text')}</span><button type="button" data-copycode><span>Copy</span></button></div><pre><code>${esc(code)}</code></pre></div>`;
|
|
623
|
+
}
|
|
624
|
+
function parseList(lines, i) {
|
|
625
|
+
const baseIndent = indentOf(lines[i]);
|
|
626
|
+
const ordered = /^\s*\d/.test(lines[i]);
|
|
627
|
+
const items = [];
|
|
628
|
+
while (i < lines.length) {
|
|
629
|
+
const l = lines[i];
|
|
630
|
+
const m = l.match(ITEM);
|
|
631
|
+
const ind = indentOf(l);
|
|
632
|
+
const cur = items[items.length - 1];
|
|
633
|
+
if (m && ind === baseIndent) { items.push([m[3]]); i++; continue; }
|
|
634
|
+
if (!l.trim()) {
|
|
635
|
+
const nx = lines[i + 1];
|
|
636
|
+
if (nx !== undefined && nx.trim() && (indentOf(nx) > baseIndent || (ITEM.test(nx) && indentOf(nx) === baseIndent))) { cur.push(''); i++; continue; }
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
if (ind > baseIndent) { cur.push(l.slice(Math.min(ind, baseIndent + 2))); i++; continue; }
|
|
640
|
+
if (cur[cur.length - 1] !== '' && !/^\s*(#|```|~~~|>|\|)/.test(l)) { cur.push(l.trim()); i++; continue; }
|
|
641
|
+
break;
|
|
642
|
+
}
|
|
643
|
+
const tag = ordered ? 'ol' : 'ul';
|
|
644
|
+
return { html: `<${tag}>${items.map((it) => `<li>${md(it.join('\n'))}</li>`).join('')}</${tag}>`, i };
|
|
645
|
+
}
|
|
646
|
+
function md(src) {
|
|
647
|
+
const lines = String(src).replace(/\r/g, '').split('\n');
|
|
648
|
+
let out = '';
|
|
649
|
+
let para = [];
|
|
650
|
+
const flush = () => { if (para.length) { out += `<p>${para.map(inline).join('<br>')}</p>`; para = []; } };
|
|
651
|
+
let i = 0;
|
|
652
|
+
while (i < lines.length) {
|
|
653
|
+
const line = lines[i];
|
|
654
|
+
const fence = line.match(/^\s*(```+|~~~+)\s*([\w+#.-]*)/);
|
|
655
|
+
if (fence) {
|
|
656
|
+
flush();
|
|
657
|
+
const ind = indentOf(line);
|
|
658
|
+
const body = [];
|
|
659
|
+
i++;
|
|
660
|
+
while (i < lines.length && !/^\s*(```+|~~~+)\s*$/.test(lines[i])) { body.push(lines[i].slice(Math.min(ind, indentOf(lines[i])))); i++; }
|
|
661
|
+
i++;
|
|
662
|
+
out += codeBlock(body.join('\n'), fence[2]);
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
if (!line.trim()) { flush(); i++; continue; }
|
|
666
|
+
let m;
|
|
667
|
+
if ((m = line.match(/^\s{0,3}(#{1,4})\s+(.*)$/))) { flush(); out += `<h${m[1].length}>${inline(m[2])}</h${m[1].length}>`; i++; continue; }
|
|
668
|
+
if (/^\s*(---+|\*\*\*+|___+)\s*$/.test(line)) { flush(); out += '<hr>'; i++; continue; }
|
|
669
|
+
if (/^\s*>/.test(line)) {
|
|
670
|
+
flush();
|
|
671
|
+
const q = [];
|
|
672
|
+
while (i < lines.length && /^\s*>/.test(lines[i])) { q.push(lines[i].replace(/^\s*>\s?/, '')); i++; }
|
|
673
|
+
out += `<blockquote>${md(q.join('\n'))}</blockquote>`;
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
if (/^\s*\|.*\|\s*$/.test(line) && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1] || '')) {
|
|
677
|
+
flush();
|
|
678
|
+
const cells = (l) => l.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim());
|
|
679
|
+
const head = cells(line);
|
|
680
|
+
i += 2;
|
|
681
|
+
const rows = [];
|
|
682
|
+
while (i < lines.length && /^\s*\|/.test(lines[i])) { rows.push(cells(lines[i])); i++; }
|
|
683
|
+
out += `<table><thead><tr>${head.map((c) => `<th>${inline(c)}</th>`).join('')}</tr></thead><tbody>${rows.map((r) => `<tr>${r.map((c) => `<td>${inline(c)}</td>`).join('')}</tr>`).join('')}</tbody></table>`;
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
if (ITEM.test(line)) { flush(); const r = parseList(lines, i); out += r.html; i = r.i; continue; }
|
|
687
|
+
para.push(line.trim());
|
|
688
|
+
i++;
|
|
689
|
+
}
|
|
690
|
+
flush();
|
|
691
|
+
return out;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// ---------- session detail ----------
|
|
695
|
+
const timeOf = (ts) => new Date(ts).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
|
|
696
|
+
function renderMsg(m, idx) {
|
|
697
|
+
const user = m.role === 'user';
|
|
698
|
+
const long = m.text.length > 1800 || (m.text.match(/\n/g) || []).length > 32;
|
|
699
|
+
const tools = m.tools.slice(0, 12);
|
|
700
|
+
const sid = state.detail ? state.detail.id : '';
|
|
701
|
+
const srcNow = state.detail ? state.detail.source : 'claude';
|
|
702
|
+
const uuids = m.uuids && m.uuids.length ? m.uuids : (m.uuid ? [m.uuid] : []);
|
|
703
|
+
const bm = m.uuid && sid ? state.bmIndex.get(`${sid}|${m.uuid}`) : null;
|
|
704
|
+
const ext = sid ? uuids.map((u) => state.extIndex.get(`${sid}|${u}`)).find(Boolean) : null;
|
|
705
|
+
return `<article class="msg ${m.role}${bm || ext ? ' is-bm' : ''}" data-i="${idx}" data-uuid="${esc(m.uuid || '')}" data-uuids="${esc(uuids.join(' '))}">
|
|
706
|
+
<div class="avatar${user ? '' : ` s-${esc(srcNow)}`}" aria-hidden="true">${user ? 'Y' : esc(assistantOf(srcNow)[1])}</div>
|
|
707
|
+
<div class="min0">
|
|
708
|
+
<div class="msg-head"><b>${user ? 'You' : esc(assistantOf(srcNow)[0])}</b>${m.ts ? `<span class="time">${timeOf(m.ts)}</span>` : ''}${ext ? `<span class="src-badge" title="Bookmarked with the ${esc(ext.source)} extension">${ICON.bookmark}${esc(ext.source)}</span>` : ''}<span class="msg-actions">${m.uuid ? `<button type="button" class="msg-bm" data-bm="${idx}" aria-pressed="${Boolean(bm)}" aria-label="${bm ? 'Remove bookmark' : 'Bookmark this message'}" title="${bm ? 'Remove bookmark' : 'Bookmark this message'}">${ICON.bookmark}</button>` : ''}${m.text ? `<button type="button" class="msg-copy" data-copymsg="${idx}"><span>Copy</span></button>` : ''}</span></div>
|
|
709
|
+
${m.text ? `<div class="bubble"><div class="md${long ? ' clamp' : ''}">${md(m.text)}</div>${long ? '<button type="button" class="more-btn" data-more>Show more</button>' : ''}</div>` : ''}
|
|
710
|
+
${bm ? `<label class="bm-note">${ICON.bookmark}<span class="sr-only">Bookmark note</span><input type="text" data-bmnote="${esc(bm.id)}" value="${esc(bm.note || '')}" placeholder="Add a note to this bookmark…" maxlength="500"></label>` : ''}
|
|
711
|
+
${tools.length ? `<div class="tools-row">${tools.map((t) => `<span class="tool"><b>${esc(t.name || t)}</b>${t.detail ? ' ' + esc(t.detail) : ''}</span>`).join('')}${m.tools.length > 12 ? `<span class="tool">+${m.tools.length - 12} more</span>` : ''}</div>` : ''}
|
|
712
|
+
</div>
|
|
713
|
+
</article>`;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function syncPinButton() {
|
|
717
|
+
const on = Boolean(state.detail && state.pins.has(state.detail.uid));
|
|
718
|
+
$('detailPin').setAttribute('aria-pressed', String(on));
|
|
719
|
+
$('detailPin').setAttribute('aria-label', on ? 'Remove chat bookmark' : 'Bookmark this chat');
|
|
720
|
+
$('detailPin').title = on ? 'Remove chat bookmark' : 'Bookmark this chat';
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async function openDetail(uid, focusUuid = '') {
|
|
724
|
+
const s = state.byUid.get(uid) || state.sessions.find((x) => x.id === String(uid).split('|').pop());
|
|
725
|
+
if (!s) return;
|
|
726
|
+
const p = s.project;
|
|
727
|
+
state.detail = s;
|
|
728
|
+
state.msgs = [];
|
|
729
|
+
state.focusMsg = focusUuid;
|
|
730
|
+
renderMarks();
|
|
731
|
+
$('detailProject').textContent = `${toolLabel(s.source)} · ${short(p.cwd) || 'no project folder'}`;
|
|
732
|
+
$('detailTitle').textContent = s.title;
|
|
733
|
+
$('detailMeta').innerHTML = [
|
|
734
|
+
p.missing ? `<span class="chip danger">${ICON.warn}folder missing</span>` : '',
|
|
735
|
+
`<span class="chip">${ICON.clock}${date(s.mtime)}</span>`,
|
|
736
|
+
s.branch ? `<span class="chip">${ICON.branch}${esc(s.branch)}</span>` : '',
|
|
737
|
+
toolBadge(s.source),
|
|
738
|
+
`<span class="chip">${plural(s.promptCount, 'prompt')}</span>`,
|
|
739
|
+
`<span class="chip">${size(s.size)}</span>`,
|
|
740
|
+
`<span class="chip mono-s">${esc(s.id)}</span>`,
|
|
741
|
+
].join('');
|
|
742
|
+
const ri = resumeInfo(s);
|
|
743
|
+
$('resumeLabel').textContent = ri.label;
|
|
744
|
+
$('detailCmd').textContent = ri.cmd;
|
|
745
|
+
$('detailCmd').hidden = !ri.cmd;
|
|
746
|
+
$('detailOpenLabel').textContent = ri.open;
|
|
747
|
+
$('detailOpen').disabled = ri.kind === 'none' || (ri.kind === 'url' ? !ri.url : !p.exists);
|
|
748
|
+
$('detailOpen').title = ri.kind === 'url' ? 'Opens the chat in your browser' : p.exists ? 'Opens the project folder' : (s.source === 'claude' ? 'Move this session to the new folder first' : 'This chat has no project folder on this computer');
|
|
749
|
+
$('detailOpen').querySelector('use').setAttribute('href', ri.kind === 'url' ? '#i-link' : ri.kind === 'app' ? '#i-folder' : '#i-terminal');
|
|
750
|
+
$('resumeNote').hidden = !ri.note;
|
|
751
|
+
$('resumeNote').textContent = ri.note || '';
|
|
752
|
+
$('detailMove').hidden = s.source !== 'claude';
|
|
753
|
+
$('detailCopy').hidden = !ri.cmd;
|
|
754
|
+
syncPinButton();
|
|
755
|
+
$('find').value = '';
|
|
756
|
+
$('findCount').textContent = '';
|
|
757
|
+
setWho('all');
|
|
758
|
+
$('transcript').innerHTML = [30, 80, 55, 70].map((w, i) => `<div class="msg skel"><span class="avatar sk"></span><div><span class="sk" style="width:${w}%"></span><span class="sk" style="width:${[60, 90, 40, 85][i]}%"></span></div></div>`).join('');
|
|
759
|
+
$('transcript').setAttribute('aria-busy', 'true');
|
|
760
|
+
if (!$('detail').open) $('detail').showModal();
|
|
761
|
+
history.replaceState(null, '', `#s=${encodeURIComponent(s.uid)}`);
|
|
762
|
+
$('transcript').scrollTop = 0;
|
|
763
|
+
try {
|
|
764
|
+
const { messages } = await api(`/api/session?key=${encodeURIComponent(p.key)}&id=${encodeURIComponent(s.id)}`);
|
|
765
|
+
if (state.detail !== s) return;
|
|
766
|
+
state.msgs = messages;
|
|
767
|
+
$('transcript').innerHTML = messages.map(renderMsg).join('') || emptyState('No readable messages', 'This session has no text messages, only tool activity.');
|
|
768
|
+
renderMarks();
|
|
769
|
+
if (state.focusMsg) { scrollToMsg(state.focusMsg); state.focusMsg = ''; } else stagger($('transcript'), ':scope > .msg', 8);
|
|
770
|
+
} catch (e) {
|
|
771
|
+
$('transcript').innerHTML = `<p class="error">${esc(e.message)}</p>`;
|
|
772
|
+
} finally {
|
|
773
|
+
$('transcript').removeAttribute('aria-busy');
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function expandClamp(c) {
|
|
778
|
+
c.classList.remove('clamp');
|
|
779
|
+
const b = c.parentElement.querySelector('[data-more]');
|
|
780
|
+
if (b) b.remove();
|
|
781
|
+
}
|
|
782
|
+
function setWho(who) {
|
|
783
|
+
document.querySelectorAll('[data-who]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.who === who)));
|
|
784
|
+
document.querySelectorAll('#transcript .msg').forEach((m) => m.classList.toggle('dim', (who === 'user' && m.classList.contains('assistant')) || (who === 'bm' && !m.classList.contains('is-bm'))));
|
|
785
|
+
}
|
|
786
|
+
function clearHits() {
|
|
787
|
+
const t = $('transcript');
|
|
788
|
+
t.querySelectorAll('mark.hit').forEach((m) => m.replaceWith(document.createTextNode(m.textContent)));
|
|
789
|
+
t.normalize();
|
|
790
|
+
state.hits = [];
|
|
791
|
+
}
|
|
792
|
+
function findInConvo(q) {
|
|
793
|
+
clearHits();
|
|
794
|
+
if (!q) { $('findCount').textContent = ''; return; }
|
|
795
|
+
const ql = q.toLowerCase();
|
|
796
|
+
const walker = document.createTreeWalker($('transcript'), NodeFilter.SHOW_TEXT, {
|
|
797
|
+
acceptNode: (n) => (n.parentElement.closest('.md, .tools-row') && !n.parentElement.closest('.msg.dim') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT),
|
|
798
|
+
});
|
|
799
|
+
const nodes = [];
|
|
800
|
+
while (walker.nextNode()) nodes.push(walker.currentNode);
|
|
801
|
+
for (const n of nodes) {
|
|
802
|
+
const t = n.nodeValue;
|
|
803
|
+
const low = t.toLowerCase();
|
|
804
|
+
let i = low.indexOf(ql);
|
|
805
|
+
if (i < 0) continue;
|
|
806
|
+
const frag = document.createDocumentFragment();
|
|
807
|
+
let last = 0;
|
|
808
|
+
while (i >= 0) {
|
|
809
|
+
frag.append(t.slice(last, i));
|
|
810
|
+
const mk = document.createElement('mark');
|
|
811
|
+
mk.className = 'hit';
|
|
812
|
+
mk.textContent = t.slice(i, i + q.length);
|
|
813
|
+
frag.append(mk);
|
|
814
|
+
state.hits.push(mk);
|
|
815
|
+
last = i + q.length;
|
|
816
|
+
i = low.indexOf(ql, last);
|
|
817
|
+
}
|
|
818
|
+
frag.append(t.slice(last));
|
|
819
|
+
n.replaceWith(frag);
|
|
820
|
+
}
|
|
821
|
+
if (!state.hits.length) { $('findCount').textContent = 'No matches'; return; }
|
|
822
|
+
focusHit(0);
|
|
823
|
+
}
|
|
824
|
+
function focusHit(i) {
|
|
825
|
+
if (!state.hits.length) return;
|
|
826
|
+
state.hits.forEach((h) => h.classList.remove('cur'));
|
|
827
|
+
state.hitIdx = (i + state.hits.length) % state.hits.length;
|
|
828
|
+
const h = state.hits[state.hitIdx];
|
|
829
|
+
h.classList.add('cur');
|
|
830
|
+
const c = h.closest('.clamp');
|
|
831
|
+
if (c) expandClamp(c);
|
|
832
|
+
h.scrollIntoView({ block: 'center', behavior: motionOn() ? 'smooth' : 'auto' });
|
|
833
|
+
$('findCount').textContent = `${state.hitIdx + 1} / ${state.hits.length}`;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
async function openTerminal() {
|
|
837
|
+
const s = state.detail;
|
|
838
|
+
if (!s) return;
|
|
839
|
+
const b = $('detailOpen');
|
|
840
|
+
b.disabled = true;
|
|
841
|
+
try {
|
|
842
|
+
const ri = resumeInfo(s);
|
|
843
|
+
if (ri.kind === 'url') { window.open(ri.url, '_blank', 'noopener,noreferrer'); return; }
|
|
844
|
+
const r = await api('/api/open-terminal', { key: s.project.key, id: s.id });
|
|
845
|
+
toast(r.app ? `Opened the project in ${r.terminal}.` : `Opened in ${r.terminal}.`);
|
|
846
|
+
} catch (e) {
|
|
847
|
+
toast(e.message);
|
|
848
|
+
} finally {
|
|
849
|
+
const ri = resumeInfo(s);
|
|
850
|
+
b.disabled = ri.kind === 'url' ? !ri.url : !s.project.exists;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// ---------- tools: filter chips, overview panel, sources dialog, import ----------
|
|
855
|
+
function toolCounts() {
|
|
856
|
+
const c = {};
|
|
857
|
+
for (const s of state.sessions) c[s.source] = (c[s.source] || 0) + 1;
|
|
858
|
+
return c;
|
|
859
|
+
}
|
|
860
|
+
function renderTools() {
|
|
861
|
+
const c = toolCounts();
|
|
862
|
+
const ids = Object.keys(TOOLS).filter((id) => c[id]);
|
|
863
|
+
$('srcTabs').hidden = ids.length < 2;
|
|
864
|
+
$('srcTabs').innerHTML = [`<button type="button" data-src="" aria-pressed="${!state.src}">All tools <span>${state.sessions.length.toLocaleString()}</span></button>`,
|
|
865
|
+
...ids.map((id) => `<button type="button" data-src="${id}" aria-pressed="${state.src === id}"><i class="dot s-${id}"></i>${esc(toolLabel(id))} <span>${c[id].toLocaleString()}</span></button>`)].join('');
|
|
866
|
+
$('toolCount').textContent = ids.length ? ids.length : '';
|
|
867
|
+
$('toolPanel').hidden = ids.length < 2;
|
|
868
|
+
const max = Math.max(1, ...ids.map((id) => c[id]));
|
|
869
|
+
$('toolBars').innerHTML = ids.sort((a, b) => c[b] - c[a]).map((id, i) => `<button type="button" class="row" data-src="${id}">
|
|
870
|
+
<div class="row-title"><i class="dot s-${id}"></i>${esc(toolLabel(id))}</div>
|
|
871
|
+
<div class="row-side"><span class="muted small">${plural(c[id], 'chat')}</span></div>
|
|
872
|
+
<div class="bar-mini"><span class="s-${id}" style="width:${Math.max(4, (c[id] / max) * 100)}%; --i:${i}"></span></div>
|
|
873
|
+
</button>`).join('');
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
async function openSources() {
|
|
877
|
+
document.querySelectorAll('dialog[open]').forEach((d) => d.close());
|
|
878
|
+
$('importMsg').textContent = '';
|
|
879
|
+
$('srcList').innerHTML = '<div class="row skel"><span class="sk" style="width:50%"></span><span class="sk" style="width:70%"></span></div>';
|
|
880
|
+
$('sources').showModal();
|
|
881
|
+
try {
|
|
882
|
+
const { sources } = await api('/api/sources');
|
|
883
|
+
state.sources = sources;
|
|
884
|
+
$('srcList').innerHTML = sources.map((t) => `<div class="src-row${t.found ? '' : ' off'}">
|
|
885
|
+
<i class="dot s-${esc(t.id)}"></i>
|
|
886
|
+
<div class="min0">
|
|
887
|
+
<div class="src-name">${esc(t.label)}${t.experimental ? ' <span class="chip">experimental</span>' : ''}${t.imported ? ' <span class="chip">import</span>' : ''}</div>
|
|
888
|
+
<div class="mono-s">${esc(short(t.path || ''))}</div>
|
|
889
|
+
${t.note ? `<div class="small error">${esc(t.note)}</div>` : ''}
|
|
890
|
+
${t.imported && t.found ? `<div class="small muted">Imported ${esc(date(Date.parse(t.importedAt)))}${t.file ? ` from ${esc(t.file)}` : ''}</div>` : ''}
|
|
891
|
+
</div>
|
|
892
|
+
<div class="src-state">${t.found ? `<span class="chip ok">${ICON.check}${plural(t.count, 'chat')}</span>` : `<span class="chip">${t.imported ? 'Not imported' : 'Not found'}</span>`}
|
|
893
|
+
${t.imported && t.found ? `<button type="button" class="btn ghost sm" data-rmimport="${esc(t.id)}">Remove</button>` : ''}</div>
|
|
894
|
+
</div>`).join('');
|
|
895
|
+
} catch (e) {
|
|
896
|
+
$('srcList').innerHTML = `<p class="error">${esc(e.message)}</p>`;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
async function uploadExport(file) {
|
|
901
|
+
if (!file) return;
|
|
902
|
+
$('importMsg').className = 'small';
|
|
903
|
+
$('importMsg').textContent = `Reading ${file.name} (${size(file.size)})…`;
|
|
904
|
+
$('drop').classList.add('busy');
|
|
905
|
+
try {
|
|
906
|
+
const res = await fetch('/api/import', { method: 'POST', headers: { 'X-Token': window.CSM_TOKEN, 'Content-Type': 'application/octet-stream', 'X-Filename': encodeURIComponent(file.name).slice(0, 200) }, body: file });
|
|
907
|
+
const data = await res.json().catch(() => ({}));
|
|
908
|
+
if (!res.ok) throw new Error(data.error || `Import failed (${res.status})`);
|
|
909
|
+
$('importMsg').className = 'small ok-t';
|
|
910
|
+
$('importMsg').textContent = `Imported ${plural(data.total, 'chat')} from ${data.label}: ${data.added} new, ${data.updated} updated.`;
|
|
911
|
+
await load();
|
|
912
|
+
await openSourcesListOnly();
|
|
913
|
+
} catch (e) {
|
|
914
|
+
$('importMsg').className = 'small error';
|
|
915
|
+
$('importMsg').textContent = e.message;
|
|
916
|
+
} finally {
|
|
917
|
+
$('drop').classList.remove('busy');
|
|
918
|
+
$('importFile').value = '';
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
async function openSourcesListOnly() { if ($('sources').open) { const msg = $('importMsg').textContent; const cls = $('importMsg').className; await openSources(); $('importMsg').textContent = msg; $('importMsg').className = cls; } }
|
|
922
|
+
async function removeImport(source) {
|
|
923
|
+
try {
|
|
924
|
+
await api('/api/imports/delete', { source });
|
|
925
|
+
toast(`Removed the ${toolLabel(source)} import`);
|
|
926
|
+
await load();
|
|
927
|
+
await openSourcesListOnly();
|
|
928
|
+
} catch (e) { toast(e.message); }
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// ---------- bookmarks ----------
|
|
932
|
+
function setExternal(list) {
|
|
933
|
+
state.external = (list || []).filter((b) => b && b.sessionId && b.msgUuid);
|
|
934
|
+
state.extIndex = new Map(state.external.map((b) => [`${b.sessionId}|${b.msgUuid}`, b]));
|
|
935
|
+
}
|
|
936
|
+
// Message bookmarks from both places (ours + the VS Code extension's), newest first.
|
|
937
|
+
const msgMarks = () => [...state.bookmarks, ...state.external].sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
938
|
+
const allMarks = () => [...state.bookmarks, ...state.chatMarks.values()];
|
|
939
|
+
function setBookmarks(list) {
|
|
940
|
+
const sorted = (list || []).slice().sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
941
|
+
state.chatMarks = new Map(sorted.filter((b) => b.kind === 'chat').map((b) => [b.sessionId, b]));
|
|
942
|
+
state.bookmarks = sorted.filter((b) => b.kind !== 'chat');
|
|
943
|
+
if (state.sessions.length) computePins();
|
|
944
|
+
state.bmIndex = new Map(state.bookmarks.map((b) => [`${b.sessionId}|${b.msgUuid}`, b]));
|
|
945
|
+
}
|
|
946
|
+
const sessionById = (id) => state.sessions.find((s) => s.id === id);
|
|
947
|
+
const stripMd = (t) => String(t || '')
|
|
948
|
+
.replace(/```[\w+#.-]*\n?([\s\S]*?)```/g, '$1')
|
|
949
|
+
.replace(/^\s{0,3}#{1,4}\s+/gm, '')
|
|
950
|
+
.replace(/^\s*([-*+]|\d+[.)])\s+/gm, '')
|
|
951
|
+
.replace(/\*\*([^*]+)\*\*/g, '$1')
|
|
952
|
+
.replace(/`([^`]+)`/g, '$1')
|
|
953
|
+
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
|
954
|
+
.replace(/\|?(\s*:?-{3,}:?\s*\|)+/g, ' ')
|
|
955
|
+
.replace(/\s*\|\s*/g, ' · ')
|
|
956
|
+
.replace(/(\s*·\s*)+/g, ' · ')
|
|
957
|
+
.replace(/^\s*·\s*|\s*·\s*$/gm, '');
|
|
958
|
+
const bmSnippet = (m) => (stripMd(m.text) || (m.tools || []).map((t) => `${t.name || t}${t.detail ? ' ' + t.detail : ''}`).join(' · ')).replace(/\s+/g, ' ').trim();
|
|
959
|
+
|
|
960
|
+
async function toggleBookmark(idx) {
|
|
961
|
+
const s = state.detail;
|
|
962
|
+
const m = state.msgs[idx];
|
|
963
|
+
if (!s || !m || !m.uuid) return;
|
|
964
|
+
const key = `${s.id}|${m.uuid}`;
|
|
965
|
+
const existing = state.bmIndex.get(key);
|
|
966
|
+
try {
|
|
967
|
+
if (existing) {
|
|
968
|
+
await api('/api/bookmarks/delete', { id: existing.id });
|
|
969
|
+
setBookmarks(allMarks().filter((b) => b.id !== existing.id));
|
|
970
|
+
toast('Bookmark removed');
|
|
971
|
+
} else {
|
|
972
|
+
const { bookmark } = await api('/api/bookmarks', {
|
|
973
|
+
sessionId: s.id, msgUuid: m.uuid, role: m.role, text: bmSnippet(m).slice(0, 600), ts: m.ts, title: s.title, cwd: s.project.cwd, note: '',
|
|
974
|
+
});
|
|
975
|
+
setBookmarks([bookmark, ...allMarks()]);
|
|
976
|
+
toast('Bookmarked. Add a note under the message if you like.');
|
|
977
|
+
}
|
|
978
|
+
} catch (e) { toast(e.message); return; }
|
|
979
|
+
const art = document.querySelector(`#transcript .msg[data-i="${idx}"]`);
|
|
980
|
+
if (art) {
|
|
981
|
+
art.outerHTML = renderMsg(m, idx);
|
|
982
|
+
const fresh = document.querySelector(`#transcript .msg[data-i="${idx}"]`);
|
|
983
|
+
if (!existing && fresh) { replay(fresh, 'flash'); const inp = fresh.querySelector('[data-bmnote]'); if (inp) inp.focus({ preventScroll: true }); }
|
|
984
|
+
}
|
|
985
|
+
renderMarks();
|
|
986
|
+
renderBookmarks();
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
async function saveNote(input) {
|
|
990
|
+
const b = allMarks().find((x) => x.id === input.dataset.bmnote);
|
|
991
|
+
if (!b || (b.note || '') === input.value.trim()) return;
|
|
992
|
+
try {
|
|
993
|
+
const { bookmark } = await api('/api/bookmarks', { ...b, note: input.value.trim() });
|
|
994
|
+
Object.assign(b, bookmark);
|
|
995
|
+
input.closest('.bm-note, .bm-item')?.classList.add('saved');
|
|
996
|
+
setTimeout(() => input.closest('.bm-note, .bm-item')?.classList.remove('saved'), 1200);
|
|
997
|
+
renderMarks();
|
|
998
|
+
if (state.view !== 'bookmarks') renderBookmarks();
|
|
999
|
+
else document.querySelectorAll(`[data-bmnote="${CSS.escape(b.id)}"]`).forEach((el) => { if (el !== input) el.value = b.note; });
|
|
1000
|
+
} catch (e) { toast(e.message); }
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
async function removeBookmark(id) {
|
|
1004
|
+
try {
|
|
1005
|
+
await api('/api/bookmarks/delete', { id });
|
|
1006
|
+
const wasChat = [...state.chatMarks.values()].some((b) => b.id === id);
|
|
1007
|
+
setBookmarks(allMarks().filter((b) => b.id !== id));
|
|
1008
|
+
toast('Bookmark removed');
|
|
1009
|
+
if (wasChat) { computePins(); renderAll(); if (state.detail) syncPinButton(); } else renderBookmarks();
|
|
1010
|
+
if (state.detail) { renderMarks(); $('transcript').querySelectorAll('.msg.is-bm').forEach((el) => { const i = Number(el.dataset.i); if (!state.bmIndex.get(`${state.detail.id}|${el.dataset.uuid}`)) el.outerHTML = renderMsg(state.msgs[i], i); }); }
|
|
1011
|
+
} catch (e) { toast(e.message); }
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
function scrollToMsg(uuid) {
|
|
1015
|
+
const el = [...document.querySelectorAll('#transcript .msg')].find((x) => (x.dataset.uuids || '').split(' ').includes(uuid));
|
|
1016
|
+
if (!el) { toast('That message is no longer in this session.'); return; }
|
|
1017
|
+
const c = el.querySelector('.clamp');
|
|
1018
|
+
if (c) expandClamp(c);
|
|
1019
|
+
el.classList.remove('dim');
|
|
1020
|
+
el.scrollIntoView({ block: 'center', behavior: motionOn() ? 'smooth' : 'auto' });
|
|
1021
|
+
el.classList.remove('flash');
|
|
1022
|
+
void el.offsetWidth;
|
|
1023
|
+
el.classList.add('flash');
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
function renderMarks() {
|
|
1027
|
+
const s = state.detail;
|
|
1028
|
+
const marks = s ? msgMarks().filter((b) => b.sessionId === s.id) : [];
|
|
1029
|
+
$('detailMarks').hidden = !marks.length;
|
|
1030
|
+
const order = new Map(state.msgs.flatMap((m, i) => (m.uuids || [m.uuid]).map((u) => [u, i])));
|
|
1031
|
+
marks.sort((a, b) => (order.get(a.msgUuid) ?? 1e9) - (order.get(b.msgUuid) ?? 1e9));
|
|
1032
|
+
$('detailMarks').innerHTML = marks.length
|
|
1033
|
+
? `<span class="eyebrow">${ICON.bookmark}${marks.length}</span>` + marks.map((b) => `<button type="button" class="mark-chip" data-jump="${esc(b.msgUuid)}" title="${esc(stripMd(b.text))}${b.readOnly ? ` (bookmarked in ${esc(b.source)})` : ''}">${b.readOnly ? `<span class="chip-src">${esc(b.source)}</span>` : ''}${esc((b.note || stripMd(b.text) || 'Bookmarked message').slice(0, 48))}</button>`).join('')
|
|
1034
|
+
: '';
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
function bmItem(b, q) {
|
|
1038
|
+
const bmSrc = (sessionById(b.sessionId) || { source: 'claude' }).source;
|
|
1039
|
+
const user = b.role === 'user';
|
|
1040
|
+
return `<div class="bm-item" data-bmid="${esc(b.id)}">
|
|
1041
|
+
<div class="avatar sm ${user ? 'u' : 'a'}" aria-hidden="true">${user ? 'Y' : esc(assistantOf(bmSrc)[1])}</div>
|
|
1042
|
+
<div class="min0">
|
|
1043
|
+
<div class="bm-meta"><b>${user ? 'You' : esc(assistantOf(bmSrc)[0])}</b>${b.ts ? `<span>${timeOf(b.ts)}</span>` : ''}${b.readOnly ? `<span class="src-badge">${ICON.bookmark}${esc(b.source)}</span>` : ''}</div>
|
|
1044
|
+
<p class="bm-text">${b.text ? hl(stripMd(b.text).replace(/\s+/g, ' '), q) : '<span class="muted">This message is no longer in the session file.</span>'}</p>
|
|
1045
|
+
${b.readOnly
|
|
1046
|
+
? `<p class="src-note">Bookmarked in ${esc(b.source)}. To remove it, use the bookmark button under the reply there.</p>`
|
|
1047
|
+
: `<label class="bm-note inline"><span class="sr-only">Note</span><input type="text" data-bmnote="${esc(b.id)}" value="${esc(b.note || '')}" placeholder="Add a note…" maxlength="500"></label>`}
|
|
1048
|
+
</div>
|
|
1049
|
+
<div class="bm-actions">
|
|
1050
|
+
<button type="button" class="btn ghost sm" data-bmopen="${esc(b.id)}">Open${use('arrow')}</button>
|
|
1051
|
+
${b.readOnly ? '' : `<button type="button" class="btn ghost icon sm" data-bmdel="${esc(b.id)}" aria-label="Remove bookmark">${use('trash')}</button>`}
|
|
1052
|
+
</div>
|
|
1053
|
+
</div>`;
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
function chatItem(b, q) {
|
|
1057
|
+
const s = sessionById(b.sessionId);
|
|
1058
|
+
return `<div class="bm-item chat" data-bmid="${esc(b.id)}">
|
|
1059
|
+
<div class="avatar sm c" aria-hidden="true">${ICON.bookmark}</div>
|
|
1060
|
+
<div class="min0">
|
|
1061
|
+
<div class="bm-meta"><b>${hl(s ? s.title : b.title, q)}</b><span>${esc(base(s ? s.project.cwd : b.cwd))}${s ? ` · ${ago(s.mtime)} · ${plural(s.promptCount, 'prompt')}` : ' · session not found'}</span></div>
|
|
1062
|
+
${s && s.last ? `<p class="bm-text">${ICON.reply} ${esc(s.last)}</p>` : ''}
|
|
1063
|
+
<label class="bm-note inline"><span class="sr-only">Note</span><input type="text" data-bmnote="${esc(b.id)}" value="${esc(b.note || '')}" placeholder="Why is this chat worth keeping?" maxlength="500"></label>
|
|
1064
|
+
</div>
|
|
1065
|
+
<div class="bm-actions">
|
|
1066
|
+
${s ? `<button type="button" class="btn ghost sm" data-session="${esc(s.uid)}">Open${use('arrow')}</button>` : ''}
|
|
1067
|
+
<button type="button" class="btn ghost icon sm" data-bmdel="${esc(b.id)}" aria-label="Remove chat bookmark">${use('trash')}</button>
|
|
1068
|
+
</div>
|
|
1069
|
+
</div>`;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
function renderBookmarks() {
|
|
1073
|
+
const chats = [...state.chatMarks.values()].sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
1074
|
+
const allMsg = msgMarks();
|
|
1075
|
+
const n = allMsg.length + chats.length;
|
|
1076
|
+
$('navBookmarks').textContent = n ? n : '';
|
|
1077
|
+
// overview panel
|
|
1078
|
+
$('bmPanel').hidden = !n;
|
|
1079
|
+
$('bmRecent').innerHTML = allMsg.slice(0, 4).map((b) => `<button type="button" class="row" data-bmopen="${esc(b.id)}">
|
|
1080
|
+
<div class="row-title">${esc((b.note || stripMd(b.text)).slice(0, 90))}</div>
|
|
1081
|
+
<div class="row-meta"><span>${esc((b.title || (sessionById(b.sessionId) || {}).title || '').slice(0, 50))}</span>${b.readOnly ? `<span class="sep">·</span><span>${esc(b.source)}</span>` : ''}</div>
|
|
1082
|
+
</button>`).join('');
|
|
1083
|
+
// page
|
|
1084
|
+
const q = $('bmQ').value.trim().toLowerCase();
|
|
1085
|
+
const list = allMsg.filter((b) => { const x = sessionById(b.sessionId); return !q || [b.text, b.note, b.title || (x ? x.title : ''), b.cwd, b.source].join('\n').toLowerCase().includes(q); });
|
|
1086
|
+
const chatList = chats.filter((b) => { const s = sessionById(b.sessionId); return !q || [s ? s.title : b.title, b.note, b.cwd, s ? s.last : ''].join('\n').toLowerCase().includes(q); });
|
|
1087
|
+
$('bmTabs').innerHTML = [['all', 'All', chatList.length + list.length], ['chats', 'Chats', chatList.length], ['messages', 'Messages', list.length]]
|
|
1088
|
+
.map(([k, label, c]) => `<button type="button" data-bmtab="${k}" aria-pressed="${state.bmTab === k}">${label} <span>${c}</span></button>`).join('');
|
|
1089
|
+
$('bmCount').textContent = n ? `${plural(chats.length, 'chat')} and ${plural(allMsg.length, 'message')} saved${state.external.length ? ` (${state.external.length} from VS Code)` : ''}. Notes save when you leave the field.` : 'Chats and messages you saved, with your notes.';
|
|
1090
|
+
if (!n) {
|
|
1091
|
+
$('bmList').innerHTML = emptyState('No bookmarks yet', `Bookmark a whole chat with ${ICON.bookmark} at the top of a conversation (or press <kbd>b</kbd> on a row), or bookmark a single message by hovering over it.`, '<button type="button" class="btn ghost" data-view="sessions">Browse sessions</button>');
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
const showChats = state.bmTab !== 'messages';
|
|
1095
|
+
const showMsgs = state.bmTab !== 'chats';
|
|
1096
|
+
if ((!showChats || !chatList.length) && (!showMsgs || !list.length)) {
|
|
1097
|
+
$('bmList').innerHTML = emptyState(q ? `No bookmarks match “${q}”` : 'Nothing in this tab yet', q ? 'Search looks at chat titles, messages and your notes.' : (state.bmTab === 'chats' ? 'Open a chat and click the bookmark icon at the top.' : 'Hover over a message in a chat and click its bookmark icon.'));
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
const chatHtml = showChats && chatList.length ? `<section class="bm-group"><header class="bm-head"><div><p class="eyebrow">Chats · ${chatList.length}</p></div></header>${chatList.map((b) => chatItem(b, q)).join('')}</section>` : '';
|
|
1101
|
+
const msgHead = showMsgs && list.length && state.bmTab === 'all' ? `<p class="eyebrow bm-sep">Messages · ${list.length}</p>` : '';
|
|
1102
|
+
if (!showMsgs || !list.length) { $('bmList').innerHTML = chatHtml; return; }
|
|
1103
|
+
const groups = new Map();
|
|
1104
|
+
for (const b of list) { if (!groups.has(b.sessionId)) groups.set(b.sessionId, []); groups.get(b.sessionId).push(b); }
|
|
1105
|
+
$('bmList').innerHTML = chatHtml + msgHead + [...groups].map(([sid, items]) => {
|
|
1106
|
+
const s = sessionById(sid);
|
|
1107
|
+
const title = s ? s.title : items[0].title;
|
|
1108
|
+
const cwd = s ? s.project.cwd : items[0].cwd;
|
|
1109
|
+
return `<section class="bm-group">
|
|
1110
|
+
<header class="bm-head">
|
|
1111
|
+
<div class="min0"><h2>${state.chatMarks.has(sid) ? `<span class="pin-dot" title="Chat bookmarked">${ICON.bookmark}</span>` : ''}${hl(title, q)}</h2><p class="mono-s">${esc(short(cwd))}${s ? '' : ' · session not found'}</p></div>
|
|
1112
|
+
${s ? `<button type="button" class="link" data-session="${esc(s.uid)}">Open chat</button>` : ''}
|
|
1113
|
+
</header>
|
|
1114
|
+
${items.map((b) => bmItem(b, q)).join('')}
|
|
1115
|
+
</section>`;
|
|
1116
|
+
}).join('');
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
function openBookmark(id) {
|
|
1120
|
+
const b = msgMarks().find((x) => x.id === id);
|
|
1121
|
+
if (!b) return;
|
|
1122
|
+
const s = sessionById(b.sessionId);
|
|
1123
|
+
if (!s) { toast('That session no longer exists. You can remove the bookmark.'); return; }
|
|
1124
|
+
openDetail(s.uid, b.msgUuid);
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// ---------- mover ----------
|
|
1128
|
+
// groups: [{ key, ids|null }] (ids null = whole project, including memory)
|
|
1129
|
+
async function openMover(groups) {
|
|
1130
|
+
const projects = groups.map((g) => ({ ...g, p: state.projects.find((x) => x.key === g.key) })).filter((g) => g.p);
|
|
1131
|
+
if (!projects.length) return;
|
|
1132
|
+
const count = projects.reduce((n, g) => n + (g.ids ? g.ids.length : g.p.sessions.length), 0);
|
|
1133
|
+
state.mover = { groups: projects, count };
|
|
1134
|
+
const first = projects[0].p;
|
|
1135
|
+
$('moverTitle').textContent = `Move ${plural(count, 'session')}`;
|
|
1136
|
+
$('moverFrom').textContent = projects.length === 1 ? (short(first.cwd) || first.key) : `${projects.length} projects`;
|
|
1137
|
+
$('moverFromState').innerHTML = projects.length === 1 && first.missing ? '<span class="chip danger">folder missing</span>' : '';
|
|
1138
|
+
$('moverTo').value = '';
|
|
1139
|
+
$('moverError').textContent = '';
|
|
1140
|
+
$('suggestions').innerHTML = '<span class="sk" style="width:70%;height:44px"></span>';
|
|
1141
|
+
$('suggestBox').hidden = false;
|
|
1142
|
+
updatePreview();
|
|
1143
|
+
if ($('detail').open) $('detail').close();
|
|
1144
|
+
$('mover').showModal();
|
|
1145
|
+
browse(first.exists ? first.cwd : parentOf(first.cwd));
|
|
1146
|
+
try {
|
|
1147
|
+
const { suggestions } = await api(`/api/suggest?key=${encodeURIComponent(first.key)}`);
|
|
1148
|
+
$('suggestions').innerHTML = suggestions.length
|
|
1149
|
+
? suggestions.map((s) => `<button type="button" class="choice" data-pick="${esc(s.path)}" aria-pressed="false">${ICON.folder}<span>${esc(short(s.path))}</span></button>`).join('')
|
|
1150
|
+
: '<p class="muted small">No similar folder names found nearby. Type or browse to the folder below.</p>';
|
|
1151
|
+
stagger($('suggestions'));
|
|
1152
|
+
} catch {
|
|
1153
|
+
$('suggestBox').hidden = true;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
function parentOf(p) {
|
|
1158
|
+
if (!p) return state.home;
|
|
1159
|
+
const i = p.lastIndexOf('/');
|
|
1160
|
+
return i > 0 ? p.slice(0, i) : '/';
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
async function browse(path) {
|
|
1164
|
+
try {
|
|
1165
|
+
const d = await api(`/api/dirs?path=${encodeURIComponent(path || state.home)}`);
|
|
1166
|
+
$('browsePath').textContent = short(d.path);
|
|
1167
|
+
$('browseList').innerHTML =
|
|
1168
|
+
(d.parent ? `<button type="button" data-browse="${esc(d.parent)}">${use('up')}Up one level</button>` : '') +
|
|
1169
|
+
`<button type="button" class="use-here" data-pick="${esc(d.path)}">${use('check')}<b>Use this folder</b><span class="muted">${esc(short(d.path))}</span></button>` +
|
|
1170
|
+
d.dirs.map((n) => `<button type="button" data-browse="${esc((d.path === '/' ? '' : d.path) + '/' + n)}">${ICON.folder}${esc(n)}</button>`).join('');
|
|
1171
|
+
} catch (e) {
|
|
1172
|
+
$('browseList').innerHTML = `<p class="error small">${esc(e.message)}</p>`;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
function markPicked(path) {
|
|
1177
|
+
document.querySelectorAll('#suggestions .choice').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.pick === path)));
|
|
1178
|
+
}
|
|
1179
|
+
function pick(path) {
|
|
1180
|
+
$('moverTo').value = short(path);
|
|
1181
|
+
markPicked(path);
|
|
1182
|
+
updatePreview();
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
function updatePreview() {
|
|
1186
|
+
const m = state.mover;
|
|
1187
|
+
if (!m) return;
|
|
1188
|
+
const raw = $('moverTo').value.trim();
|
|
1189
|
+
const to = raw ? expand(raw) : '';
|
|
1190
|
+
$('moverError').textContent = '';
|
|
1191
|
+
if (!to) {
|
|
1192
|
+
$('moverPreview').innerHTML = '<span class="muted">Pick the folder these sessions belong to now.</span>';
|
|
1193
|
+
$('moverGo').disabled = true;
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
const key = encode(to);
|
|
1197
|
+
const target = state.projects.find((p) => p.key === key);
|
|
1198
|
+
const same = m.groups.filter((g) => g.key === key);
|
|
1199
|
+
const movable = m.count - same.reduce((n, g) => n + (g.ids ? g.ids.length : g.p.sessions.length), 0);
|
|
1200
|
+
if (!movable) {
|
|
1201
|
+
$('moverPreview').innerHTML = '<span class="muted">That is the folder they already belong to.</span>';
|
|
1202
|
+
$('moverGo').disabled = true;
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
const memory = m.groups.some((g) => !g.ids && g.p.memory);
|
|
1206
|
+
$('moverPreview').innerHTML = `Moves ${plural(movable, 'session')}${memory ? ' and project memory' : ''} to <code>${esc(short(state.root))}/${esc(key)}</code>.
|
|
1207
|
+
${same.length ? ` ${plural(m.count - movable, 'session')} already there will be left alone.` : ''}
|
|
1208
|
+
${target && target.sessions.length ? ` Merges with the ${plural(target.sessions.length, 'session')} already there.` : ''}
|
|
1209
|
+
A backup is saved first.`;
|
|
1210
|
+
$('moverGo').disabled = false;
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
async function doMove(e) {
|
|
1214
|
+
e.preventDefault();
|
|
1215
|
+
const m = state.mover;
|
|
1216
|
+
const to = expand($('moverTo').value.trim());
|
|
1217
|
+
const key = encode(to);
|
|
1218
|
+
$('moverGo').disabled = true;
|
|
1219
|
+
$('moverGo').textContent = 'Moving…';
|
|
1220
|
+
let moved = 0;
|
|
1221
|
+
let skipped = 0;
|
|
1222
|
+
try {
|
|
1223
|
+
for (const g of m.groups) {
|
|
1224
|
+
if (g.key === key) continue;
|
|
1225
|
+
const r = await api('/api/move', { key: g.key, to, ids: g.ids || undefined });
|
|
1226
|
+
moved += r.moved;
|
|
1227
|
+
skipped += r.skipped.length;
|
|
1228
|
+
}
|
|
1229
|
+
$('mover').close();
|
|
1230
|
+
state.selected.clear();
|
|
1231
|
+
toast(`Moved ${plural(moved, 'session')} to ${short(to)}.${skipped ? ` Skipped ${skipped} that already existed.` : ''}`);
|
|
1232
|
+
} catch (err) {
|
|
1233
|
+
$('moverError').textContent = moved ? `Moved ${moved}, then stopped: ${err.message}` : err.message;
|
|
1234
|
+
} finally {
|
|
1235
|
+
$('moverGo').textContent = 'Move sessions';
|
|
1236
|
+
$('moverGo').disabled = false;
|
|
1237
|
+
if (moved) await load();
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
function bulkGroups() {
|
|
1242
|
+
const by = new Map();
|
|
1243
|
+
for (const s of state.sessions) {
|
|
1244
|
+
if (!state.selected.has(s.uid)) continue;
|
|
1245
|
+
if (!by.has(s.project.key)) by.set(s.project.key, []);
|
|
1246
|
+
by.get(s.project.key).push(s.id);
|
|
1247
|
+
}
|
|
1248
|
+
return [...by].map(([key, ids]) => ({ key, ids }));
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// ---------- command palette ----------
|
|
1252
|
+
const pal = { items: [], active: 0 };
|
|
1253
|
+
function paletteItems(q) {
|
|
1254
|
+
const ql = q.trim().toLowerCase();
|
|
1255
|
+
const actions = [
|
|
1256
|
+
{ group: 'Go to', label: 'Overview', hint: 'g o', run: () => setView('overview'), icon: 'grid' },
|
|
1257
|
+
{ group: 'Go to', label: 'Sessions', hint: 'g s', run: () => setView('sessions'), icon: 'chat' },
|
|
1258
|
+
{ group: 'Go to', label: 'Bookmarks', hint: 'g m', run: () => setView('bookmarks'), icon: 'bookmark' },
|
|
1259
|
+
{ group: 'Go to', label: 'Projects', hint: 'g p', run: () => setView('projects'), icon: 'folder' },
|
|
1260
|
+
{ group: 'Go to', label: 'Backups', hint: 'g b', run: () => setView('backups'), icon: 'archive' },
|
|
1261
|
+
{ group: 'Actions', label: 'Tools & import', run: () => openSources(), icon: 'plug' },
|
|
1262
|
+
{ group: 'Chatshelf', label: 'Star Chatshelf on GitHub', run: () => window.open(REPO_URL, '_blank', 'noopener,noreferrer'), icon: 'star' },
|
|
1263
|
+
{ group: 'Chatshelf', label: 'Report a bug or suggest a feature', run: () => window.open(`${REPO_URL}/issues/new/choose`, '_blank', 'noopener,noreferrer'), icon: 'chat' },
|
|
1264
|
+
{ group: 'Chatshelf', label: 'Contribute: add support for another tool', run: () => window.open(`${REPO_URL}/blob/main/CONTRIBUTING.md`, '_blank', 'noopener,noreferrer'), icon: 'plug' },
|
|
1265
|
+
{ group: 'Actions', label: 'Import a ChatGPT or claude.ai export', run: () => openSources(), icon: 'upload' },
|
|
1266
|
+
{ group: 'Actions', label: 'Find missing folders', run: () => { state.projTab = 'missing'; renderProjects(); setView('projects'); }, icon: 'search' },
|
|
1267
|
+
{ group: 'Actions', label: 'Light theme', run: () => applyTheme('light'), icon: 'sun' },
|
|
1268
|
+
{ group: 'Actions', label: 'Dark theme', run: () => applyTheme('dark'), icon: 'moon' },
|
|
1269
|
+
{ group: 'Actions', label: 'Theme: follow system', run: () => applyTheme('system'), icon: 'monitor' },
|
|
1270
|
+
{ group: 'Actions', label: 'Keyboard shortcuts', hint: '?', run: () => $('shortcuts').showModal(), icon: 'key' },
|
|
1271
|
+
];
|
|
1272
|
+
const sessions = (ql ? state.sessions.filter((s) => s.hay.includes(ql)) : [...pinnedSessions(), ...state.sessions.filter((s) => !state.pins.has(s.uid) && s.promptCount)])
|
|
1273
|
+
.slice(0, ql ? 8 : 6)
|
|
1274
|
+
.map((s) => ({ group: ql ? 'Sessions' : 'Recent', label: s.title, sub: `${toolLabel(s.source)} · ${projName(s.project)} · ${ago(s.mtime)}`, run: () => openDetail(s.uid), icon: state.pins.has(s.uid) ? 'bookmark' : 'chat' }));
|
|
1275
|
+
const projects = ql ? state.projects.filter((p) => (p.cwd || p.key).toLowerCase().includes(ql)).slice(0, 4)
|
|
1276
|
+
.map((p) => ({ group: 'Projects', label: projName(p), sub: `${toolLabel(p.source)} · ${short(p.cwd)}`, run: () => { $('proj').value = p.key; searchFor(''); }, icon: 'folder' })) : [];
|
|
1277
|
+
const chatMarksHit = ql ? [...state.chatMarks.values()].filter((b) => [b.note, b.title].join('\n').toLowerCase().includes(ql)).slice(0, 3)
|
|
1278
|
+
.map((b) => ({ group: 'Bookmarks', label: b.note || b.title, sub: b.note ? `Chat: ${b.title}` : 'Bookmarked chat', run: () => { const x = sessionById(b.sessionId); if (x) openDetail(x.uid); }, icon: 'bookmark' })) : [];
|
|
1279
|
+
const marks = ql ? msgMarks().filter((b) => [b.text, b.note, b.title].join('\n').toLowerCase().includes(ql)).slice(0, 5)
|
|
1280
|
+
.map((b) => ({ group: 'Bookmarks', label: b.note || stripMd(b.text) || 'Bookmarked message', sub: [b.title || (sessionById(b.sessionId) || {}).title, b.readOnly ? b.source : ''].filter(Boolean).join(' · '), run: () => openBookmark(b.id), icon: 'bookmark' })) : [];
|
|
1281
|
+
const acts = actions.filter((a) => !ql || a.label.toLowerCase().includes(ql));
|
|
1282
|
+
return [...sessions, ...chatMarksHit, ...marks, ...projects, ...acts];
|
|
1283
|
+
}
|
|
1284
|
+
function renderPalette() {
|
|
1285
|
+
const q = $('palQ').value;
|
|
1286
|
+
pal.items = paletteItems(q);
|
|
1287
|
+
pal.active = Math.min(pal.active, Math.max(0, pal.items.length - 1));
|
|
1288
|
+
let group = '';
|
|
1289
|
+
$('palList').innerHTML = pal.items.map((it, i) => {
|
|
1290
|
+
const head = it.group !== group ? `<div class="pal-group" role="presentation">${esc((group = it.group))}</div>` : '';
|
|
1291
|
+
return `${head}<div class="pal-item" role="option" id="pal-${i}" data-pal="${i}" aria-selected="${i === pal.active}">
|
|
1292
|
+
${use(it.icon)}<span class="pal-label"><span class="pal-main">${hl(it.label, q.trim().toLowerCase())}</span>${it.sub ? `<span class="pal-sub">${esc(it.sub)}</span>` : ''}</span>${it.hint ? `<kbd>${esc(it.hint)}</kbd>` : ''}</div>`;
|
|
1293
|
+
}).join('') || `<div class="pal-empty muted">No matches for “${esc(q)}”. Try a folder name or a word from a prompt.</div>`;
|
|
1294
|
+
$('palQ').setAttribute('aria-activedescendant', pal.items.length ? `pal-${pal.active}` : '');
|
|
1295
|
+
}
|
|
1296
|
+
function openPalette() {
|
|
1297
|
+
if ($('palette').open) return;
|
|
1298
|
+
document.querySelectorAll('dialog[open]').forEach((d) => d.close());
|
|
1299
|
+
$('palQ').value = '';
|
|
1300
|
+
pal.active = 0;
|
|
1301
|
+
renderPalette();
|
|
1302
|
+
$('palette').showModal();
|
|
1303
|
+
$('palQ').focus();
|
|
1304
|
+
stagger($('palList'), '.pal-item', 10);
|
|
1305
|
+
}
|
|
1306
|
+
function runPalette(i) {
|
|
1307
|
+
const it = pal.items[i];
|
|
1308
|
+
if (!it) return;
|
|
1309
|
+
$('palette').close();
|
|
1310
|
+
it.run();
|
|
1311
|
+
}
|
|
1312
|
+
function movePalette(d) {
|
|
1313
|
+
if (!pal.items.length) return;
|
|
1314
|
+
pal.active = (pal.active + d + pal.items.length) % pal.items.length;
|
|
1315
|
+
$('palList').querySelectorAll('.pal-item').forEach((el) => el.setAttribute('aria-selected', String(Number(el.dataset.pal) === pal.active)));
|
|
1316
|
+
$('palQ').setAttribute('aria-activedescendant', `pal-${pal.active}`);
|
|
1317
|
+
$(`pal-${pal.active}`).scrollIntoView({ block: 'nearest' });
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// ---------- theme ----------
|
|
1321
|
+
const darkQuery = matchMedia('(prefers-color-scheme: dark)');
|
|
1322
|
+
function applyTheme(pref, animate = true) {
|
|
1323
|
+
localStorage.setItem('csm-theme', pref);
|
|
1324
|
+
const dark = pref === 'dark' || (pref === 'system' && darkQuery.matches);
|
|
1325
|
+
const set = () => {
|
|
1326
|
+
root.dataset.theme = dark ? 'dark' : 'light';
|
|
1327
|
+
document.querySelectorAll('[data-theme-set]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.themeSet === pref)));
|
|
1328
|
+
};
|
|
1329
|
+
if (animate && motionOn() && document.startViewTransition && root.dataset.theme !== (dark ? 'dark' : 'light')) document.startViewTransition(set);
|
|
1330
|
+
else set();
|
|
1331
|
+
}
|
|
1332
|
+
darkQuery.addEventListener('change', () => { if ((localStorage.getItem('csm-theme') || 'system') === 'system') applyTheme('system'); });
|
|
1333
|
+
|
|
1334
|
+
// ---------- navigation ----------
|
|
1335
|
+
const VIEWS = ['overview', 'sessions', 'bookmarks', 'projects', 'backups'];
|
|
1336
|
+
function setView(view) {
|
|
1337
|
+
const changed = state.view !== view;
|
|
1338
|
+
state.view = view;
|
|
1339
|
+
for (const v of VIEWS) $(`view-${v}`).hidden = v !== view;
|
|
1340
|
+
document.querySelectorAll('.nav-item').forEach((t) => (t.dataset.view === view ? t.setAttribute('aria-current', 'page') : t.removeAttribute('aria-current')));
|
|
1341
|
+
renderBulk();
|
|
1342
|
+
if (view === 'backups') renderBackups();
|
|
1343
|
+
if (!$('detail').open && !deepLink && location.hash !== `#${view}`) history.replaceState(null, '', `#${view}`);
|
|
1344
|
+
window.scrollTo(0, 0);
|
|
1345
|
+
if (changed || !state.loaded) animateView(view);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
function searchFor(text) {
|
|
1349
|
+
$('q').value = text;
|
|
1350
|
+
state.shown = PAGE;
|
|
1351
|
+
state.sessTab = 'all';
|
|
1352
|
+
renderSessions();
|
|
1353
|
+
if (state.view !== 'sessions') setView('sessions');
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
function listButtons() {
|
|
1357
|
+
const scope = state.view === 'sessions' ? $('list') : state.view === 'overview' ? $('view-overview') : null;
|
|
1358
|
+
return scope ? [...scope.querySelectorAll('.row-open, button.row[data-session]')] : [];
|
|
1359
|
+
}
|
|
1360
|
+
function moveFocus(d) {
|
|
1361
|
+
const items = listButtons();
|
|
1362
|
+
if (!items.length) return;
|
|
1363
|
+
const i = items.indexOf(document.activeElement);
|
|
1364
|
+
const next = items[i < 0 ? (d > 0 ? 0 : items.length - 1) : Math.max(0, Math.min(items.length - 1, i + d))];
|
|
1365
|
+
next.focus({ preventScroll: true });
|
|
1366
|
+
next.scrollIntoView({ block: 'nearest', behavior: motionOn() ? 'smooth' : 'auto' });
|
|
1367
|
+
}
|
|
1368
|
+
const focusedUid = () => { const el = document.activeElement; return el && el.dataset ? el.dataset.session : undefined; };
|
|
1369
|
+
|
|
1370
|
+
// ---------- events ----------
|
|
1371
|
+
document.addEventListener('click', async (e) => {
|
|
1372
|
+
const pi = e.target.closest('[data-pal]');
|
|
1373
|
+
if (pi) { runPalette(Number(pi.dataset.pal)); return; }
|
|
1374
|
+
const t = e.target.closest('button');
|
|
1375
|
+
if (!t) return;
|
|
1376
|
+
const d = t.dataset;
|
|
1377
|
+
if (d.themeSet) applyTheme(d.themeSet);
|
|
1378
|
+
else if ('palette' in d) openPalette();
|
|
1379
|
+
else if ('shortcuts' in d) $('shortcuts').showModal();
|
|
1380
|
+
else if ('sources' in d) openSources();
|
|
1381
|
+
else if (d.src !== undefined) { state.src = d.src; state.shown = PAGE; renderTools(); renderSessions(); stagger($('list'), ':scope > .row, :scope > .date-head', 12); if (state.view !== 'sessions') setView('sessions'); }
|
|
1382
|
+
else if (d.rmimport) removeImport(d.rmimport);
|
|
1383
|
+
else if ('reload' in d) { skeletons(); load(); }
|
|
1384
|
+
else if ('clearFilters' in d) { $('q').value = ''; $('proj').value = ''; state.sessTab = 'all'; state.src = ''; renderTools(); setDateFilter(''); }
|
|
1385
|
+
else if ('dateClear' in d) setDateFilter('');
|
|
1386
|
+
else if ('copycode' in d) copy(t.closest('.code').querySelector('code').textContent, t);
|
|
1387
|
+
else if (d.copymsg) copy(state.msgs[Number(d.copymsg)].text, t);
|
|
1388
|
+
else if ('more' in d) expandClamp(t.parentElement.querySelector('.clamp'));
|
|
1389
|
+
else if (d.who) { setWho(d.who); findInConvo($('find').value.trim()); }
|
|
1390
|
+
else if (d.pin) togglePin(d.pin);
|
|
1391
|
+
else if (d.bm) toggleBookmark(Number(d.bm));
|
|
1392
|
+
else if (d.bmopen) openBookmark(d.bmopen);
|
|
1393
|
+
else if (d.bmdel) removeBookmark(d.bmdel);
|
|
1394
|
+
else if (d.jump) scrollToMsg(d.jump);
|
|
1395
|
+
else if (d.bmtab) { state.bmTab = d.bmtab; renderBookmarks(); stagger($('bmList'), ':scope > *', 10); }
|
|
1396
|
+
else if (d.view) setView(d.view);
|
|
1397
|
+
else if (d.session) openDetail(d.session);
|
|
1398
|
+
else if (d.show) { $('proj').value = d.show; $('q').value = ''; state.sessTab = 'all'; state.shown = PAGE; renderSessions(); setView('sessions'); }
|
|
1399
|
+
else if (d.move) openMover([{ key: d.move, ids: null }]);
|
|
1400
|
+
else if (d.pick) pick(d.pick);
|
|
1401
|
+
else if (d.browse) browse(d.browse);
|
|
1402
|
+
else if (d.sesstab) { state.sessTab = d.sesstab; state.shown = PAGE; renderSessions(); stagger($('list'), ':scope > .row, :scope > .date-head', 12); }
|
|
1403
|
+
else if (d.projtab) { state.projTab = d.projtab; renderProjects(); stagger($('projects'), ':scope > .tr, :scope > .group-head', 12); }
|
|
1404
|
+
else if (d.sort) {
|
|
1405
|
+
state.sort = d.sort;
|
|
1406
|
+
document.querySelectorAll('[data-sort]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.sort === d.sort)));
|
|
1407
|
+
renderSessions();
|
|
1408
|
+
stagger($('list'), ':scope > .row, :scope > .date-head', 12);
|
|
1409
|
+
} else if ('close' in d) t.closest('dialog').close();
|
|
1410
|
+
else if (d.restore) {
|
|
1411
|
+
t.disabled = true;
|
|
1412
|
+
try {
|
|
1413
|
+
const r = await api('/api/restore', { name: d.restore });
|
|
1414
|
+
toast(`Restored ${plural(r.restored, 'session')}.${r.skipped.length ? ` ${r.skipped.length} were already there.` : ''}`);
|
|
1415
|
+
await load();
|
|
1416
|
+
} catch (err) { toast(err.message); } finally { t.disabled = false; }
|
|
1417
|
+
}
|
|
1418
|
+
});
|
|
1419
|
+
|
|
1420
|
+
document.addEventListener('change', (e) => {
|
|
1421
|
+
const uid = e.target.dataset && e.target.dataset.select;
|
|
1422
|
+
if (!uid) return;
|
|
1423
|
+
if (e.target.checked) state.selected.add(uid); else state.selected.delete(uid);
|
|
1424
|
+
e.target.closest('.row').classList.toggle('is-selected', e.target.checked);
|
|
1425
|
+
renderBulk();
|
|
1426
|
+
const { rows } = filteredSessions();
|
|
1427
|
+
const visible = rows.slice(0, state.shown);
|
|
1428
|
+
$('selectAll').checked = visible.length > 0 && visible.every((s) => state.selected.has(s.uid));
|
|
1429
|
+
$('selectAll').indeterminate = !$('selectAll').checked && visible.some((s) => state.selected.has(s.uid));
|
|
1430
|
+
});
|
|
1431
|
+
$('selectAll').addEventListener('change', (e) => {
|
|
1432
|
+
const { rows } = filteredSessions();
|
|
1433
|
+
for (const s of rows.slice(0, state.shown)) { if (e.target.checked) state.selected.add(s.uid); else state.selected.delete(s.uid); }
|
|
1434
|
+
renderSessions();
|
|
1435
|
+
renderBulk();
|
|
1436
|
+
});
|
|
1437
|
+
document.addEventListener('change', (e) => { if (e.target.dataset && e.target.dataset.bmnote) saveNote(e.target); });
|
|
1438
|
+
document.addEventListener('keydown', (e) => { if (e.key === 'Enter' && e.target.dataset && e.target.dataset.bmnote) { e.preventDefault(); e.target.blur(); } }, true);
|
|
1439
|
+
$('bmQ').addEventListener('input', () => renderBookmarks());
|
|
1440
|
+
$('importFile').addEventListener('change', (e) => uploadExport(e.target.files[0]));
|
|
1441
|
+
['dragenter', 'dragover'].forEach((ev) => $('drop').addEventListener(ev, (e) => { e.preventDefault(); $('drop').classList.add('over'); }));
|
|
1442
|
+
['dragleave', 'drop'].forEach((ev) => $('drop').addEventListener(ev, (e) => { e.preventDefault(); $('drop').classList.remove('over'); }));
|
|
1443
|
+
$('drop').addEventListener('drop', (e) => uploadExport(e.dataTransfer.files[0]));
|
|
1444
|
+
$('dateRange').addEventListener('change', () => {
|
|
1445
|
+
const v = $('dateRange').value;
|
|
1446
|
+
if (v === 'custom' && !$('dateFrom').value && !$('dateTo').value) { $('dateFrom').value = ymd(Date.now() - 6 * DAY); $('dateTo').value = ymd(Date.now()); }
|
|
1447
|
+
$('dateCustom').hidden = v !== 'custom';
|
|
1448
|
+
state.shown = PAGE;
|
|
1449
|
+
renderSessions();
|
|
1450
|
+
stagger($('list'), ':scope > .row, :scope > .date-head', 12);
|
|
1451
|
+
if (v === 'custom') $('dateFrom').focus();
|
|
1452
|
+
});
|
|
1453
|
+
['dateFrom', 'dateTo'].forEach((id) => $(id).addEventListener('change', () => { state.shown = PAGE; renderSessions(); }));
|
|
1454
|
+
$('heat').addEventListener('click', (e) => {
|
|
1455
|
+
const cell = e.target.closest('i[data-day]');
|
|
1456
|
+
if (!cell) return;
|
|
1457
|
+
state.src = '';
|
|
1458
|
+
state.sessTab = 'all';
|
|
1459
|
+
$('q').value = '';
|
|
1460
|
+
$('proj').value = '';
|
|
1461
|
+
renderTools();
|
|
1462
|
+
setDateFilter('custom', cell.dataset.day, cell.dataset.day);
|
|
1463
|
+
setView('sessions');
|
|
1464
|
+
toast(`Showing chats from ${dateLabel()}`);
|
|
1465
|
+
});
|
|
1466
|
+
$('showEmpty').addEventListener('change', () => { state.shown = PAGE; renderSessions(); });
|
|
1467
|
+
$('bulkClear').addEventListener('click', () => { state.selected.clear(); renderSessions(); renderBulk(); });
|
|
1468
|
+
$('bulkGo').addEventListener('click', () => openMover(bulkGroups()));
|
|
1469
|
+
|
|
1470
|
+
$('detailCopy').addEventListener('click', (e) => copy($('detailCmd').textContent, e.currentTarget));
|
|
1471
|
+
$('detailOpen').addEventListener('click', openTerminal);
|
|
1472
|
+
$('detailPin').addEventListener('click', () => state.detail && togglePin(state.detail.uid));
|
|
1473
|
+
$('detailMove').addEventListener('click', () => state.detail && openMover([{ key: state.detail.project.key, ids: [state.detail.id] }]));
|
|
1474
|
+
$('detail').addEventListener('close', () => { state.detail = null; history.replaceState(null, '', `#${state.view}`); });
|
|
1475
|
+
let findTimer;
|
|
1476
|
+
$('find').addEventListener('input', (e) => { clearTimeout(findTimer); findTimer = setTimeout(() => findInConvo(e.target.value.trim()), 200); });
|
|
1477
|
+
$('find').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); focusHit(state.hitIdx + (e.shiftKey ? -1 : 1)); } });
|
|
1478
|
+
$('jumpEnd').addEventListener('click', () => { const t = $('transcript'); t.scrollTo({ top: t.scrollHeight, behavior: motionOn() ? 'smooth' : 'auto' }); });
|
|
1479
|
+
|
|
1480
|
+
$('moverTo').addEventListener('input', () => { markPicked(expand($('moverTo').value.trim())); updatePreview(); });
|
|
1481
|
+
$('moverTo').addEventListener('change', () => { const v = expand($('moverTo').value.trim()); if (v) browse(v); });
|
|
1482
|
+
$('moverForm').addEventListener('submit', doMove);
|
|
1483
|
+
$('more').addEventListener('click', () => { state.shown += PAGE; renderSessions(); });
|
|
1484
|
+
$('q').addEventListener('input', () => { state.shown = PAGE; renderSessions(); });
|
|
1485
|
+
$('proj').addEventListener('input', () => { state.shown = PAGE; renderSessions(); stagger($('list'), ':scope > .row, :scope > .date-head', 12); });
|
|
1486
|
+
$('ask').addEventListener('keydown', (e) => { if (e.key === 'Enter') { searchFor(e.target.value); $('q').focus(); } });
|
|
1487
|
+
|
|
1488
|
+
$('palQ').addEventListener('input', () => { pal.active = 0; renderPalette(); });
|
|
1489
|
+
$('palQ').addEventListener('keydown', (e) => {
|
|
1490
|
+
if (e.key === 'ArrowDown') { e.preventDefault(); movePalette(1); }
|
|
1491
|
+
else if (e.key === 'ArrowUp') { e.preventDefault(); movePalette(-1); }
|
|
1492
|
+
else if (e.key === 'Enter') { e.preventDefault(); runPalette(pal.active); }
|
|
1493
|
+
});
|
|
1494
|
+
// Clicking the backdrop closes a dialog.
|
|
1495
|
+
document.querySelectorAll('dialog').forEach((dlg) => dlg.addEventListener('click', (e) => { if (e.target === dlg) dlg.close(); }));
|
|
1496
|
+
|
|
1497
|
+
let gPending = 0;
|
|
1498
|
+
document.addEventListener('keydown', (e) => {
|
|
1499
|
+
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openPalette(); return; }
|
|
1500
|
+
const el = document.activeElement;
|
|
1501
|
+
const typing = /INPUT|TEXTAREA|SELECT/.test(el.tagName) && el.type !== 'checkbox';
|
|
1502
|
+
if (typing || e.ctrlKey || e.metaKey || e.altKey) return;
|
|
1503
|
+
if (document.querySelector('dialog[open]')) return;
|
|
1504
|
+
if (gPending && Date.now() - gPending < 1200) {
|
|
1505
|
+
const map = { o: 'overview', s: 'sessions', m: 'bookmarks', p: 'projects', b: 'backups' };
|
|
1506
|
+
gPending = 0;
|
|
1507
|
+
if (map[e.key]) { e.preventDefault(); setView(map[e.key]); }
|
|
1508
|
+
return;
|
|
1509
|
+
}
|
|
1510
|
+
const inList = listButtons().includes(el);
|
|
1511
|
+
if (e.key === 'g') { gPending = Date.now(); }
|
|
1512
|
+
else if (e.key === '/') {
|
|
1513
|
+
e.preventDefault();
|
|
1514
|
+
if (state.view === 'overview') $('ask').focus();
|
|
1515
|
+
else { if (state.view !== 'sessions') setView('sessions'); $('q').focus(); }
|
|
1516
|
+
} else if (e.key === '?') { e.preventDefault(); $('shortcuts').showModal(); }
|
|
1517
|
+
else if (e.key === 'j' || (e.key === 'ArrowDown' && inList)) { e.preventDefault(); moveFocus(1); }
|
|
1518
|
+
else if (e.key === 'k' || (e.key === 'ArrowUp' && inList)) { e.preventDefault(); moveFocus(-1); }
|
|
1519
|
+
else if (e.key === 'x' && focusedUid()) {
|
|
1520
|
+
const box = document.querySelector(`[data-select="${CSS.escape(focusedUid())}"]`);
|
|
1521
|
+
if (box) { box.checked = !box.checked; box.dispatchEvent(new Event('change', { bubbles: true })); }
|
|
1522
|
+
} else if ((e.key === 'b' || e.key === 'p') && focusedUid()) {
|
|
1523
|
+
const uid = focusedUid();
|
|
1524
|
+
togglePin(uid).then(() => {
|
|
1525
|
+
const again = document.querySelector(`#view-${state.view} [data-session="${CSS.escape(uid)}"]`);
|
|
1526
|
+
if (again) again.focus({ preventScroll: true });
|
|
1527
|
+
});
|
|
1528
|
+
} else if (e.key === 'Escape' && state.selected.size) { state.selected.clear(); renderSessions(); renderBulk(); }
|
|
1529
|
+
});
|
|
1530
|
+
|
|
1531
|
+
// ---------- start ----------
|
|
1532
|
+
applyTheme(localStorage.getItem('csm-theme') || 'system', false);
|
|
1533
|
+
skeletons();
|
|
1534
|
+
loadStars();
|
|
1535
|
+
setView(VIEWS.includes(location.hash.slice(1)) ? location.hash.slice(1) : deepLink ? 'sessions' : 'overview');
|
|
1536
|
+
load();
|