csm-cli 0.1.0__py3-none-any.whl

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.
csm_cli/web.html ADDED
@@ -0,0 +1,955 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>csm · Claude 会话管理器</title>
7
+ <style>
8
+ /* =========================================================================
9
+ * 配色(学习模式协作点:这是你天天看的界面,颜色偏好由你定)
10
+ * 当前为占位值——改下面两块变量即可全局换肤,不影响任何布局逻辑。
11
+ * 可用值:颜色名 / #hex / rgb() / oklch() 都行
12
+ * ========================================================================= */
13
+ :root {
14
+ --bg: #ffffff; /* 页面背景 */
15
+ --fg: #1a1a1a; /* 主文字 */
16
+ --accent: #0969da; /* 强调色(选中边框/链接/徽章) */
17
+ --dim: #6e7781; /* 次要文字 */
18
+ --border: #d0d7de; /* 分隔线 */
19
+ --user: #1a7f37; /* 用户输入行的强调 */
20
+ --tool: #8250df; /* 工具调用行的标记 */
21
+ --error: #cf222e; /* 错误 */
22
+ --waiting: #9a6700; /* waiting 状态 */
23
+ }
24
+ @media (prefers-color-scheme: dark) {
25
+ :root {
26
+ /* TODO(user): 深色模式配色——把下面占位值换成你喜欢的深色方案 */
27
+ --bg: #0d1117;
28
+ --fg: #e6edf3;
29
+ --accent: #4493f8;
30
+ --dim: #8b949e;
31
+ --border: #30363d;
32
+ --user: #3fb950;
33
+ --tool: #d2a8ff;
34
+ --error: #f85149;
35
+ --waiting: #e3b341;
36
+ }
37
+ }
38
+
39
+ * { box-sizing: border-box; }
40
+ html, body { height: 100%; }
41
+ body {
42
+ margin: 0; background: var(--bg); color: var(--fg);
43
+ font: 14px/1.5 -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
44
+ display: flex; flex-direction: column;
45
+ }
46
+ header {
47
+ padding: 8px 14px; border-bottom: 1px solid var(--border);
48
+ display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap;
49
+ }
50
+ header h1 { font-size: 15px; margin: 0; }
51
+ header .stats { color: var(--dim); font-size: 12px; }
52
+ header .refreshed { color: var(--dim); font-size: 12px; margin-left: auto; }
53
+
54
+ .layout { flex: 1; display: grid; grid-template-columns: 45% 55%; min-height: 0; }
55
+
56
+ /* ---- 列表栏 ---- */
57
+ #list-pane { border-right: 1px solid var(--border); display: flex; flex-direction: column; min-height: 0; }
58
+ #search {
59
+ margin: 8px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px;
60
+ background: var(--bg); color: var(--fg); font-size: 13px; outline: none;
61
+ }
62
+ #search:focus { border-color: var(--accent); }
63
+ #chips { display: flex; gap: 6px; padding: 0 8px 8px; flex-wrap: wrap; }
64
+ .chip {
65
+ font-size: 12px; padding: 2px 10px; border-radius: 12px; cursor: pointer;
66
+ border: 1px solid var(--border); background: var(--bg); color: var(--dim);
67
+ }
68
+ .chip.on { border-color: var(--accent); color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, transparent); }
69
+ #rows { flex: 1; overflow-y: auto; padding: 0 8px 8px; }
70
+ .row {
71
+ padding: 7px 8px; border-radius: 6px; cursor: pointer;
72
+ border: 1px solid transparent; margin-bottom: 4px;
73
+ }
74
+ .row:hover { background: color-mix(in srgb, var(--accent) 7%, transparent); }
75
+ .row.selected { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 10%, transparent); }
76
+ .row.pinned { background: color-mix(in srgb, var(--accent) 4%, transparent); }
77
+ .row .l1 { display: flex; align-items: center; gap: 6px; }
78
+ .row .title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
79
+ .row .title.fallback { font-weight: 400; color: var(--dim); }
80
+ .row .badge-new {
81
+ font-size: 10px; padding: 0 5px; border-radius: 8px; flex: none;
82
+ background: var(--accent); color: var(--bg);
83
+ }
84
+ .row .badge-cur {
85
+ font-size: 10px; padding: 0 5px; border-radius: 8px; flex: none;
86
+ border: 1px solid var(--accent); color: var(--accent);
87
+ }
88
+ .row .badge-sdk {
89
+ font-size: 10px; padding: 0 5px; border-radius: 8px; flex: none;
90
+ border: 1px solid var(--border); color: var(--dim);
91
+ }
92
+ .row .star {
93
+ flex: none; cursor: pointer; background: none; border: none; padding: 0 2px;
94
+ font-size: 14px; line-height: 1; color: var(--dim);
95
+ }
96
+ .row .star.s1 { color: var(--waiting); }
97
+ .row .star.s2 { color: var(--accent); }
98
+ .row .copy {
99
+ flex: none; font-size: 11px; padding: 2px 8px; border-radius: 5px; cursor: pointer;
100
+ border: 1px solid var(--border); background: var(--bg); color: var(--dim);
101
+ }
102
+ .row .copy:hover { border-color: var(--accent); color: var(--accent); }
103
+ .row .copy.ok { border-color: var(--user); color: var(--user); }
104
+ .row .l2 { color: var(--dim); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; }
105
+ .row .tagchip { cursor: pointer; }
106
+ .row .tagchip:hover { color: var(--accent); text-decoration: underline; }
107
+ .dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--border); }
108
+ .dot.busy { background: var(--user); }
109
+ .dot.idle { background: var(--tool); }
110
+ .dot.waiting { background: var(--waiting); }
111
+ .dot.busy.pulse, .dot.idle.pulse { animation: pulse 2s infinite; }
112
+ @keyframes pulse { 50% { opacity: 0.35; } }
113
+ .empty { color: var(--dim); text-align: center; padding: 40px 0; }
114
+
115
+ /* ---- 详情栏 ---- */
116
+ #detail-pane { display: flex; flex-direction: column; min-height: 0; }
117
+ #detail-head { padding: 10px 14px; border-bottom: 1px solid var(--border); }
118
+ #detail-head .t { font-weight: 700; font-size: 15px; }
119
+ #detail-head .meta { color: var(--dim); font-size: 12px; margin-top: 3px; word-break: break-all; }
120
+ #detail-head .actions { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }
121
+ #detail-head button {
122
+ font-size: 12px; padding: 4px 10px; border-radius: 6px; cursor: pointer;
123
+ border: 1px solid var(--border); background: var(--bg); color: var(--fg);
124
+ }
125
+ #d-tags { margin-top: 6px; display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
126
+ #d-tags .tag {
127
+ font-size: 11.5px; padding: 1px 8px; border-radius: 10px; cursor: default;
128
+ border: 1px solid var(--border); color: var(--accent);
129
+ }
130
+ #d-tags .tag .x { cursor: pointer; color: var(--dim); margin-left: 4px; }
131
+ #d-tags .tag .x:hover { color: var(--error); }
132
+ #d-tags button {
133
+ font-size: 11.5px; padding: 1px 8px; border-radius: 10px; cursor: pointer;
134
+ border: 1px dashed var(--border); background: none; color: var(--dim);
135
+ }
136
+ #d-tags input {
137
+ font-size: 12px; width: 110px; padding: 2px 8px; border-radius: 10px;
138
+ border: 1px solid var(--accent); background: var(--bg); color: var(--fg); outline: none;
139
+ }
140
+ #detail-head button.primary { background: var(--accent); border-color: var(--accent); color: var(--bg); }
141
+ #detail-head button.on { border-color: var(--accent); color: var(--accent); }
142
+ #messages { flex: 1; overflow-y: auto; padding: 12px 14px; }
143
+ .msg { margin-bottom: 12px; }
144
+ .msg .ts { color: var(--dim); font-size: 10.5px; margin-bottom: 2px; }
145
+ .msg .body { word-break: break-word; }
146
+ .msg .body pre {
147
+ background: color-mix(in srgb, var(--fg) 5%, transparent);
148
+ border: 1px solid var(--border); border-radius: 6px;
149
+ padding: 8px 10px; overflow-x: auto; margin: 6px 0;
150
+ font: 12px/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace;
151
+ white-space: pre;
152
+ }
153
+ .msg .body code {
154
+ background: color-mix(in srgb, var(--fg) 7%, transparent); border-radius: 4px;
155
+ padding: 1px 5px;
156
+ font: 0.92em ui-monospace, "SF Mono", Menlo, Consolas, monospace;
157
+ }
158
+ .msg .body pre code { background: none; padding: 0; }
159
+ .msg .body h1, .msg .body h2, .msg .body h3, .msg .body h4 {
160
+ margin: 10px 0 4px; line-height: 1.3;
161
+ }
162
+ .msg .body h1 { font-size: 1.15em; border-bottom: 1px solid var(--border); padding-bottom: 3px; }
163
+ .msg .body h2 { font-size: 1.1em; }
164
+ .msg .body h3 { font-size: 1.05em; }
165
+ .msg .body h4 { font-size: 1em; color: var(--dim); }
166
+ .msg .body ul, .msg .body ol { margin: 4px 0; padding-left: 22px; }
167
+ .msg .body li { margin: 2px 0; }
168
+ .msg .body blockquote {
169
+ margin: 6px 0; padding: 4px 10px; color: var(--dim);
170
+ border-left: 3px solid var(--border);
171
+ }
172
+ .msg .body a { color: var(--accent); }
173
+ .msg .body hr { border: none; border-top: 1px solid var(--border); margin: 8px 0; }
174
+ .msg .body table { border-collapse: collapse; margin: 6px 0; font-size: 0.95em; display: block; overflow-x: auto; }
175
+ .msg .body th, .msg .body td { border: 1px solid var(--border); padding: 3px 10px; text-align: left; }
176
+ .msg .body th { background: color-mix(in srgb, var(--fg) 6%, transparent); }
177
+ .msg .body p { margin: 4px 0; white-space: pre-wrap; }
178
+ .msg.input .body {
179
+ border-left: 3px solid var(--user); padding: 6px 10px;
180
+ background: color-mix(in srgb, var(--user) 6%, transparent); border-radius: 0 6px 6px 0;
181
+ }
182
+ .msg.text .body { padding: 2px 0; }
183
+ .msg.tool {
184
+ border: 1px solid var(--border); border-radius: 6px; padding: 5px 10px;
185
+ cursor: pointer; font-size: 12.5px;
186
+ }
187
+ .msg.tool .head { display: flex; gap: 6px; align-items: baseline; }
188
+ .msg.tool .head .tname { color: var(--tool); font-weight: 600; }
189
+ .msg.tool .head .brief { color: var(--dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
190
+ .msg.tool .head .state { color: var(--dim); font-size: 11px; flex: none; }
191
+ .msg.tool.error { border-color: var(--error); }
192
+ .msg.tool.error .head .tname { color: var(--error); }
193
+ .msg.tool .result {
194
+ margin-top: 6px; padding-top: 6px; border-top: 1px dashed var(--border);
195
+ color: var(--dim); font-size: 12px; white-space: pre-wrap; word-break: break-word;
196
+ }
197
+
198
+ /* ---- Edit/Write 行级 diff(展开区第一块) ---- */
199
+ .diff {
200
+ margin: 6px 0; border: 1px solid var(--border); border-radius: 6px;
201
+ font: 12px/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace;
202
+ overflow-x: auto; white-space: pre;
203
+ }
204
+ .diff .dl { background: color-mix(in srgb, var(--error) 10%, transparent); }
205
+ .diff .ad { background: color-mix(in srgb, var(--user) 10%, transparent); }
206
+ .diff .sep { color: var(--dim); text-align: center; }
207
+ .diff .hint { color: var(--dim); padding: 0 8px; }
208
+
209
+ /* ---- 复制命令菜单(终端 / tmux / headless 三变体) ---- */
210
+ .copy-menu { position: relative; display: inline-block; }
211
+ .copy-menu summary {
212
+ font-size: 12px; padding: 4px 10px; border-radius: 6px; cursor: pointer;
213
+ border: 1px solid var(--border); background: var(--bg); color: var(--fg);
214
+ list-style: none;
215
+ }
216
+ .copy-menu summary::-webkit-details-marker { display: none; }
217
+ .copy-menu summary::after { content: " ▾"; color: var(--dim); }
218
+ .copy-menu .menu {
219
+ position: absolute; top: calc(100% + 4px); left: 0; z-index: 10;
220
+ background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
221
+ box-shadow: 0 4px 14px rgba(0,0,0,.18); min-width: 160px; padding: 4px;
222
+ }
223
+ .copy-menu button {
224
+ display: block; width: 100%; text-align: left; white-space: nowrap;
225
+ font-size: 12px; padding: 6px 10px; border: none; background: none;
226
+ color: var(--fg); cursor: pointer; border-radius: 4px;
227
+ }
228
+ .copy-menu button:hover { background: color-mix(in srgb, var(--accent) 10%, transparent); }
229
+ .copy-menu button small { display: block; color: var(--dim); font-size: 10.5px; }
230
+ .trunc-hint { color: var(--dim); font-size: 11px; }
231
+ #load-more, #detail-placeholder {
232
+ display: block; margin: 8px auto; padding: 5px 16px; border-radius: 6px;
233
+ border: 1px solid var(--border); background: var(--bg); color: var(--dim); cursor: pointer;
234
+ }
235
+ .loading { color: var(--dim); text-align: center; padding: 30px 0; }
236
+
237
+ /* ---- 窄屏堆叠 ---- */
238
+ @media (max-width: 860px) {
239
+ .layout { grid-template-columns: 1fr; }
240
+ #detail-pane { display: none; }
241
+ body.detail-open #list-pane { display: none; }
242
+ body.detail-open #detail-pane { display: flex; }
243
+ #back-btn { display: inline-block !important; }
244
+ }
245
+ #back-btn { display: none; }
246
+ </style>
247
+ </head>
248
+ <body>
249
+ <header>
250
+ <h1>csm</h1>
251
+ <span class="stats" id="stats">加载中…</span>
252
+ <span class="refreshed" id="refreshed"></span>
253
+ </header>
254
+ <main class="layout">
255
+ <section id="list-pane">
256
+ <input id="search" type="search" placeholder="搜索标题 / 首输入 / 项目 / SID… #标签">
257
+ <div id="chips"></div>
258
+ <div id="rows"></div>
259
+ </section>
260
+ <aside id="detail-pane">
261
+ <div id="detail-head">
262
+ <button id="back-btn">← 返回列表</button>
263
+ <div class="t" id="d-title">点击左侧会话查看预览</div>
264
+ <div class="meta" id="d-meta"></div>
265
+ <div id="d-tags" hidden></div>
266
+ <div class="actions" id="d-actions" hidden>
267
+ <button class="primary" id="btn-copy">复制 resume 命令</button>
268
+ <details class="copy-menu" id="copy-menu">
269
+ <summary>更多变体</summary>
270
+ <div class="menu">
271
+ <button data-variant="term"><small>claude --resume</small>终端恢复</button>
272
+ <button data-variant="tmux"><small>tmux 新窗口</small>并行恢复</button>
273
+ <button data-variant="headless"><small>claude -p --resume</small>headless 续跑</button>
274
+ </div>
275
+ </details>
276
+ <button id="btn-level-summary" class="on">摘要</button>
277
+ <button id="btn-level-full">完整</button>
278
+ <button id="btn-reload">↺ 刷新</button>
279
+ </div>
280
+ </div>
281
+ <div id="messages">
282
+ <div class="loading" id="placeholder">选择一个会话后展示对话流</div>
283
+ </div>
284
+ </aside>
285
+ </main>
286
+ <script>
287
+ "use strict";
288
+
289
+ const state = {
290
+ sessions: new Map(), // sid -> { data, el, isNew }
291
+ selected: null,
292
+ level: "summary",
293
+ oldestOrder: -1,
294
+ hasMore: false,
295
+ filter: "",
296
+ chip: "all", // 分类过滤器(与后端 FILTER_NAMES 对应)
297
+ newSeenAt: new Map(), // sid -> 徽章出现时间(10 分钟后自动摘除)
298
+ };
299
+
300
+ const CHIP_DEFS = [
301
+ ["all", "全部"], ["running", "运行中"], ["current", "本终端"],
302
+ ["starred", "收藏"], ["closed", "已关闭"], ["once", "单轮"],
303
+ ];
304
+
305
+ // 与后端 scanner.match_filter 逐条镜像(字段都在 payload 里)
306
+ function matchChip(s, name) {
307
+ switch (name) {
308
+ case "all": return true;
309
+ case "running": return s.running_status != null;
310
+ case "current": return !!s.is_current;
311
+ case "starred": return s.star > 0;
312
+ case "closed": return s.running_status == null;
313
+ case "once": return s.msg_count === 1;
314
+ default: return false;
315
+ }
316
+ }
317
+
318
+ const $ = (id) => document.getElementById(id);
319
+ const rowsEl = $("rows");
320
+
321
+ function relTime(mtime) {
322
+ const d = Math.max(Date.now() / 1000 - mtime, 0);
323
+ if (d < 60) return "now";
324
+ if (d < 3600) return Math.floor(d / 60) + "m";
325
+ if (d < 86400) return Math.floor(d / 3600) + "h";
326
+ if (d < 86400 * 7) return Math.floor(d / 86400) + "d";
327
+ const t = new Date(mtime * 1000);
328
+ return `${String(t.getMonth() + 1).padStart(2, "0")}-${String(t.getDate()).padStart(2, "0")}`;
329
+ }
330
+ function hhmm(ts) { return ts ? ts.slice(11, 16) : ""; }
331
+ function shortPath(p) {
332
+ const home = "~"; // 服务端已尽量给原始路径,这里只做展示缩短
333
+ return p && p.length > 46 ? p.slice(0, 18) + "…" + p.slice(-26) : (p || "?");
334
+ }
335
+
336
+ /* ---------- 行构建(keyed:每 sid 一个 el,就地更新,绝不重建容器) ---------- */
337
+
338
+ function buildRow(s) {
339
+ const el = document.createElement("div");
340
+ el.className = "row";
341
+ el.dataset.sid = s.session_id;
342
+ el.innerHTML = `
343
+ <div class="l1">
344
+ <button class="star" title="循环:无 → ⭐ → ★">☆</button>
345
+ <span class="dot"></span>
346
+ <span class="title"></span>
347
+ <span class="badge-cur" hidden>◉本终端</span>
348
+ <span class="badge-sdk" hidden>SDK</span>
349
+ <span class="badge-new" hidden>NEW</span>
350
+ <button class="copy" title="复制 resume 命令">复制</button>
351
+ </div>
352
+ <div class="l2"></div>`;
353
+ el.addEventListener("click", () => selectSession(s.session_id));
354
+ el.querySelector(".star").addEventListener("click", (ev) => {
355
+ ev.stopPropagation();
356
+ cycleStar(s.session_id);
357
+ });
358
+ el.querySelector(".copy").addEventListener("click", (ev) => {
359
+ ev.stopPropagation();
360
+ copyResume(s.session_id, ev.currentTarget);
361
+ });
362
+ updateRow(el, s);
363
+ return el;
364
+ }
365
+
366
+ function updateRow(el, s) {
367
+ const dot = el.querySelector(".dot");
368
+ dot.className = "dot" + (s.running_status ? " " + s.running_status : "");
369
+ if (s.running_status === "busy") dot.classList.add("pulse");
370
+ el.classList.toggle("pinned", s.star > 0);
371
+ const star = el.querySelector(".star");
372
+ star.textContent = s.star === 2 ? "★" : s.star === 1 ? "⭐" : "☆";
373
+ star.className = "star" + (s.star === 2 ? " s2" : s.star === 1 ? " s1" : "");
374
+ el.querySelector(".badge-cur").hidden = !s.is_current;
375
+ el.querySelector(".badge-sdk").hidden = !(s.entrypoint === "sdk-cli" && !s.running_status);
376
+ const title = el.querySelector(".title");
377
+ const t = s.title || s.first_input || "(无用户输入)";
378
+ title.textContent = t;
379
+ title.classList.toggle("fallback", !s.title);
380
+ const l2 = el.querySelector(".l2");
381
+ const where = s.wt_name
382
+ ? `${s.wt_repo}/${s.wt_name}` + (s.wt_branch ? ` ⎇${s.wt_branch}` : "")
383
+ : shortPath(s.project_path);
384
+ l2.textContent =
385
+ `${relTime(s.mtime)} · ${where} · ${s.msg_count ?? "·"} 轮 · ${s.session_id.slice(0, 8)}`;
386
+ if (s.tags && s.tags.length) {
387
+ const tag = document.createElement("span");
388
+ tag.className = "tagchip";
389
+ tag.textContent = " · " + s.tags.slice(0, 2).map((t) => "#" + t).join(" ");
390
+ tag.title = s.tags.map((t) => "#" + t).join(" ");
391
+ tag.addEventListener("click", (ev) => {
392
+ ev.stopPropagation();
393
+ $("search").value = "#" + s.tags[0] + " ";
394
+ state.filter = ("#" + s.tags[0]).toLowerCase();
395
+ applyFilter();
396
+ });
397
+ l2.appendChild(tag);
398
+ }
399
+ }
400
+
401
+ function reconcileOrder(order) {
402
+ /* 服务端数组顺序即目标顺序(含收藏置顶);appendChild 移动既有节点,listener 全保留 */
403
+ const cur = [...rowsEl.querySelectorAll(".row")].map((el) => el.dataset.sid);
404
+ if (cur.join("\n") === order.join("\n")) return; // 顺序没变零成本
405
+ for (const sid of order) {
406
+ const rec = state.sessions.get(sid);
407
+ if (rec) rowsEl.appendChild(rec.el); // appendChild 移动而非复制
408
+ }
409
+ }
410
+
411
+ /* ---------- 轮询 + diff ---------- */
412
+
413
+ async function poll() {
414
+ let data;
415
+ try {
416
+ const res = await fetch("/api/sessions");
417
+ data = await res.json();
418
+ } catch { return; } // 服务重启中等,静默重试
419
+ const seen = new Set();
420
+ let running = 0;
421
+ for (const s of data.sessions) {
422
+ seen.add(s.session_id);
423
+ if (s.running_status) running++;
424
+ const cur = state.sessions.get(s.session_id);
425
+ if (!cur) {
426
+ const el = buildRow(s);
427
+ markNew(s.session_id, el);
428
+ state.sessions.set(s.session_id, { data: s, el });
429
+ } else if (cur.data.rev !== s.rev) {
430
+ cur.data = s;
431
+ updateRow(cur.el, s);
432
+ if (s.session_id === state.selected) refreshDetailIfBottomPinned();
433
+ }
434
+ }
435
+ for (const [sid, cur] of [...state.sessions]) {
436
+ if (!seen.has(sid)) {
437
+ cur.el.remove();
438
+ state.sessions.delete(sid);
439
+ if (sid === state.selected) showDetailError("会话文件已被删除");
440
+ }
441
+ }
442
+ reconcileOrder(data.sessions.map((s) => s.session_id)); // 服务端序为权威(含置顶)
443
+ buildChips(!!data.current_tty_available);
444
+ pruneBadges();
445
+ applyFilter();
446
+ const starred = data.sessions.filter((s) => s.star > 0).length;
447
+ $("stats").textContent = `${data.count} 会话 · ${running} 运行中 · ★${starred} 收藏`;
448
+ $("refreshed").textContent = "刷新于 " + new Date().toLocaleTimeString("zh-CN", { hour12: false });
449
+ }
450
+
451
+ function markNew(sid, el) {
452
+ state.newSeenAt.set(sid, Date.now());
453
+ el.querySelector(".badge-new").hidden = false;
454
+ }
455
+ function pruneBadges() {
456
+ const now = Date.now();
457
+ for (const [sid, at] of state.newSeenAt) {
458
+ if (now - at > 10 * 60 * 1000) {
459
+ state.sessions.get(sid)?.el.querySelector(".badge-new")?.setAttribute("hidden", "");
460
+ state.newSeenAt.delete(sid);
461
+ }
462
+ }
463
+ }
464
+
465
+ /* ---------- 搜索与分类过滤(chips AND #tags AND plain 子串) ---------- */
466
+
467
+ let filterTimer = null;
468
+ $("search").addEventListener("input", (ev) => {
469
+ clearTimeout(filterTimer);
470
+ filterTimer = setTimeout(() => { state.filter = ev.target.value.trim().toLowerCase(); applyFilter(); }, 100);
471
+ });
472
+
473
+ function buildChips(ttyAvailable) {
474
+ const box = $("chips");
475
+ if (box.childElementCount === 0) {
476
+ for (const [name, label] of CHIP_DEFS) {
477
+ const b = document.createElement("button");
478
+ b.className = "chip";
479
+ b.dataset.name = name;
480
+ b.textContent = label;
481
+ b.addEventListener("click", () => {
482
+ state.chip = name;
483
+ for (const c of box.children) c.classList.toggle("on", c.dataset.name === name);
484
+ applyFilter();
485
+ });
486
+ box.appendChild(b);
487
+ }
488
+ }
489
+ for (const c of box.children) {
490
+ c.classList.toggle("on", c.dataset.name === state.chip);
491
+ if (c.dataset.name === "current") c.hidden = !ttyAvailable; // tty 不可用则隐藏
492
+ }
493
+ }
494
+
495
+ function applyFilter() {
496
+ const toks = state.filter.split(/\s+/).filter(Boolean);
497
+ const tags = toks.filter((t) => t.startsWith("#") && t.length > 1).map((t) => t.slice(1));
498
+ const plain = toks.filter((t) => !(t.startsWith("#") && t.length > 1));
499
+ let shown = 0;
500
+ for (const { data, el } of state.sessions.values()) {
501
+ const hay = `${data.title || ""}\n${data.first_input || ""}\n${data.project_path || ""}\n${data.session_id}`.toLowerCase();
502
+ const ok = matchChip(data, state.chip)
503
+ && tags.every((t) => (data.tags || []).some((x) => x.toLowerCase() === t))
504
+ && plain.every((t) => hay.includes(t));
505
+ el.style.display = ok ? "" : "none";
506
+ if (ok) shown++;
507
+ }
508
+ if (state.filter || state.chip !== "all") $("stats").textContent += ` · ${shown} 匹配`;
509
+ }
510
+
511
+ /* ---------- 收藏(星标循环 + 标签编辑) ---------- */
512
+
513
+ async function postFavorite(sid, body, fallback) {
514
+ try {
515
+ const res = await fetch(`/api/favorites/${sid}`, {
516
+ method: "POST",
517
+ headers: { "Content-Type": "application/json" },
518
+ body: JSON.stringify(body),
519
+ });
520
+ const data = await res.json();
521
+ if (!res.ok) throw new Error(data.error || "failed");
522
+ return data;
523
+ } catch (err) {
524
+ if (fallback) fallback();
525
+ return null;
526
+ }
527
+ }
528
+
529
+ async function cycleStar(sid) {
530
+ const rec = state.sessions.get(sid);
531
+ if (!rec) return;
532
+ const old = rec.data.star;
533
+ const next = (old + 1) % 3;
534
+ // 乐观更新
535
+ rec.data.star = next;
536
+ updateRow(rec.el, rec.data);
537
+ rec.data.rev += ":local"; // 防 poll 旧值回写覆盖(下次 poll 即服务端权威)
538
+ const result = await postFavorite(sid, { star: next }, () => {
539
+ rec.data.star = old; // 失败回滚
540
+ updateRow(rec.el, rec.data);
541
+ });
542
+ if (result && sid === state.selected) renderTags(result.star ?? old, result.tags ?? rec.data.tags);
543
+ }
544
+
545
+ function renderTags(star, tags) {
546
+ const box = $("d-tags");
547
+ box.innerHTML = "";
548
+ (tags || []).forEach((t, i) => {
549
+ const chip = document.createElement("span");
550
+ chip.className = "tag";
551
+ chip.textContent = "#" + t;
552
+ const x = document.createElement("span");
553
+ x.className = "x";
554
+ x.textContent = "×";
555
+ x.title = "删除标签";
556
+ x.addEventListener("click", async () => {
557
+ const sid = state.selected;
558
+ if (!sid) return;
559
+ const r = await postFavorite(sid, { tags: tags.filter((_, j) => j !== i) });
560
+ if (r) { renderTags(r.star, r.tags); poll(); }
561
+ });
562
+ chip.appendChild(x);
563
+ box.appendChild(chip);
564
+ });
565
+ const add = document.createElement("button");
566
+ add.textContent = "+标签";
567
+ add.addEventListener("click", () => {
568
+ const input = document.createElement("input");
569
+ input.maxLength = 24;
570
+ input.placeholder = "标签名,回车确认";
571
+ add.replaceWith(input);
572
+ input.focus();
573
+ const commit = async () => {
574
+ const v = input.value.trim();
575
+ const sid = state.selected;
576
+ if (v && sid) {
577
+ const r = await postFavorite(sid, { tags: [...(tags || []), v] });
578
+ if (r) { renderTags(r.star, r.tags); poll(); return; }
579
+ }
580
+ renderTags(star, tags); // 取消/失败:还原
581
+ };
582
+ input.addEventListener("keydown", (ev) => {
583
+ if (ev.key === "Enter") commit();
584
+ if (ev.key === "Escape") renderTags(star, tags);
585
+ });
586
+ input.addEventListener("blur", commit);
587
+ });
588
+ box.appendChild(add);
589
+ }
590
+
591
+ /* ---------- 复制(终端 / tmux / headless 变体) ---------- */
592
+
593
+ function shellQuote(s) {
594
+ return "'" + String(s).replace(/'/g, "'\\''") + "'";
595
+ }
596
+
597
+ function buildCopyCommand(s, variant) {
598
+ const sid = s.session_id;
599
+ const dir = shellQuote(s.project_path || ".");
600
+ if (variant === "tmux") {
601
+ return `tmux new-window -c ${dir} ${shellQuote(`claude --resume ${sid}`)}`;
602
+ }
603
+ if (variant === "headless") {
604
+ return `cd ${dir} && claude -p --resume ${shellQuote(sid)}`;
605
+ }
606
+ return `claude --resume ${sid}`;
607
+ }
608
+
609
+ async function copyText(cmd) {
610
+ try {
611
+ await navigator.clipboard.writeText(cmd);
612
+ } catch {
613
+ const ta = document.createElement("textarea");
614
+ ta.value = cmd;
615
+ document.body.appendChild(ta);
616
+ ta.select();
617
+ document.execCommand("copy");
618
+ ta.remove();
619
+ }
620
+ }
621
+
622
+ async function copyResume(sid, btn) {
623
+ const rec = state.sessions.get(sid);
624
+ await copyText(buildCopyCommand(rec ? rec.data : { session_id: sid }, "term"));
625
+ btn.textContent = "已复制 ✓";
626
+ btn.classList.add("ok");
627
+ setTimeout(() => { btn.textContent = "复制"; btn.classList.remove("ok"); }, 1500);
628
+ }
629
+
630
+ for (const b of $("copy-menu").querySelectorAll("button")) {
631
+ b.addEventListener("click", async () => {
632
+ const rec = state.sessions.get(state.selected);
633
+ if (!rec) return;
634
+ await copyText(buildCopyCommand(rec.data, b.dataset.variant));
635
+ $("copy-menu").open = false;
636
+ const sum = $("copy-menu").querySelector("summary");
637
+ const old = sum.firstChild.textContent;
638
+ sum.firstChild.textContent = "已复制 ✓ ";
639
+ setTimeout(() => { sum.firstChild.textContent = old; }, 1500);
640
+ });
641
+ }
642
+
643
+ /* ---------- 详情(侧栏对话流) ---------- */
644
+
645
+ function selectSession(sid) {
646
+ state.selected = sid;
647
+ for (const { el } of state.sessions.values()) el.classList.remove("selected");
648
+ state.sessions.get(sid)?.el.classList.add("selected");
649
+ document.body.classList.add("detail-open");
650
+ $("d-actions").hidden = false;
651
+ const s = state.sessions.get(sid).data;
652
+ $("d-title").textContent = (s.star === 2 ? "★ " : s.star === 1 ? "⭐ " : "") +
653
+ (s.title || s.first_input || "(无用户输入)");
654
+ $("d-meta").textContent =
655
+ `${s.wt_name ? `${s.wt_repo}/${s.wt_name} ⎇${s.wt_branch || "?"}` +
656
+ (s.wt_ahead != null ? ` +${s.wt_ahead}` : "") + " · " : ""}` +
657
+ `${shortPath(s.project_path)} · ${relTime(s.mtime)} · ${s.msg_count ?? "?"} 轮 · ${s.session_id}` +
658
+ (s.is_current ? " · ◉本终端" : "") + (s.entrypoint === "sdk-cli" ? " · SDK" : "");
659
+ $("d-tags").hidden = false;
660
+ renderTags(s.star, s.tags);
661
+ loadMessages(true);
662
+ }
663
+
664
+ function showDetailError(msg) {
665
+ $("messages").innerHTML = `<div class="empty">${msg}</div>`;
666
+ }
667
+
668
+ function atBottom(el) { return el.scrollTop + el.clientHeight >= el.scrollHeight - 20; }
669
+
670
+ function refreshDetailIfBottomPinned() {
671
+ if (atBottom($("messages"))) loadMessages(false);
672
+ }
673
+
674
+ async function loadMessages(reset) {
675
+ const sid = state.selected;
676
+ if (!sid) return;
677
+ const box = $("messages");
678
+ if (reset) {
679
+ box.innerHTML = `<div class="loading">解析中…(大文件首次约 1s)</div>`;
680
+ state.oldestOrder = -1;
681
+ }
682
+ const url = `/api/sessions/${sid}/messages?level=${state.level}&limit=50` +
683
+ (reset || state.oldestOrder < 0 ? "" : `&before_order=${state.oldestOrder}`);
684
+ let data;
685
+ try {
686
+ const res = await fetch(url);
687
+ data = await res.json();
688
+ if (!res.ok) { showDetailError(data.error || "加载失败"); return; }
689
+ } catch { showDetailError("网络错误"); return; }
690
+ if (sid !== state.selected) return; // 已切走,丢弃
691
+ state.hasMore = data.has_more;
692
+ state.oldestOrder = data.first_order ?? -1;
693
+
694
+ if (reset) box.innerHTML = "";
695
+ const frag = document.createDocumentFragment();
696
+ for (const m of data.messages) frag.appendChild(renderMessage(m));
697
+ const moreBtn = box.querySelector("#load-more");
698
+ if (moreBtn) moreBtn.remove();
699
+ if (reset) box.appendChild(frag);
700
+ else box.insertBefore(frag, box.firstChild);
701
+ if (data.has_more) {
702
+ const b = document.createElement("button");
703
+ b.id = "load-more";
704
+ b.textContent = "加载更早的消息";
705
+ b.addEventListener("click", () => loadMessages(false));
706
+ box.insertBefore(b, box.firstChild);
707
+ }
708
+ if (reset) box.scrollTop = box.scrollHeight; // 预览定位到最新
709
+ }
710
+
711
+ /* ---------- 轻量 Markdown 渲染(离线单文件约束,自实现 ~80 行) ----------
712
+ * 安全模型:先全文 HTML 转义,再白名单标签转换 → 天然免疫 XSS;
713
+ * 链接仅允许 http(s)。覆盖 Claude 输出高频语法:
714
+ * 代码块/行内代码/粗斜体/标题/无序有序列表/引用/链接/水平线/表格。 */
715
+
716
+ function escHtml(s) {
717
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;")
718
+ .replace(/>/g, "&gt;").replace(/"/g, "&quot;");
719
+ }
720
+
721
+ function mdInline(text) {
722
+ // 行内转换(输入已转义)。顺序:code → bold → italic → link
723
+ let out = "";
724
+ let rest = text;
725
+ const codeRe = /`([^`\n]+)`/;
726
+ while (true) {
727
+ const m = rest.match(codeRe);
728
+ if (!m) break;
729
+ out += mdInlineNoCode(rest.slice(0, m.index)) + `<code>${m[1]}</code>`;
730
+ rest = rest.slice(m.index + m[0].length);
731
+ }
732
+ return out + mdInlineNoCode(rest);
733
+ }
734
+
735
+ function mdInlineNoCode(text) {
736
+ return text
737
+ .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
738
+ .replace(/(^|[^*])\*([^*\n]+)\*/g, "$1<em>$2</em>")
739
+ .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g,
740
+ '<a href="$2" target="_blank" rel="noopener">$1</a>');
741
+ }
742
+
743
+ function mdBlock(escaped) {
744
+ // 块级状态机:标题/列表/引用/表格/hr/段落
745
+ const lines = escaped.split("\n");
746
+ const out = [];
747
+ let list = null; // "ul" | "ol"
748
+ let quote = null; // string[]
749
+ let table = null; // {rows: [[]], header: bool}
750
+
751
+ const flushList = () => { if (list) { out.push(`</${list}>`); list = null; } };
752
+ const flushQuote = () => {
753
+ if (quote) { out.push(`<blockquote>${mdInline(quote.join("\n"))}</blockquote>`); quote = null; }
754
+ };
755
+ const flushTable = () => {
756
+ if (table) {
757
+ const [head, ...body] = table;
758
+ out.push("<table><thead><tr>" +
759
+ head.map((c) => `<th>${mdInline(c)}</th>`).join("") + "</tr></thead><tbody>" +
760
+ body.map((r) => "<tr>" + r.map((c) => `<td>${mdInline(c)}</td>`).join("") + "</tr>").join("") +
761
+ "</tbody></table>");
762
+ table = null;
763
+ }
764
+ };
765
+ const flushAll = () => { flushList(); flushQuote(); flushTable(); };
766
+
767
+ for (const raw of lines) {
768
+ const line = raw; // 已整体转义过
769
+ const t = line.trim();
770
+
771
+ const tbl = t.match(/^\|(.+)\|$/);
772
+ if (tbl) {
773
+ const cells = tbl[1].split("|").map((c) => c.trim());
774
+ if (cells.every((c) => /^:?-{2,}:?$/.test(c))) continue; // 分隔行
775
+ if (list || quote) flushAll();
776
+ table = table || [];
777
+ table.push(cells);
778
+ continue;
779
+ }
780
+ flushTable();
781
+
782
+ if (!t) { flushAll(); continue; }
783
+
784
+ const h = t.match(/^(#{1,4})\s+(.*)$/);
785
+ if (h) { flushAll(); out.push(`<h${h[1].length}>${mdInline(h[2])}</h${h[1].length}>`); continue; }
786
+
787
+ if (/^(---+|\*\*\*+)$/.test(t)) { flushAll(); out.push("<hr>"); continue; }
788
+
789
+ const q = t.match(/^&gt;\s?(.*)$/);
790
+ if (q) { flushList(); (quote = quote || []).push(q[1]); continue; }
791
+ flushQuote();
792
+
793
+ const ul = t.match(/^[-*+]\s+(.*)$/);
794
+ if (ul) {
795
+ if (list !== "ul") { flushList(); out.push("<ul>"); list = "ul"; }
796
+ out.push(`<li>${mdInline(ul[1])}</li>`);
797
+ continue;
798
+ }
799
+ const ol = t.match(/^\d+[.)]\s+(.*)$/);
800
+ if (ol) {
801
+ if (list !== "ol") { flushList(); out.push("<ol>"); list = "ol"; }
802
+ out.push(`<li>${mdInline(ol[1])}</li>`);
803
+ continue;
804
+ }
805
+ flushList();
806
+ out.push(`<p>${mdInline(t)}</p>`);
807
+ }
808
+ flushAll();
809
+ return out.join("");
810
+ }
811
+
812
+ function mdToHtml(text) {
813
+ // 按 fenced code 分割:奇数段是代码(原样,已转义),偶数段走块级解析
814
+ const parts = escHtml(text).split(/^```[a-zA-Z0-9_+-]*\n?/m);
815
+ let html = "";
816
+ for (let i = 0; i < parts.length; i++) {
817
+ if (i % 2 === 1) {
818
+ // 未闭合的代码块(摘要截断所致)也完整渲染为代码
819
+ const code = parts[i].replace(/\n$/, "");
820
+ html += `<pre><code>${code}</code></pre>`;
821
+ } else {
822
+ html += mdBlock(parts[i]);
823
+ }
824
+ }
825
+ return html;
826
+ }
827
+
828
+ /* ---------- Edit/Write 行级 diff ----------
829
+ * LCS DP(O(n·m),行数乘积超 25 万退化提示)。服务端只在 full 级别附带
830
+ * tool_input(白名单键 + 20K 截断),摘要级别天然无 diff。 */
831
+
832
+ function diffLines(aText, bText) {
833
+ const a = aText.split("\n"), b = bText.split("\n");
834
+ if (a.length * b.length > 250000) return null;
835
+ const n = a.length, m = b.length;
836
+ const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
837
+ for (let i = n - 1; i >= 0; i--)
838
+ for (let j = m - 1; j >= 0; j--)
839
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
840
+ const rows = [];
841
+ let i = 0, j = 0;
842
+ while (i < n && j < m) {
843
+ if (a[i] === b[j]) { rows.push([" ", a[i]]); i++; j++; }
844
+ else if (dp[i + 1][j] >= dp[i][j + 1]) { rows.push(["-", a[i]]); i++; }
845
+ else { rows.push(["+", b[j]]); j++; }
846
+ }
847
+ while (i < n) rows.push(["-", a[i++]]);
848
+ while (j < m) rows.push(["+", b[j++]]);
849
+ return rows;
850
+ }
851
+
852
+ function buildDiffEl(inp, toolName) {
853
+ const pairs = []; // [oldText|null(新文件全增), newText, label|null]
854
+ if (toolName === "Edit" && typeof inp.old_string === "string") {
855
+ pairs.push([inp.old_string, typeof inp.new_string === "string" ? inp.new_string : "", null]);
856
+ } else if (toolName === "Write" && typeof inp.content === "string") {
857
+ pairs.push([null, inp.content, null]);
858
+ } else if (Array.isArray(inp.edits)) { // MultiEdit 逐段
859
+ inp.edits.forEach((ed, i) =>
860
+ pairs.push([typeof ed.old_string === "string" ? ed.old_string : "",
861
+ typeof ed.new_string === "string" ? ed.new_string : "",
862
+ `edit ${i + 1}/${inp.edits.length}`]));
863
+ } else {
864
+ return null;
865
+ }
866
+ const box = document.createElement("div");
867
+ for (const [oldT, newT, label] of pairs) {
868
+ if (label) {
869
+ const sep = document.createElement("div");
870
+ sep.className = "sep";
871
+ sep.textContent = `── ${label} ──`;
872
+ box.appendChild(sep);
873
+ }
874
+ const d = document.createElement("div");
875
+ d.className = "diff";
876
+ const rows = oldT == null
877
+ ? newT.split("\n").map((l) => ["+", l])
878
+ : diffLines(oldT, newT);
879
+ if (rows) {
880
+ for (const [t, line] of rows) {
881
+ const r = document.createElement("div");
882
+ r.className = t === "-" ? "dl" : t === "+" ? "ad" : "ctx";
883
+ r.textContent = (t === " " ? " " : t + " ") + line;
884
+ d.appendChild(r);
885
+ }
886
+ } else {
887
+ const h = document.createElement("div");
888
+ h.className = "hint";
889
+ h.textContent = "(改动过大,行级 diff 已省略)";
890
+ d.appendChild(h);
891
+ }
892
+ box.appendChild(d);
893
+ }
894
+ return box;
895
+ }
896
+
897
+ function renderMessage(m) {
898
+ const div = document.createElement("div");
899
+ const ts = `<div class="ts">${hhmm(m.ts)}</div>`;
900
+ if (m.kind === "input") {
901
+ div.className = "msg input";
902
+ div.innerHTML = ts + `<div class="body"></div>`;
903
+ div.querySelector(".body").innerHTML = mdToHtml(m.text || "");
904
+ } else if (m.kind === "text") {
905
+ div.className = "msg text";
906
+ div.innerHTML = ts + `<div class="body"></div>`;
907
+ div.querySelector(".body").innerHTML = mdToHtml(m.text || "");
908
+ if (m.text_truncated) {
909
+ const hint = document.createElement("div");
910
+ hint.className = "trunc-hint";
911
+ hint.textContent = "(已截断,切到「完整」查看全文)";
912
+ div.appendChild(hint);
913
+ }
914
+ } else {
915
+ div.className = "msg tool" + (m.tool_error ? " error" : "");
916
+ const stateTxt = m.tool_error ? "✗"
917
+ : m.tool_result_brief == null ? "…" : "✓";
918
+ div.innerHTML = `<div class="head"><span class="tname">🔧 ${m.tool_name}</span>` +
919
+ `<span class="brief"></span><span class="state">${stateTxt}</span></div>` +
920
+ `<div class="result" hidden></div>`;
921
+ div.querySelector(".brief").textContent = m.tool_brief || "";
922
+ const resultEl = div.querySelector(".result");
923
+ if (m.tool_input) {
924
+ const d = buildDiffEl(m.tool_input, m.tool_name);
925
+ if (d) resultEl.appendChild(d);
926
+ }
927
+ const brief = document.createElement("div");
928
+ brief.textContent = m.tool_result_brief ?? "(结果未写入或会话进行中)";
929
+ resultEl.appendChild(brief);
930
+ div.addEventListener("click", () => { resultEl.hidden = !resultEl.hidden; });
931
+ }
932
+ return div;
933
+ }
934
+
935
+ $("btn-copy").addEventListener("click", () => state.selected && copyResume(state.selected, $("btn-copy")));
936
+ $("btn-level-summary").addEventListener("click", () => setLevel("summary"));
937
+ $("btn-level-full").addEventListener("click", () => setLevel("full"));
938
+ $("btn-reload").addEventListener("click", () => loadMessages(true));
939
+ $("back-btn").addEventListener("click", () => document.body.classList.remove("detail-open"));
940
+
941
+ function setLevel(level) {
942
+ state.level = level;
943
+ $("btn-level-summary").classList.toggle("on", level === "summary");
944
+ $("btn-level-full").classList.toggle("on", level === "full");
945
+ loadMessages(true);
946
+ }
947
+
948
+ /* ---------- 启动 ---------- */
949
+
950
+ poll();
951
+ setInterval(() => { if (!document.hidden) poll(); }, 5000);
952
+ document.addEventListener("visibilitychange", () => { if (!document.hidden) poll(); });
953
+ </script>
954
+ </body>
955
+ </html>