@yanzc/claude-pro 0.10.0 → 0.12.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/README.md +66 -35
- package/package.json +1 -1
- package/src/agent.js +16 -6
- package/src/browser/session.js +32 -2
- package/src/commands.js +160 -11
- package/src/config.js +42 -10
- package/src/live.js +148 -0
- package/src/main.js +5 -3
- package/src/peers.js +64 -10
- package/src/providers.js +10 -1
- package/src/remote.js +90 -243
- package/src/runtime.js +36 -11
- package/src/selfcheck.js +3 -3
- package/src/session.js +116 -7
- package/src/supervisor.js +1 -1
- package/src/tools/bash.js +23 -20
- package/src/tools/browser.js +14 -8
- package/src/tools/code.js +18 -11
- package/src/tools/peers.js +6 -5
- package/src/tools/restart.js +1 -1
- package/src/ui/dialogs.js +23 -30
- package/src/ui/editor.js +65 -169
- package/src/ui/repl.js +470 -449
- package/src/ui/screen.js +47 -674
- package/src/updater.js +5 -4
- package/src/utils/shell.js +4 -5
- package/src/web/api.js +787 -0
- package/src/web/app.css +412 -0
- package/src/web/app.js +1850 -0
- package/src/web/data.js +424 -0
- package/src/web/host.js +334 -0
- package/src/web/login.html +66 -0
- package/src/web/page.html +41 -0
- package/src/web/remote-access.js +232 -0
- package/src/web/server.js +459 -0
package/src/web/app.js
ADDED
|
@@ -0,0 +1,1850 @@
|
|
|
1
|
+
// claude-pro web console (see server.js). One page, routed by the address's #fragment.
|
|
2
|
+
(() => {
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
// ---------------------------------------------------------------- helpers
|
|
6
|
+
|
|
7
|
+
const $ = (sel, root = document) => root.querySelector(sel);
|
|
8
|
+
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
|
|
9
|
+
const esc = (v) => String(v == null ? "" : v).replace(/[&<>"']/g, (ch) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ch]);
|
|
10
|
+
const main = $("#main");
|
|
11
|
+
|
|
12
|
+
async function api(path, { method = "GET", body } = {}) {
|
|
13
|
+
const res = await fetch(path, {
|
|
14
|
+
method,
|
|
15
|
+
headers: body !== undefined ? { "content-type": "application/json" } : {},
|
|
16
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
17
|
+
credentials: "same-origin",
|
|
18
|
+
});
|
|
19
|
+
const text = await res.text();
|
|
20
|
+
let data = null;
|
|
21
|
+
try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; }
|
|
22
|
+
if (!res.ok) {
|
|
23
|
+
const err = new Error(data?.error || `请求失败 (${res.status})`);
|
|
24
|
+
err.status = res.status;
|
|
25
|
+
if (res.status === 401 && data?.login) { location.reload(); return new Promise(() => {}); } // 远程访问: its login page
|
|
26
|
+
if (res.status === 401) showLoggedOut(err.message);
|
|
27
|
+
throw err;
|
|
28
|
+
}
|
|
29
|
+
return data;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
let toastTimer = 0;
|
|
33
|
+
function toast(message, kind = "ok") {
|
|
34
|
+
let el = $(".toast");
|
|
35
|
+
if (!el) { el = document.createElement("div"); document.body.appendChild(el); }
|
|
36
|
+
el.className = `toast${kind === "error" ? " error" : ""}`;
|
|
37
|
+
el.textContent = message;
|
|
38
|
+
clearTimeout(toastTimer);
|
|
39
|
+
toastTimer = setTimeout(() => el.remove(), kind === "error" ? 6000 : 3000);
|
|
40
|
+
}
|
|
41
|
+
const fail = (e) => toast(e?.message || String(e), "error");
|
|
42
|
+
|
|
43
|
+
const fmtBytes = (n) => {
|
|
44
|
+
n = Number(n) || 0;
|
|
45
|
+
if (n < 1024) return `${n} B`;
|
|
46
|
+
if (n < 1024 ** 2) return `${(n / 1024).toFixed(1)} KB`;
|
|
47
|
+
if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(1)} MB`;
|
|
48
|
+
return `${(n / 1024 ** 3).toFixed(2)} GB`;
|
|
49
|
+
};
|
|
50
|
+
const fmtTokens = (v) => { const n = Number(v) || 0; return n >= 1e9 ? `${(n / 1e9).toFixed(2)}B` : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n); };
|
|
51
|
+
const fmtUsd = (v) => { const n = Number(v) || 0; return `$${n.toFixed(n !== 0 && n < 0.01 ? 4 : 2)}`; };
|
|
52
|
+
const fmtTime = (ms) => (ms ? new Date(ms).toLocaleString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }) : "—");
|
|
53
|
+
function ago(ms) {
|
|
54
|
+
if (!ms) return "—";
|
|
55
|
+
const s = Math.max(0, Math.round((Date.now() - ms) / 1000));
|
|
56
|
+
if (s < 60) return "刚刚";
|
|
57
|
+
if (s < 3600) return `${Math.floor(s / 60)} 分钟前`;
|
|
58
|
+
if (s < 86400) return `${Math.floor(s / 3600)} 小时前`;
|
|
59
|
+
if (s < 86400 * 7) return `${Math.floor(s / 86400)} 天前`;
|
|
60
|
+
return new Date(ms).toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" });
|
|
61
|
+
}
|
|
62
|
+
const fmtDuration = (ms) => { const s = Math.max(0, Math.floor(ms / 1000)); if (s < 60) return `${s}s`; const m = Math.floor(s / 60); return m < 60 ? `${m}m ${s % 60}s` : `${Math.floor(m / 60)}h ${m % 60}m`; };
|
|
63
|
+
const shortPath = (p) => String(p || "").replace(/\\/g, "/");
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------- ANSI and Markdown (as the gateway's page)
|
|
66
|
+
|
|
67
|
+
const BASIC = ["#0c0c0c", "#cd3131", "#0dbc79", "#b5a10a", "#2472c8", "#bc3fbc", "#11a8cd", "#a0a0a0", "#666666", "#f14c4c", "#23d18b", "#b5a10a", "#3b8eea", "#d670d6", "#29b8db", "#8a8a8a"];
|
|
68
|
+
function color256(value) {
|
|
69
|
+
let n = Number(value) || 0;
|
|
70
|
+
if (n < 16) return BASIC[n];
|
|
71
|
+
if (n >= 232) { const v = 8 + (n - 232) * 10; return `rgb(${v},${v},${v})`; }
|
|
72
|
+
n -= 16;
|
|
73
|
+
const scale = [0, 95, 135, 175, 215, 255];
|
|
74
|
+
return `rgb(${scale[Math.floor(n / 36)]},${scale[Math.floor(n / 6) % 6]},${scale[n % 6]})`;
|
|
75
|
+
}
|
|
76
|
+
function ansi(line) {
|
|
77
|
+
line = String(line == null ? "" : line);
|
|
78
|
+
let out = "";
|
|
79
|
+
let style = {};
|
|
80
|
+
// eslint-disable-next-line no-control-regex
|
|
81
|
+
const re = /\x1b\[([0-9;]*)m|\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[\x00-\x08\x0b-\x1f\x7f]/g;
|
|
82
|
+
const add = (text) => {
|
|
83
|
+
if (!text) return;
|
|
84
|
+
let fg = style.fg, bg = style.bg;
|
|
85
|
+
if (style.inverse) { const old = fg; fg = bg || "var(--rc-bg)"; bg = old || "var(--rc-fg)"; }
|
|
86
|
+
// A background is the terminal's diff (dark red and green for a dark terminal): shown as the page's own added /
|
|
87
|
+
// removed colours, with its text in the page's colour, so that it reads on a light page as on a dark one.
|
|
88
|
+
let tone = "";
|
|
89
|
+
if (bg && !style.inverse) {
|
|
90
|
+
const rgb = /rgb\((\d+),(\d+),(\d+)\)/.exec(bg) || /^#(..)(..)(..)$/.exec(bg);
|
|
91
|
+
const [r, g] = rgb ? [rgb[1], rgb[2]].map((v) => (v.length === 2 && rgb[0].startsWith("#") ? parseInt(v, 16) : Number(v))) : [0, 0];
|
|
92
|
+
const b = rgb ? (rgb[0].startsWith("#") ? parseInt(rgb[3], 16) : Number(rgb[3])) : 0;
|
|
93
|
+
tone = g > r + 12 ? "a-add" : r > g + 12 ? "a-del" : "a-bg";
|
|
94
|
+
if (tone !== "a-bg" && r + g + b > 300) tone += " a-word"; // the changed words, brighter than their line
|
|
95
|
+
bg = null;
|
|
96
|
+
fg = null;
|
|
97
|
+
}
|
|
98
|
+
const classes = [tone, style.bold && "a-b", style.dim && !tone && "a-d", style.italic && "a-i", style.underline && "a-u", style.strike && "a-s"].filter(Boolean);
|
|
99
|
+
const css = (fg ? `color:${fg};` : "") + (bg ? `background:${bg};` : "");
|
|
100
|
+
const attrs = (classes.length ? ` class="${classes.join(" ")}"` : "") + (css ? ` style="${esc(css)}"` : "");
|
|
101
|
+
out += attrs ? `<span${attrs}>${esc(text)}</span>` : esc(text);
|
|
102
|
+
};
|
|
103
|
+
let last = 0, m;
|
|
104
|
+
while ((m = re.exec(line))) {
|
|
105
|
+
add(line.slice(last, m.index));
|
|
106
|
+
last = re.lastIndex;
|
|
107
|
+
if (m[1] === undefined) continue;
|
|
108
|
+
const codes = m[1] === "" ? [0] : m[1].split(";").map(Number);
|
|
109
|
+
for (let i = 0; i < codes.length; i++) {
|
|
110
|
+
const code = codes[i];
|
|
111
|
+
if (code === 0) style = {};
|
|
112
|
+
else if (code === 1) style.bold = true;
|
|
113
|
+
else if (code === 2) style.dim = true;
|
|
114
|
+
else if (code === 22) style.bold = style.dim = false;
|
|
115
|
+
else if (code === 3) style.italic = true;
|
|
116
|
+
else if (code === 23) style.italic = false;
|
|
117
|
+
else if (code === 4) style.underline = true;
|
|
118
|
+
else if (code === 24) style.underline = false;
|
|
119
|
+
else if (code === 7) style.inverse = true;
|
|
120
|
+
else if (code === 27) style.inverse = false;
|
|
121
|
+
else if (code === 9) style.strike = true;
|
|
122
|
+
else if (code === 29) style.strike = false;
|
|
123
|
+
else if (code >= 30 && code <= 37) style.fg = BASIC[code - 30];
|
|
124
|
+
else if (code >= 90 && code <= 97) style.fg = BASIC[code - 82];
|
|
125
|
+
else if (code >= 40 && code <= 47) style.bg = BASIC[code - 40];
|
|
126
|
+
else if (code >= 100 && code <= 107) style.bg = BASIC[code - 92];
|
|
127
|
+
else if (code === 39) style.fg = null;
|
|
128
|
+
else if (code === 49) style.bg = null;
|
|
129
|
+
else if (code === 38 || code === 48) {
|
|
130
|
+
let color = null;
|
|
131
|
+
if (codes[i + 1] === 2) { color = `rgb(${codes[i + 2] | 0},${codes[i + 3] | 0},${codes[i + 4] | 0})`; i += 4; }
|
|
132
|
+
else if (codes[i + 1] === 5) { color = color256(codes[i + 2]); i += 2; }
|
|
133
|
+
if (code === 38) style.fg = color; else style.bg = color;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
add(line.slice(last));
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
const ansiLines = (lines) => (Array.isArray(lines) ? lines : []).map(ansi).join("\n");
|
|
141
|
+
const plain = (s) => String(s || "").replace(/\x1b\[[0-9;?]*[A-Za-z]/g, ""); // eslint-disable-line no-control-regex
|
|
142
|
+
|
|
143
|
+
function inline(source) {
|
|
144
|
+
const codes = [];
|
|
145
|
+
const text = String(source == null ? "" : source).replace(/\u0000/g, "").replace(/`([^`]+)`/g, (_, code) => { codes.push(code); return `\u0000${codes.length - 1}\u0000`; });
|
|
146
|
+
return esc(text)
|
|
147
|
+
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
|
148
|
+
.replace(/(^|[^*\w])\*([^*\s](?:[^*]*[^*\s])?)\*(?!\*)/g, "$1<em>$2</em>")
|
|
149
|
+
.replace(/~~([^~]+)~~/g, "<del>$1</del>")
|
|
150
|
+
.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
|
|
151
|
+
.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${esc(codes[Number(i)])}</code>`);
|
|
152
|
+
}
|
|
153
|
+
function md(source) {
|
|
154
|
+
const lines = String(source == null ? "" : source).replace(/\r\n/g, "\n").split("\n");
|
|
155
|
+
let html = "", para = [], i = 0;
|
|
156
|
+
const flush = () => { if (para.length) { html += `<p>${para.map(inline).join("<br>")}</p>`; para = []; } };
|
|
157
|
+
const row = /^\s*\|.*\|\s*$/;
|
|
158
|
+
while (i < lines.length) {
|
|
159
|
+
const line = lines[i];
|
|
160
|
+
const fence = /^\s*(```+|~~~+)/.exec(line);
|
|
161
|
+
if (fence) {
|
|
162
|
+
flush();
|
|
163
|
+
const body = [];
|
|
164
|
+
i++;
|
|
165
|
+
while (i < lines.length && !lines[i].trim().startsWith(fence[1])) body.push(lines[i++]);
|
|
166
|
+
i++;
|
|
167
|
+
html += `<pre>${esc(body.join("\n"))}</pre>`;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (row.test(line) && i + 1 < lines.length && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1])) {
|
|
171
|
+
flush();
|
|
172
|
+
const rows = [];
|
|
173
|
+
while (i < lines.length && row.test(lines[i])) rows.push(lines[i++]);
|
|
174
|
+
const cells = (r) => r.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim());
|
|
175
|
+
html += "<table><thead><tr>" + cells(rows[0]).map((c) => `<th>${inline(c)}</th>`).join("") + "</tr></thead><tbody>"
|
|
176
|
+
+ rows.slice(2).map((r) => `<tr>${cells(r).map((c) => `<td>${inline(c)}</td>`).join("")}</tr>`).join("") + "</tbody></table>";
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const h = /^(#{1,6})\s+(.*)$/.exec(line);
|
|
180
|
+
if (h) { flush(); html += `<h${Math.min(4, h[1].length)}>${inline(h[2])}</h${Math.min(4, h[1].length)}>`; i++; continue; }
|
|
181
|
+
const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
|
|
182
|
+
if (li) { flush(); html += `<div class="li" style="padding-left:${Math.min(li[1].length, 12) * 0.5}em"><span class="bullet">${/\d/.test(li[2]) ? esc(li[2]) : "•"}</span><span>${inline(li[3])}</span></div>`; i++; continue; }
|
|
183
|
+
const q = /^\s*>\s?(.*)$/.exec(line);
|
|
184
|
+
if (q) { flush(); html += `<blockquote>${inline(q[1])}</blockquote>`; i++; continue; }
|
|
185
|
+
if (!line.trim()) { flush(); i++; continue; }
|
|
186
|
+
para.push(line);
|
|
187
|
+
i++;
|
|
188
|
+
}
|
|
189
|
+
flush();
|
|
190
|
+
return html;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---------------------------------------------------------------- the transcript model (as the session's remote.js)
|
|
194
|
+
|
|
195
|
+
function applyEvent(state, ev) {
|
|
196
|
+
const items = state.items;
|
|
197
|
+
const push = (item) => { items.push(item); return item; };
|
|
198
|
+
switch (ev.t) {
|
|
199
|
+
case "user": return push({ k: "user", text: ev.text });
|
|
200
|
+
case "image": return push({ k: "image", n: ev.n });
|
|
201
|
+
case "output": {
|
|
202
|
+
const last = items[items.length - 1];
|
|
203
|
+
if (last && last.k === "output") { last.lines.push(...(ev.lines || [])); return last; }
|
|
204
|
+
return push({ k: "output", lines: (ev.lines || []).slice() });
|
|
205
|
+
}
|
|
206
|
+
case "start":
|
|
207
|
+
if (state.open) state.open.open = false;
|
|
208
|
+
state.open = push({ k: ev.kind === "thinking" ? "thinking" : "text", text: "", open: true });
|
|
209
|
+
return state.open;
|
|
210
|
+
case "delta":
|
|
211
|
+
if (!state.open) state.open = push({ k: ev.kind === "thinking" ? "thinking" : "text", text: "", open: true });
|
|
212
|
+
state.open.text += String(ev.text || "");
|
|
213
|
+
return state.open;
|
|
214
|
+
case "stop": { const it = state.open; if (!it) return null; it.open = false; state.open = null; return it; }
|
|
215
|
+
case "tool": { const it = push({ k: "tool", id: ev.id, head: ev.head, status: "running", progress: "", sub: [], subCount: 0, lines: [] }); state.tools[ev.id] = it; return it; }
|
|
216
|
+
case "progress": { const it = state.tools[ev.id]; if (!it || it.status !== "running") return null; it.progress = ev.text; return it; }
|
|
217
|
+
case "sub": { const it = state.tools[ev.id]; if (!it || it.status !== "running") return null; it.sub.push(ev.head); if (it.sub.length > 3) it.sub.shift(); it.subCount++; return it; }
|
|
218
|
+
case "done": {
|
|
219
|
+
const it = state.tools[ev.id] || push({ k: "tool", id: ev.id, sub: [], subCount: 0 });
|
|
220
|
+
it.head = ev.head ?? it.head; it.status = ev.status; it.lines = ev.lines || []; it.progress = "";
|
|
221
|
+
delete state.tools[ev.id];
|
|
222
|
+
return it;
|
|
223
|
+
}
|
|
224
|
+
default: return null;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function hydrate(items) {
|
|
228
|
+
const state = { items, open: null, tools: {} };
|
|
229
|
+
for (const it of items) {
|
|
230
|
+
if (it.open) state.open = it;
|
|
231
|
+
if (it.k === "tool" && it.status === "running") state.tools[it.id] = it;
|
|
232
|
+
}
|
|
233
|
+
return state;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const trimBlank = (lines) => {
|
|
237
|
+
const out = Array.isArray(lines) ? lines.slice() : [];
|
|
238
|
+
const blank = (l) => !plain(l).trim();
|
|
239
|
+
while (out.length && blank(out[0])) out.shift();
|
|
240
|
+
while (out.length && blank(out[out.length - 1])) out.pop();
|
|
241
|
+
return out;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// One transcript item as HTML. opts: {image(n): url, full: Map id -> text, canExpand}
|
|
245
|
+
function itemHtml(item, opts = {}) {
|
|
246
|
+
if (item.k === "user") return `<div class="it it-user"><div class="bubble">${esc(item.text)}</div></div>`;
|
|
247
|
+
if (item.k === "image") return `<div class="it it-image">${opts.image ? `<img src="${opts.image(item.n)}" alt="图片" loading="lazy" data-zoom>` : "[图片]"}</div>`;
|
|
248
|
+
if (item.k === "text") return `<div class="it it-text"><span class="mark">⏺</span><div class="md">${md(item.text)}</div></div>`;
|
|
249
|
+
if (item.k === "thinking") return `<div class="it it-thinking"><details${item.open ? " open" : ""}><summary>✻ ${item.open ? "思考中…" : "思考过程"}</summary><div class="pre">${esc(item.text)}</div></details></div>`;
|
|
250
|
+
if (item.k === "summary") return `<div class="it it-summary"><details><summary>✻ 对话已压缩(摘要)</summary><div class="md">${md(item.text)}</div></details></div>`;
|
|
251
|
+
if (item.k === "output") {
|
|
252
|
+
const lines = trimBlank(item.lines);
|
|
253
|
+
return lines.length ? `<div class="it it-output"><pre>${ansiLines(lines)}</pre></div>` : "";
|
|
254
|
+
}
|
|
255
|
+
if (item.k === "tool") {
|
|
256
|
+
const running = item.status === "running";
|
|
257
|
+
let body = running
|
|
258
|
+
? [...(item.sub || []).map((h) => `<span class="a-d">${ansi(h)}</span>`), (item.subCount || 0) > (item.sub || []).length ? `<span class="a-d">+${item.subCount - item.sub.length} 次工具调用</span>` : "", item.progress ? `<span class="a-d">${esc(item.progress)}</span>` : ""].filter(Boolean).join("\n")
|
|
259
|
+
: ansiLines(trimBlank(item.lines));
|
|
260
|
+
const whole = opts.full?.get(item.id);
|
|
261
|
+
if (whole != null && !running) body = esc(whole);
|
|
262
|
+
// a shortened output ("… +N lines") is fetched whole when it comes into view (see wholeOutputs), except for
|
|
263
|
+
// the edits, whose diff says more than their result
|
|
264
|
+
const cut = !running && whole == null && item.id && truncated(item);
|
|
265
|
+
return `<div class="it it-tool ${running ? "running" : item.status === "error" ? "error" : "done"}"${cut ? ` data-cut="${esc(item.id)}"` : ""}><div class="head"><span class="dot"></span><span>${ansi(item.head || "")}</span></div>${body ? (running ? `<pre>${body}</pre>` : folded(body)) : ""}</div>`;
|
|
266
|
+
}
|
|
267
|
+
return "";
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ---------------------------------------------------------------- images for a message (as pasting one in the terminal)
|
|
271
|
+
|
|
272
|
+
const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
|
|
273
|
+
const MAX_IMAGES = 6;
|
|
274
|
+
const encode = (canvas, type, quality) => new Promise((resolve) => canvas.toBlob(resolve, type, quality));
|
|
275
|
+
// {media_type, data (base64), size, url}: scaled down to 2000 px on the longer edge (the model sees no more), at most 5 MB
|
|
276
|
+
async function prepareImage(file) {
|
|
277
|
+
if (!IMAGE_TYPES.includes(file.type)) throw new Error("只支持 PNG、JPEG、GIF、WebP 图片");
|
|
278
|
+
let blob = file;
|
|
279
|
+
if (file.type !== "image/gif") {
|
|
280
|
+
const bitmap = await createImageBitmap(file).catch(() => null);
|
|
281
|
+
if (bitmap && (Math.max(bitmap.width, bitmap.height) > 2000 || file.size > 2.5 * 1024 * 1024)) {
|
|
282
|
+
const scale = Math.min(1, 2000 / Math.max(bitmap.width, bitmap.height));
|
|
283
|
+
const canvas = document.createElement("canvas");
|
|
284
|
+
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
|
285
|
+
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
|
286
|
+
const ctx = canvas.getContext("2d");
|
|
287
|
+
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
|
288
|
+
blob = (await encode(canvas, file.type === "image/png" ? "image/png" : "image/jpeg", 0.9)) || file;
|
|
289
|
+
if (blob.size > 2.5 * 1024 * 1024) {
|
|
290
|
+
ctx.globalCompositeOperation = "destination-over";
|
|
291
|
+
ctx.fillStyle = "#fff";
|
|
292
|
+
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
293
|
+
blob = (await encode(canvas, "image/jpeg", 0.85)) || blob;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
bitmap?.close?.();
|
|
297
|
+
}
|
|
298
|
+
if (blob.size > 5 * 1024 * 1024) throw new Error("图片太大:缩小后仍超过 5 MB");
|
|
299
|
+
const data = await new Promise((resolve, reject) => {
|
|
300
|
+
const reader = new FileReader();
|
|
301
|
+
reader.onload = () => resolve(String(reader.result).split(",")[1] || "");
|
|
302
|
+
reader.onerror = () => reject(new Error("读取图片失败"));
|
|
303
|
+
reader.readAsDataURL(blob);
|
|
304
|
+
});
|
|
305
|
+
return { media_type: IMAGE_TYPES.includes(blob.type) ? blob.type : file.type, data, size: blob.size, url: URL.createObjectURL(blob) };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// A tool's output: whole, but folded to its first lines when it is long (展开 shows the rest, 收起 folds it again).
|
|
309
|
+
const FOLD_LINES = 5;
|
|
310
|
+
function folded(html) {
|
|
311
|
+
const n = html.split("\n").length;
|
|
312
|
+
if (n <= FOLD_LINES + 2) return `<pre>${html}</pre>`;
|
|
313
|
+
return `<div class="fold"><pre>${html}</pre><button type="button" class="fold-btn" data-fold>展开全部 · ${n} 行</button></div>`;
|
|
314
|
+
}
|
|
315
|
+
document.addEventListener("click", (e) => {
|
|
316
|
+
const b = e.target.closest("[data-fold]");
|
|
317
|
+
if (!b) return;
|
|
318
|
+
const box = b.closest(".fold");
|
|
319
|
+
const open = box.classList.toggle("open");
|
|
320
|
+
b.textContent = open ? "收起" : `展开全部 · ${box.querySelector("pre").textContent.split("\n").length} 行`;
|
|
321
|
+
if (!open) box.scrollIntoView({ block: "nearest" });
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
// An image of the conversation (or of the message box) opens in a box over the page: Esc, a click or ✕ closes it.
|
|
325
|
+
function zoomImage(src) {
|
|
326
|
+
const back = document.createElement("div");
|
|
327
|
+
back.className = "zoom";
|
|
328
|
+
back.innerHTML = `<img src="${esc(src)}" alt="图片"><button type="button" class="zoom-close" aria-label="关闭">✕</button>`;
|
|
329
|
+
const close = () => { back.remove(); document.removeEventListener("keydown", onKey); };
|
|
330
|
+
const onKey = (e) => { if (e.key === "Escape") close(); };
|
|
331
|
+
back.addEventListener("click", close);
|
|
332
|
+
document.addEventListener("keydown", onKey);
|
|
333
|
+
document.body.appendChild(back);
|
|
334
|
+
}
|
|
335
|
+
document.addEventListener("click", (e) => {
|
|
336
|
+
const img = e.target.closest("img[data-zoom], .thumb img");
|
|
337
|
+
if (!img) return;
|
|
338
|
+
e.preventDefault();
|
|
339
|
+
zoomImage(img.src);
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
// ---------------------------------------------------------------- whole tool outputs
|
|
343
|
+
|
|
344
|
+
const EDIT_TOOL = /^(Edit|MultiEdit|Write|NotebookEdit)\b/;
|
|
345
|
+
function truncated(item) {
|
|
346
|
+
if (EDIT_TOOL.test(plain(item.head || ""))) return false;
|
|
347
|
+
return (item.lines || []).some((l) => /… \+\d+ lines/.test(plain(l)));
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Watches the tool calls in `root` whose output was shortened; when one comes near the view its whole output is
|
|
351
|
+
// fetched (fetch(id) → text) and handed to onWhole(id, text). Returns {observe(), disconnect()}.
|
|
352
|
+
function wholeOutputs(root, fetch, onWhole) {
|
|
353
|
+
const asked = new Set();
|
|
354
|
+
const io = new IntersectionObserver((entries) => {
|
|
355
|
+
for (const e of entries) {
|
|
356
|
+
if (!e.isIntersecting) continue;
|
|
357
|
+
const id = e.target.dataset.cut;
|
|
358
|
+
io.unobserve(e.target);
|
|
359
|
+
if (!id || asked.has(id)) continue;
|
|
360
|
+
asked.add(id);
|
|
361
|
+
fetch(id).then((text) => { if (typeof text === "string") onWhole(id, text); }).catch(() => { /* the short one stays */ });
|
|
362
|
+
}
|
|
363
|
+
}, { root: root.closest(".chat-scroll") || null, rootMargin: "600px 0px" });
|
|
364
|
+
return {
|
|
365
|
+
observe() { for (const n of root.querySelectorAll("[data-cut]")) if (!asked.has(n.dataset.cut)) io.observe(n); },
|
|
366
|
+
disconnect() { io.disconnect(); },
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// ---------------------------------------------------------------- modal and file editor
|
|
371
|
+
|
|
372
|
+
function modal({ title, sub = "", body = "", foot = "", big = false }) {
|
|
373
|
+
const back = document.createElement("div");
|
|
374
|
+
back.className = "modal-back";
|
|
375
|
+
back.innerHTML = `<div class="modal${big ? " big" : ""}" role="dialog"><div class="modal-head"><div><h2>${esc(title)}</h2>${sub ? `<div class="path">${esc(sub)}</div>` : ""}</div><button type="button" class="button secondary small" data-close>关闭</button></div><div class="modal-body">${body}</div>${foot ? `<div class="modal-foot">${foot}</div>` : ""}</div>`;
|
|
376
|
+
const close = () => { back.remove(); document.removeEventListener("keydown", onKey); };
|
|
377
|
+
const onKey = (e) => { if (e.key === "Escape") close(); };
|
|
378
|
+
back.addEventListener("click", (e) => { if (e.target === back || e.target.closest("[data-close]")) close(); });
|
|
379
|
+
document.addEventListener("keydown", onKey);
|
|
380
|
+
document.body.appendChild(back);
|
|
381
|
+
return { el: back, close };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async function openEditor(path, { title = "编辑文件", deletable = false, onSaved = () => {} } = {}) {
|
|
385
|
+
let file;
|
|
386
|
+
try { file = await api(`/api/file?path=${encodeURIComponent(path)}`); } catch (e) { return fail(e); }
|
|
387
|
+
const m = modal({
|
|
388
|
+
title: file.exists ? title : `${title}(新建)`, sub: file.path, big: true,
|
|
389
|
+
body: `<textarea class="editor" spellcheck="false">${esc(file.text)}</textarea>`,
|
|
390
|
+
foot: `<span class="modal-error"></span>${deletable && file.exists ? '<button type="button" class="button danger" data-delete>删除</button>' : ""}<button type="button" class="button secondary" data-close>取消</button><button type="button" class="button" data-save>保存</button>`,
|
|
391
|
+
});
|
|
392
|
+
const area = $("textarea", m.el);
|
|
393
|
+
area.focus();
|
|
394
|
+
area.addEventListener("keydown", (e) => {
|
|
395
|
+
if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); save(); }
|
|
396
|
+
if (e.key === "Tab" && !e.shiftKey) { e.preventDefault(); document.execCommand("insertText", false, " "); }
|
|
397
|
+
});
|
|
398
|
+
async function save() {
|
|
399
|
+
try {
|
|
400
|
+
const saved = await api("/api/file", { method: "PUT", body: { path: file.path, text: area.value, mtime: file.mtime } });
|
|
401
|
+
file = { ...file, ...saved };
|
|
402
|
+
toast("已保存");
|
|
403
|
+
m.close();
|
|
404
|
+
onSaved();
|
|
405
|
+
} catch (e) { $(".modal-error", m.el).textContent = e.message; }
|
|
406
|
+
}
|
|
407
|
+
$("[data-save]", m.el).addEventListener("click", save);
|
|
408
|
+
$("[data-delete]", m.el)?.addEventListener("click", async () => {
|
|
409
|
+
if (!confirm(`删除 ${file.path}?(会移到 ~/.claude-pro/trash/files)`)) return;
|
|
410
|
+
try { await api(`/api/file?path=${encodeURIComponent(file.path)}`, { method: "DELETE" }); toast("已删除"); m.close(); onSaved(); } catch (e) { fail(e); }
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// ---------------------------------------------------------------- routing
|
|
415
|
+
|
|
416
|
+
let cleanup = null; // what the current view leaves behind (timers, streams)
|
|
417
|
+
let closeMenu = null;
|
|
418
|
+
function route() {
|
|
419
|
+
const parts = location.hash.replace(/^#\/?/, "").split("?")[0].split("/").map(decodeURIComponent); // (?tab=… is the view's own)
|
|
420
|
+
const page = parts[0] || "new";
|
|
421
|
+
$$("#nav a, .side-new").forEach((a) => a.classList.toggle("active", a.dataset.nav === page));
|
|
422
|
+
$("#sideMe").classList.toggle("active", $$("#nav a").some((a) => a.dataset.nav === page)); // a page of its menu
|
|
423
|
+
showUserMenu(false);
|
|
424
|
+
markActive();
|
|
425
|
+
$("#tip")?.classList.add("hidden");
|
|
426
|
+
closeMenu?.();
|
|
427
|
+
if (cleanup) { try { cleanup(); } catch { /* ignore */ } cleanup = null; }
|
|
428
|
+
main.scrollTop = 0;
|
|
429
|
+
setDrawer(false);
|
|
430
|
+
const views = { new: newView, remote: remotePage, overview, sessions, session: () => sessionView(parts[1], parts[2]), live: () => (parts[1] ? liveView(parts[1]) : newView()), providers, settings, memory, extensions, usage };
|
|
431
|
+
(views[page] || newView)();
|
|
432
|
+
}
|
|
433
|
+
// mode: true = full width, "chat" = the conversation layout (full height, its own scrolling)
|
|
434
|
+
const page = (html, mode = false) => { main.innerHTML = `<div class="page${mode === "chat" ? " chat" : mode ? " wide" : ""}">${html}</div>`; return $(".page", main); };
|
|
435
|
+
|
|
436
|
+
function showLoggedOut(message) {
|
|
437
|
+
main.innerHTML = `<div class="page"><div class="panel panel-pad" style="max-width:560px;margin:60px auto"><h1>需要从 claude-pro 打开</h1><p class="sub">${esc(message)}</p><p>在任意 claude-pro 会话里输入 <code>/web</code>,或在终端运行 <code>claude-pro web</code>,会自动打开并登录这个页面。</p></div></div>`;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// ---------------------------------------------------------------- 概览
|
|
441
|
+
|
|
442
|
+
async function overview() {
|
|
443
|
+
const el = page('<h1>概览</h1><p class="sub">这台电脑上的 claude-pro</p><div class="empty">正在加载…</div>');
|
|
444
|
+
let o;
|
|
445
|
+
try { o = await api("/api/overview"); } catch (e) { el.innerHTML = `<h1>概览</h1><div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
446
|
+
$("#brandVersion").textContent = `v${o.version}`;
|
|
447
|
+
const gw = o.gateway;
|
|
448
|
+
el.innerHTML = `<h1>概览</h1><p class="sub">这台电脑上的 claude-pro · ${esc(o.host)}</p>
|
|
449
|
+
<div class="cards">
|
|
450
|
+
<a class="panel stat" href="#/new"><div class="label">运行中的会话</div><div class="value">${o.running}</div><div class="hint">${o.busy ? `${o.busy} 个正在工作` : "都空闲"}</div></a>
|
|
451
|
+
<a class="panel stat" href="#/sessions"><div class="label">会话记录</div><div class="value">${o.sessions}</div><div class="hint">${o.projects} 个项目 · 占用 ${fmtBytes(o.storage)}</div></a>
|
|
452
|
+
<a class="panel stat" href="#/providers"><div class="label">默认模型</div><div class="value" style="font-size:16px;word-break:break-all">${esc(o.remembered?.model || o.model)}</div><div class="hint">推理强度 ${esc(o.remembered?.effort || o.effort)}${o.remembered?.model ? " · 来自 /model 记住的选择" : ""}</div></a>
|
|
453
|
+
<a class="panel stat" href="#/providers"><div class="label">7bit.fun 余额</div><div class="value">${gw ? (gw.balance != null ? fmtUsd(gw.balance) : "—") : "未连接"}</div><div class="hint">${gw ? esc(gw.account?.email || gw.account?.name || gw.key) : "在「模型与供应商」里连接"}${gw?.accountError ? ` · ${esc(gw.accountError)}` : ""}</div></a>
|
|
454
|
+
</div>
|
|
455
|
+
<div class="section-head"><h2>版本与位置</h2><button class="button secondary small" id="checkUpdate">检查更新</button></div>
|
|
456
|
+
<div class="panel panel-pad"><dl class="kv">
|
|
457
|
+
<dt>版本</dt><dd>v${esc(o.version)} <span id="updateState" class="muted"></span></dd>
|
|
458
|
+
<dt>安装位置</dt><dd class="mono">${esc(o.installDir)}${o.sourceCheckout ? ' <span class="pill accent">源码</span>' : ""}</dd>
|
|
459
|
+
<dt>配置目录</dt><dd class="mono">${esc(o.configDir)}</dd>
|
|
460
|
+
<dt>Node</dt><dd>${esc(o.node)} · ${esc(o.platform)}</dd>
|
|
461
|
+
</dl></div>
|
|
462
|
+
<div class="section-head"><h2>已连接的供应商</h2><a class="button secondary small" href="#/providers">管理</a></div>
|
|
463
|
+
<div class="panel">${gw || o.providers.length ? `<table class="list"><tbody>
|
|
464
|
+
${gw ? `<tr><td><strong>7bit.fun</strong></td><td class="muted">${esc(gw.url)}</td><td class="num">${esc(gw.key)}</td></tr>` : ""}
|
|
465
|
+
${o.providers.map((p) => `<tr><td><strong>${esc(p.name)}</strong></td><td class="muted">${p.models} 个模型</td><td class="num mono">${esc(p.id)}/…</td></tr>`).join("")}
|
|
466
|
+
</tbody></table>` : '<div class="empty">还没有连接任何供应商</div>'}</div>`;
|
|
467
|
+
$("#checkUpdate").addEventListener("click", async () => {
|
|
468
|
+
$("#updateState").textContent = "检查中…";
|
|
469
|
+
const u = await api("/api/update?check=1").catch((e) => ({ status: "error", error: e.message }));
|
|
470
|
+
paintBrandUpdate(u);
|
|
471
|
+
const state = $("#updateState", el);
|
|
472
|
+
if (state) state.textContent = { dev: "· 源码版通过 Git 更新", current: "· 已是最新", available: `· 有新版本 ${u.version},请点击版本号旁的更新按钮`, installed: `· 新版本 ${u.version} 已安装,点击版本号旁的按钮加载`, updating: "· 正在安装", restarting: "· 等待控制台加载新版", error: `· 检查失败:${u.error}` }[u.status] || "";
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// ---------------------------------------------------------------- 会话
|
|
477
|
+
|
|
478
|
+
let sessionCache = null;
|
|
479
|
+
async function sessions() {
|
|
480
|
+
const params = new URLSearchParams(location.hash.split("?")[1] || "");
|
|
481
|
+
const tab = ["trash", "archived"].includes(params.get("tab")) ? params.get("tab") : "list";
|
|
482
|
+
const el = page(`<h1>会话</h1><p class="sub">所有项目的对话记录:搜索、查看、改名、导出、在终端中继续</p>
|
|
483
|
+
<div class="tabs"><a href="#/sessions" class="${tab === "list" ? "active" : ""}">全部会话</a><a href="#/sessions?tab=archived" class="${tab === "archived" ? "active" : ""}">已归档</a><a href="#/sessions?tab=trash" class="${tab === "trash" ? "active" : ""}">回收站</a></div><div id="body"><div class="empty">正在加载…</div></div>`);
|
|
484
|
+
const body = $("#body", el);
|
|
485
|
+
if (tab === "trash") return trash(body);
|
|
486
|
+
let data;
|
|
487
|
+
try { data = await api("/api/sessions"); } catch (e) { body.innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
488
|
+
sessionCache = data.sessions;
|
|
489
|
+
const projects = [...new Map(data.sessions.filter((s) => s.cwd).map((s) => [s.dir, s.cwd])).entries()];
|
|
490
|
+
const saved = JSON.parse(sessionStorage.getItem("sessionFilter") || "{}");
|
|
491
|
+
body.innerHTML = `<div class="toolbar"><input type="search" id="q" placeholder="搜索会话名、第一句话、id、目录…" value="${esc(saved.q || "")}">
|
|
492
|
+
<select id="proj"><option value="">所有项目(${projects.length})</option>${projects.map(([dir, cwd]) => `<option value="${esc(dir)}"${saved.proj === dir ? " selected" : ""}>${esc(shortPath(cwd))}</option>`).join("")}</select>
|
|
493
|
+
<select id="sort"><option value="time">按最近使用</option><option value="size"${saved.sort === "size" ? " selected" : ""}>按大小</option><option value="cost"${saved.sort === "cost" ? " selected" : ""}>按花费</option></select></div>
|
|
494
|
+
<div class="panel" id="table"></div><p class="faint" id="count" style="font-size:12px;margin-top:8px"></p>`;
|
|
495
|
+
const draw = () => {
|
|
496
|
+
const q = $("#q").value.trim().toLowerCase();
|
|
497
|
+
const proj = $("#proj").value;
|
|
498
|
+
const sort = $("#sort").value;
|
|
499
|
+
sessionStorage.setItem("sessionFilter", JSON.stringify({ q, proj, sort }));
|
|
500
|
+
let list = sessionCache.filter((s) => (tab === "archived" ? s.archived : !s.archived) && (!proj || s.dir === proj) && (!q || [s.title, s.firstPrompt, s.id, s.cwd, s.topic].some((v) => String(v || "").toLowerCase().includes(q))));
|
|
501
|
+
if (sort === "size") list = list.slice().sort((a, b) => b.size - a.size);
|
|
502
|
+
if (sort === "cost") list = list.slice().sort((a, b) => b.cost - a.cost);
|
|
503
|
+
const shown = list.slice(0, 300);
|
|
504
|
+
$("#table").innerHTML = shown.length ? `<table class="list"><thead><tr><th>会话</th><th>最后使用</th><th class="num">消息</th><th class="num">大小</th><th class="num">花费</th></tr></thead><tbody>
|
|
505
|
+
${shown.map((s) => `<tr class="click" data-open="${esc(s.dir)}/${esc(s.id)}"><td class="title-cell"><strong>${s.running ? '<span class="pill ok">运行中</span> ' : ""}${esc(s.title)}</strong><div class="path">${esc(shortPath(s.cwd || s.dir))} · ${esc(s.id.slice(0, 8))}</div></td>
|
|
506
|
+
<td title="${esc(fmtTime(s.mtime))}">${ago(s.mtime)}</td><td class="num">${s.count}</td><td class="num">${fmtBytes(s.size)}</td><td class="num">${s.cost ? fmtUsd(s.cost) : "—"}${tab === "archived" ? ` <button class="button secondary small" data-unarchive="${esc(s.id)}">取消归档</button>` : ""}</td></tr>`).join("")}
|
|
507
|
+
</tbody></table>` : `<div class="empty">${tab === "archived" ? "没有归档的会话:在工作区点会话右边的「…」,选择「归档」" : "没有符合条件的会话"}</div>`;
|
|
508
|
+
$("#count").textContent = `共 ${list.length} 个${list.length > shown.length ? `,显示前 ${shown.length} 个(用搜索缩小范围)` : ""}`;
|
|
509
|
+
};
|
|
510
|
+
draw();
|
|
511
|
+
$("#q").addEventListener("input", draw);
|
|
512
|
+
$("#proj").addEventListener("change", draw);
|
|
513
|
+
$("#sort").addEventListener("change", draw);
|
|
514
|
+
$("#table").addEventListener("click", async (e) => {
|
|
515
|
+
const un = e.target.closest("[data-unarchive]");
|
|
516
|
+
if (un) {
|
|
517
|
+
try { await archive([un.dataset.unarchive], false); } catch (err) { return fail(err); }
|
|
518
|
+
const s = sessionCache.find((x) => x.id === un.dataset.unarchive);
|
|
519
|
+
if (s) delete s.archived;
|
|
520
|
+
return draw();
|
|
521
|
+
}
|
|
522
|
+
const row = e.target.closest("[data-open]");
|
|
523
|
+
if (row) location.hash = `#/session/${row.dataset.open}`;
|
|
524
|
+
});
|
|
525
|
+
$("#q").focus();
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
async function trash(body) {
|
|
529
|
+
let data;
|
|
530
|
+
try { data = await api("/api/trash"); } catch (e) { body.innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
531
|
+
const box = document.createElement("div");
|
|
532
|
+
body.replaceChildren(box);
|
|
533
|
+
box.innerHTML = `<p class="muted" style="font-size:13px">删除的会话在这里保留 7 天,之后自动清除。</p><div class="panel">${data.items.length ? `<table class="list"><thead><tr><th>会话</th><th>删除时间</th><th class="num">消息</th><th></th></tr></thead><tbody>
|
|
534
|
+
${data.items.map((t) => `<tr><td class="title-cell"><strong>${esc(t.title)}</strong><div class="path">${esc(shortPath(t.cwd || t.dir))}</div></td><td>${ago(t.deletedAt)}</td><td class="num">${t.count}</td>
|
|
535
|
+
<td class="num"><button class="button secondary small" data-restore="${esc(t.trashId)}">恢复</button> <button class="button danger small" data-purge="${esc(t.trashId)}">彻底删除</button></td></tr>`).join("")}
|
|
536
|
+
</tbody></table>` : '<div class="empty">回收站是空的</div>'}</div>${data.items.length ? '<div class="actions" style="margin-top:12px"><button class="button danger small" id="purgeAll">清空回收站</button></div>' : ""}`;
|
|
537
|
+
box.addEventListener("click", async (e) => {
|
|
538
|
+
const r = e.target.closest("[data-restore]"), p = e.target.closest("[data-purge]");
|
|
539
|
+
try {
|
|
540
|
+
if (r) { await api(`/api/trash/${encodeURIComponent(r.dataset.restore)}/restore`, { method: "POST" }); toast("已恢复"); trash(body); }
|
|
541
|
+
if (p && confirm("彻底删除这个会话?不能恢复。")) { await api(`/api/trash/${encodeURIComponent(p.dataset.purge)}`, { method: "DELETE" }); trash(body); }
|
|
542
|
+
if (e.target.id === "purgeAll" && confirm("清空回收站?不能恢复。")) { await api("/api/trash", { method: "DELETE" }); trash(body); }
|
|
543
|
+
} catch (err) { fail(err); }
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
async function sessionView(dir, id) {
|
|
548
|
+
const here = location.hash;
|
|
549
|
+
const el = page('<div class="chat-page"><div class="chat-scroll"><div class="empty">正在加载会话…</div></div></div>', "chat");
|
|
550
|
+
let d;
|
|
551
|
+
try { d = await api(`/api/sessions/${encodeURIComponent(dir)}/${encodeURIComponent(id)}`); } catch (e) { el.innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
552
|
+
if (!el.isConnected || location.hash !== here) return;
|
|
553
|
+
if (d.running) { location.replace(`#/live/${d.running}`); return; }
|
|
554
|
+
// A conversation is opened as a running one: the console takes it up (in a tenth of a second) and the live view
|
|
555
|
+
// replaces this one; what is drawn here meanwhile is the same conversation. (The console puts it away again once
|
|
556
|
+
// nobody has looked at it for a while: see SessionHost.reap.)
|
|
557
|
+
const base = `/api/sessions/${encodeURIComponent(dir)}/${encodeURIComponent(id)}`;
|
|
558
|
+
el.innerHTML = `<div class="chat-page">
|
|
559
|
+
<header class="chat-head"><div class="chat-titles"><h2>${esc(d.title)}</h2><div class="chat-sub">${esc(shortPath(d.cwd || dir))} · ${d.count} 条消息 · ${fmtBytes(d.size)}${d.cost ? ` · ${fmtUsd(d.cost)}` : ""} · 最后使用 ${esc(fmtTime(d.mtime))}</div></div><button type="button" class="icon-btn" id="hmenu" title="更多">${ICON.more}</button></header>
|
|
560
|
+
<div class="chat-scroll" id="hscroll"><div class="chat-log" id="log"></div></div>
|
|
561
|
+
<div class="chat-foot"><div class="chat-composer" id="hcomp"></div></div></div>`;
|
|
562
|
+
const log = $("#log", el);
|
|
563
|
+
const image = (n) => `${base}/image/${n}`;
|
|
564
|
+
// drawn in pieces: a long conversation has thousands of items
|
|
565
|
+
let i = 0;
|
|
566
|
+
const wholes = wholeOutputs(log, async (tool) => (await api(`${base}/output/${encodeURIComponent(tool)}`)).text, (tool, text) => {
|
|
567
|
+
const node = log.querySelector(`[data-cut="${CSS.escape(tool)}"]`);
|
|
568
|
+
const old = node?.querySelector(".fold, pre");
|
|
569
|
+
if (old) old.outerHTML = folded(esc(text));
|
|
570
|
+
});
|
|
571
|
+
cleanup = () => wholes.disconnect();
|
|
572
|
+
const step = () => {
|
|
573
|
+
log.insertAdjacentHTML("beforeend", d.items.slice(i, i + 200).map((it) => itemHtml(it, { image })).join(""));
|
|
574
|
+
wholes.observe();
|
|
575
|
+
i += 200;
|
|
576
|
+
if (i < d.items.length) requestAnimationFrame(step);
|
|
577
|
+
else if (!d.items.length) log.innerHTML = '<div class="chat-empty">没有内容</div>';
|
|
578
|
+
};
|
|
579
|
+
step();
|
|
580
|
+
// The conversation goes on (in the console, or in a terminal tab): resolves with its live peer id once it is up
|
|
581
|
+
// (null: it cannot be started from here, the command to run was shown), or throws.
|
|
582
|
+
const start = async (inConsole) => {
|
|
583
|
+
const r = await api(`${base}/open`, { method: "POST", body: { terminal: !inConsole } });
|
|
584
|
+
if (r.peerId) return r.peerId;
|
|
585
|
+
if (!r.opened) { await navigator.clipboard.writeText(r.command).catch(() => {}); toast(`请在终端运行(已复制):${r.command}`); return null; }
|
|
586
|
+
toast(`已在 ${r.how} 新标签中继续,等它上线…`);
|
|
587
|
+
for (let k = 0; k < 30; k++) {
|
|
588
|
+
await new Promise((res) => setTimeout(res, 1000));
|
|
589
|
+
const live = (await api("/api/live").catch(() => ({ sessions: [] }))).sessions.find((x) => x.status?.sessionId === id);
|
|
590
|
+
if (live) return live.peerId;
|
|
591
|
+
}
|
|
592
|
+
throw new Error("会话 30 秒内没有上线");
|
|
593
|
+
};
|
|
594
|
+
let sendingFirst = false;
|
|
595
|
+
// Writing to it starts it: the message goes to it once its live view watches it (as for a new session)
|
|
596
|
+
const hc = composer($("#hcomp", el), {
|
|
597
|
+
placeholder: "发消息继续这个对话,/命令、!命令、@会话 都可以。Enter 发送,Shift+Enter 换行",
|
|
598
|
+
dropZone: el,
|
|
599
|
+
draftKey: `session:${id}`,
|
|
600
|
+
onSend: async (text, images) => {
|
|
601
|
+
sendingFirst = true;
|
|
602
|
+
try {
|
|
603
|
+
const peerId = await start(true);
|
|
604
|
+
if (!peerId) throw new Error("这个系统不能自动启动会话");
|
|
605
|
+
queueFirstMessage(peerId, text, images);
|
|
606
|
+
if (!left && location.hash === here) location.hash = `#/live/${peerId}`;
|
|
607
|
+
} catch (e) { sendingFirst = false; throw e; }
|
|
608
|
+
},
|
|
609
|
+
});
|
|
610
|
+
const done = cleanup;
|
|
611
|
+
let left = false;
|
|
612
|
+
cleanup = () => { left = true; done(); hc.dispose(); };
|
|
613
|
+
start(true).then((peerId) => { if (peerId && !left && !sendingFirst && location.hash === here) { loadWorkspace(); location.replace(`#/live/${peerId}`); } }).catch(() => { /* stays as it is: sending starts it */ });
|
|
614
|
+
$("#hmenu", el).addEventListener("click", (e) => {
|
|
615
|
+
popMenu(e.currentTarget, [{ key: "a", title: "", items: [
|
|
616
|
+
{ label: "导出 Markdown", value: "export" },
|
|
617
|
+
{ label: d.archived ? "取消归档" : "归档", description: d.archived ? "回到工作区" : "从工作区收起,内容保留", value: "archive" },
|
|
618
|
+
{ label: "删除", description: "先进回收站,7 天内可以恢复", value: "delete" },
|
|
619
|
+
] }], async (key, value) => {
|
|
620
|
+
try {
|
|
621
|
+
if (value === "export") location.href = `${base}/export`;
|
|
622
|
+
if (value === "archive") { await archive([id], !d.archived); d.archived = !d.archived; }
|
|
623
|
+
if (value === "delete" && confirm(`删除「${d.title}」?会先移到回收站,保留 7 天。`)) {
|
|
624
|
+
await api(base, { method: "DELETE" });
|
|
625
|
+
toast("已移到回收站");
|
|
626
|
+
await loadWorkspace();
|
|
627
|
+
location.hash = "#/new";
|
|
628
|
+
}
|
|
629
|
+
} catch (err) { fail(err); }
|
|
630
|
+
});
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// ---------------------------------------------------------------- the sidebar: 工作区 (projects and their conversations)
|
|
635
|
+
|
|
636
|
+
const ICON = {
|
|
637
|
+
plus: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/></svg>',
|
|
638
|
+
folder: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>',
|
|
639
|
+
folderOpen: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h7a2 2 0 0 1 2 2v1"/><path d="M3 19l2.5-7.5A2 2 0 0 1 7.4 10H21l-2.7 8a2 2 0 0 1-1.9 1H5a2 2 0 0 1-2-2"/></svg>',
|
|
640
|
+
search: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>',
|
|
641
|
+
refresh: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/></svg>',
|
|
642
|
+
newChat: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>',
|
|
643
|
+
send: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',
|
|
644
|
+
stop: '<svg viewBox="0 0 24 24" width="14" height="14"><rect x="5" y="5" width="14" height="14" rx="2" fill="currentColor"/></svg>',
|
|
645
|
+
add: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>',
|
|
646
|
+
caret: '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>',
|
|
647
|
+
more: '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><circle cx="5" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="19" cy="12" r="1.8"/></svg>',
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
// how long ago, as short as the sidebar wants it: 刚刚, 5分, 3小时, 16天, 2个月, 1年
|
|
651
|
+
function shortAgo(ms) {
|
|
652
|
+
if (!ms) return "";
|
|
653
|
+
const s = Math.max(0, (Date.now() - ms) / 1000);
|
|
654
|
+
if (s < 60) return "刚刚";
|
|
655
|
+
if (s < 3600) return `${Math.floor(s / 60)}分`;
|
|
656
|
+
if (s < 86400) return `${Math.floor(s / 3600)}小时`;
|
|
657
|
+
if (s < 86400 * 30) return `${Math.floor(s / 86400)}天`;
|
|
658
|
+
if (s < 86400 * 365) return `${Math.floor(s / (86400 * 30))}个月`;
|
|
659
|
+
return `${Math.floor(s / (86400 * 365))}年`;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const working = (it) => Boolean(it.peer && (it.peer.status?.turn || it.peer.status?.dialog));
|
|
663
|
+
function liveState(st = {}) {
|
|
664
|
+
if (st.dialog) return ["ask", "等待回答"];
|
|
665
|
+
if (st.turn) return ["busy", st.verb ? `${st.verb}…` : "工作中"];
|
|
666
|
+
return ["idle", "空闲"];
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
const ws = {
|
|
670
|
+
sessions: [], live: [], projectOpen: {}, q: "", loaded: false,
|
|
671
|
+
closed: new Set(JSON.parse(localStorage.getItem("cpWsClosed") || "[]")),
|
|
672
|
+
expanded: new Set(),
|
|
673
|
+
tips: new Map(),
|
|
674
|
+
};
|
|
675
|
+
const projectKey = (cwd) => shortPath(cwd || "").toLowerCase().replace(/\/+$/, "");
|
|
676
|
+
const baseName = (cwd) => shortPath(cwd || "").replace(/\/+$/, "").split("/").pop() || cwd || "?";
|
|
677
|
+
|
|
678
|
+
let workspaceLoad;
|
|
679
|
+
async function loadWorkspace({ afterPending = false } = {}) {
|
|
680
|
+
if (workspaceLoad) {
|
|
681
|
+
if (!afterPending) return workspaceLoad;
|
|
682
|
+
await workspaceLoad;
|
|
683
|
+
}
|
|
684
|
+
return workspaceLoad ||= (async () => {
|
|
685
|
+
try {
|
|
686
|
+
const s = await api("/api/sessions");
|
|
687
|
+
ws.sessions = s.sessions;
|
|
688
|
+
ws.projectOpen = s.projectOpen || {};
|
|
689
|
+
ws.live = s.live || (await api("/api/live")).sessions;
|
|
690
|
+
ws.loaded = true;
|
|
691
|
+
if (!sidebarMenuOpen()) drawWorkspace();
|
|
692
|
+
} catch (e) {
|
|
693
|
+
if (!ws.loaded) $("#ws").innerHTML = `<div class="ws-empty">加载失败:${esc(e.message)}</div>`;
|
|
694
|
+
}
|
|
695
|
+
})().finally(() => { workspaceLoad = null; });
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const sidebarMenuOpen = () => $("#ws :is([data-session-menu], [data-pmenu])[aria-expanded=true]");
|
|
699
|
+
|
|
700
|
+
function drawWorkspace() {
|
|
701
|
+
if (sidebarMenuOpen()) closeMenu?.();
|
|
702
|
+
const box = $("#ws");
|
|
703
|
+
const liveById = new Map(ws.live.map((l) => [l.peerId, l]));
|
|
704
|
+
const known = new Set(ws.sessions.map((s) => s.id));
|
|
705
|
+
// (an archived conversation is not listed, unless it runs again)
|
|
706
|
+
const items = ws.sessions.filter((s) => !s.archived || s.running).map((s) => {
|
|
707
|
+
const peer = s.running ? liveById.get(s.running) : null;
|
|
708
|
+
return { id: s.id, dir: s.dir, archived: s.archived, href: peer ? `#/live/${peer.peerId}` : `#/session/${s.dir}/${s.id}`, title: peer?.status?.title || s.title, cwd: s.cwd || s.dir, mtime: s.mtime, peer, alt: peer ? `#/session/${s.dir}/${s.id}` : null };
|
|
709
|
+
});
|
|
710
|
+
// running sessions with nothing written yet (just started)
|
|
711
|
+
for (const l of ws.live) if (!known.has(l.status?.sessionId)) items.push({ href: `#/live/${l.peerId}`, title: l.status?.title || l.name, cwd: l.status?.cwd || l.cwd, mtime: l.startedAt || 0, peer: l });
|
|
712
|
+
const q = ws.q.toLowerCase();
|
|
713
|
+
const groups = new Map();
|
|
714
|
+
for (const it of items) {
|
|
715
|
+
if (q && !`${it.title} ${it.cwd}`.toLowerCase().includes(q)) continue;
|
|
716
|
+
const key = projectKey(it.cwd);
|
|
717
|
+
if (!groups.has(key)) groups.set(key, { key, cwd: it.cwd, items: [], last: 0, live: false });
|
|
718
|
+
const g = groups.get(key);
|
|
719
|
+
g.items.push(it);
|
|
720
|
+
// the projects with a session running first, then by when they last had a message (a running session counted as
|
|
721
|
+
// "now" made two such projects swap places at every redraw: both were "now", a few ms apart)
|
|
722
|
+
g.last = Math.max(g.last, it.mtime || 0);
|
|
723
|
+
if (working(it)) g.live = true;
|
|
724
|
+
}
|
|
725
|
+
const list = [...groups.values()].sort((a, b) => b.live - a.live || b.last - a.last || a.key.localeCompare(b.key));
|
|
726
|
+
const here = location.hash;
|
|
727
|
+
ws.tips.clear();
|
|
728
|
+
let n = 0;
|
|
729
|
+
box.innerHTML = list.length ? list.map((g) => {
|
|
730
|
+
g.items.sort((a, b) => working(b) - working(a) || b.mtime - a.mtime);
|
|
731
|
+
const closed = ws.closed.has(g.key) && !q;
|
|
732
|
+
const limit = ws.expanded.has(g.key) || q ? Infinity : 6;
|
|
733
|
+
const rows = closed ? "" : g.items.slice(0, limit).map((it) => {
|
|
734
|
+
const id = `t${n++}`;
|
|
735
|
+
ws.tips.set(id, it);
|
|
736
|
+
const [cls] = it.peer ? liveState(it.peer.status) : [""];
|
|
737
|
+
const active = here === it.href || (it.alt && here === it.alt);
|
|
738
|
+
return `<div class="ws-row${it.id ? " has-menu" : ""}" data-tip="${id}"><a class="ws-item${active ? " active" : ""}" href="${esc(it.href)}">${working(it) ? `<span class="ws-dot ${cls}"></span>` : ""}<span class="ws-title">${esc(it.title)}</span>${working(it) ? "" : `<span class="ws-ago">${esc(shortAgo(it.mtime))}</span>`}</a>${it.id ? `<button type="button" class="ws-menu" data-session-menu aria-label="对话操作:${esc(it.title)}" aria-expanded="false">${ICON.more}</button>` : ""}</div>`;
|
|
739
|
+
}).join("") + (!closed && g.items.length > limit ? `<button type="button" class="ws-more" data-expand="${esc(g.key)}">展开其余 ${g.items.length - limit} 个</button>` : "");
|
|
740
|
+
const running = g.items.filter(working).length;
|
|
741
|
+
return `<div class="ws-group"><div class="ws-folder-row"><button type="button" class="ws-folder" data-folder="${esc(g.key)}" title="${esc(shortPath(g.cwd))}">${closed ? ICON.folder : ICON.folderOpen}<span>${esc(baseName(g.cwd))}</span>${running ? `<span class="ws-count">${running}</span>` : ""}</button><button type="button" class="ws-pmenu" data-pmenu="${esc(g.key)}" data-cwd="${esc(g.cwd)}" title="更多" aria-label="项目菜单" aria-expanded="false">${ICON.more}</button><button type="button" class="ws-add" data-add="${esc(g.cwd)}" title="在 ${esc(baseName(g.cwd))} 里新建会话" aria-label="新建会话">${ICON.add}</button></div>${rows}</div>`;
|
|
742
|
+
}).join("") : `<div class="ws-empty">${q ? "没有符合的会话" : "还没有会话"}</div>`;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
function markActive() {
|
|
746
|
+
const here = location.hash;
|
|
747
|
+
$$("#ws .ws-item").forEach((a) => {
|
|
748
|
+
const it = ws.tips.get(a.parentElement.dataset.tip);
|
|
749
|
+
a.classList.toggle("active", Boolean(it && (here === it.href || (it.alt && here === it.alt))));
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
// 归档 (or back, `archived` false): out of the workspace, kept whole, never cleaned up by age. A conversation the
|
|
754
|
+
// console runs is put away first; one running in a terminal is only marked (it stays listed while it runs, and the
|
|
755
|
+
// page does not end a terminal's session).
|
|
756
|
+
async function archive(ids, archived = true, { force = false } = {}) {
|
|
757
|
+
if (archived) {
|
|
758
|
+
const live = (await api("/api/live")).sessions;
|
|
759
|
+
for (const id of ids) {
|
|
760
|
+
const peer = live.find((x) => x.status?.sessionId === id);
|
|
761
|
+
if (peer?.status?.hidden) await putAway(id, { force, peer }).catch((e) => { if (!/对应的终端/.test(e.message)) throw e; });
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
await api("/api/sessions/archive", { method: "POST", body: { ids, archived } });
|
|
765
|
+
for (const s of ws.sessions) if (ids.includes(s.id)) s.archived = archived ? Date.now() : undefined;
|
|
766
|
+
drawWorkspace();
|
|
767
|
+
toast(archived ? `已归档${ids.length > 1 ? ` ${ids.length} 个会话` : ""}:在「全部会话 → 已归档」里可以找回` : "已取消归档");
|
|
768
|
+
loadWorkspace({ afterPending: true });
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// A conversation the console runs (taken up when it was opened) is let go of, its turn stopped if `force`: before it
|
|
772
|
+
// is archived, deleted or continued in a terminal. Resolves once it is gone.
|
|
773
|
+
async function putAway(sessionId, { force = false, peer } = {}) {
|
|
774
|
+
const l = peer || (await api("/api/live")).sessions.find((x) => x.status?.sessionId === sessionId);
|
|
775
|
+
if (!l) return;
|
|
776
|
+
try { await api(`/api/live/${l.peerId}/end`, { method: "POST", body: { force } }); } catch (e) {
|
|
777
|
+
if (!/不在运行/.test(e.message)) throw e; // (gone meanwhile: what was wanted)
|
|
778
|
+
}
|
|
779
|
+
for (let i = 0; i < 20; i++) {
|
|
780
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
781
|
+
if (!(await api("/api/live")).sessions.some((x) => x.status?.sessionId === sessionId)) return;
|
|
782
|
+
}
|
|
783
|
+
throw new Error("会话尚未结束,请稍后再试");
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
async function copySessionId(id) {
|
|
787
|
+
try {
|
|
788
|
+
await navigator.clipboard.writeText(id);
|
|
789
|
+
toast("已复制 Session ID");
|
|
790
|
+
} catch {
|
|
791
|
+
prompt("请手动复制 Session ID", id);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function sidebarSessionMenu(button, it) {
|
|
796
|
+
const items = [
|
|
797
|
+
{ label: it.archived ? "取消归档" : "归档", value: "archive" },
|
|
798
|
+
{ label: "复制 Session ID", value: "copy" },
|
|
799
|
+
{ label: "删除对话", value: "delete", danger: true },
|
|
800
|
+
];
|
|
801
|
+
popMenu(button, [{ key: "session", title: "", items }], async (_, value) => {
|
|
802
|
+
if (value === "copy") return copySessionId(it.id);
|
|
803
|
+
const s = ws.sessions.find((s) => s.id === it.id) || it;
|
|
804
|
+
const peer = ws.live.find((l) => l.status?.sessionId === it.id);
|
|
805
|
+
const busy = Boolean(peer?.status?.busy || working({ peer }));
|
|
806
|
+
const archiving = value === "archive" && !s.archived;
|
|
807
|
+
try {
|
|
808
|
+
if (value === "archive") {
|
|
809
|
+
if (archiving && busy && peer?.status?.hidden && !confirm("它正在工作,归档会停止当前任务。确定归档?")) return;
|
|
810
|
+
await archive([it.id], archiving, { force: busy });
|
|
811
|
+
} else {
|
|
812
|
+
if (!confirm(`删除「${it.title}」?会先移到回收站,保留 7 天。${busy ? "它正在工作,会先停止。" : ""}`)) return;
|
|
813
|
+
await putAway(it.id, { force: busy });
|
|
814
|
+
await api(`/api/sessions/${encodeURIComponent(it.dir)}/${encodeURIComponent(it.id)}`, { method: "DELETE" });
|
|
815
|
+
toast("已移到回收站");
|
|
816
|
+
await loadWorkspace({ afterPending: true });
|
|
817
|
+
}
|
|
818
|
+
if ((value === "delete" || archiving) && (location.hash === it.href || location.hash === it.alt)) location.hash = "#/new";
|
|
819
|
+
else if (/^#\/sessions(?:\?|$)/.test(location.hash)) route();
|
|
820
|
+
} catch (e) { fail(e); }
|
|
821
|
+
}, { dropdown: true });
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function wireSidebar() {
|
|
825
|
+
const box = $("#ws");
|
|
826
|
+
const tip = $("#tip");
|
|
827
|
+
box.addEventListener("click", (e) => {
|
|
828
|
+
const menu = e.target.closest("[data-session-menu]");
|
|
829
|
+
if (menu) {
|
|
830
|
+
tip.classList.add("hidden");
|
|
831
|
+
const it = ws.tips.get(menu.closest("[data-tip]").dataset.tip);
|
|
832
|
+
if (it) sidebarSessionMenu(menu, it);
|
|
833
|
+
return;
|
|
834
|
+
}
|
|
835
|
+
const pm = e.target.closest("[data-pmenu]");
|
|
836
|
+
if (pm) {
|
|
837
|
+
const key = pm.dataset.pmenu;
|
|
838
|
+
const ids = ws.sessions.filter((s) => !s.archived && !s.running && projectKey(s.cwd || s.dir) === key).map((s) => s.id);
|
|
839
|
+
const items = [];
|
|
840
|
+
if (ws.projectOpen.explorer) items.push({ label: "在资源管理器中打开", value: "explorer" });
|
|
841
|
+
if (ws.projectOpen.vscode) items.push({ label: "在 VS Code 中打开", value: "vscode" });
|
|
842
|
+
items.push({ label: ids.length ? `归档全部会话(${ids.length} 个)` : "没有可以归档的会话", description: ids.length ? "从工作区收起,内容保留,可以在「全部会话 → 已归档」里找回" : "运行中的会话不能归档", value: "all" });
|
|
843
|
+
popMenu(pm, [{ key: "p", title: "", items }], async (_, value) => {
|
|
844
|
+
try {
|
|
845
|
+
if (value === "all") {
|
|
846
|
+
if (ids.length && confirm(`归档这个项目的 ${ids.length} 个会话?`)) await archive(ids);
|
|
847
|
+
} else {
|
|
848
|
+
await api("/api/projects/open", { method: "POST", body: { cwd: pm.dataset.cwd, target: value } });
|
|
849
|
+
toast(value === "vscode" ? "已在运行 claude-pro 的电脑上打开 VS Code" : "已在运行 claude-pro 的电脑上打开资源管理器");
|
|
850
|
+
}
|
|
851
|
+
} catch (e) { fail(e); }
|
|
852
|
+
}, { dropdown: true });
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
const add = e.target.closest("[data-add]");
|
|
856
|
+
if (add) {
|
|
857
|
+
// a new session in this project, at once (its first message is typed in its live view)
|
|
858
|
+
if (add.disabled) return;
|
|
859
|
+
add.disabled = true;
|
|
860
|
+
startSession(add.dataset.add, "", []).catch(fail).finally(() => { add.disabled = false; });
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
const f = e.target.closest("[data-folder]"), x = e.target.closest("[data-expand]");
|
|
864
|
+
if (f) {
|
|
865
|
+
const key = f.dataset.folder;
|
|
866
|
+
if (ws.closed.has(key)) ws.closed.delete(key); else ws.closed.add(key);
|
|
867
|
+
localStorage.setItem("cpWsClosed", JSON.stringify([...ws.closed]));
|
|
868
|
+
drawWorkspace();
|
|
869
|
+
}
|
|
870
|
+
if (x) { ws.expanded.add(x.dataset.expand); drawWorkspace(); }
|
|
871
|
+
});
|
|
872
|
+
box.addEventListener("mouseover", (e) => {
|
|
873
|
+
const a = e.target.closest("[data-tip]");
|
|
874
|
+
const it = a && ws.tips.get(a.dataset.tip);
|
|
875
|
+
if (!it || sidebarMenuOpen() || e.target.closest("[data-session-menu]")) { tip.classList.add("hidden"); return; }
|
|
876
|
+
const [cls, label] = working(it) ? liveState(it.peer.status) : ["", ""];
|
|
877
|
+
const st = it.peer?.status || {};
|
|
878
|
+
tip.innerHTML = `<strong>${esc(it.title)}</strong><div class="tip-path">${esc(shortPath(it.cwd))}</div><div>${it.peer ? esc([st.model, st.cost != null ? fmtUsd(st.cost) : "", st.context?.window ? `上下文 ${fmtTokens(st.context.used)}/${fmtTokens(st.context.window)}` : ""].filter(Boolean).join(" · ")) : esc(ago(it.mtime))}</div>${label || (it.peer && !st.hidden) ? `<div class="tip-state">${label ? `<span class="ws-dot ${cls}"></span>${esc(label)}` : ""}${it.peer && !st.hidden ? `${label ? " · " : ""}在终端窗口里运行` : ""}</div>` : ""}`;
|
|
879
|
+
const r = a.getBoundingClientRect();
|
|
880
|
+
tip.classList.remove("hidden");
|
|
881
|
+
tip.style.left = `${r.right + 8}px`;
|
|
882
|
+
tip.style.top = `${Math.min(window.innerHeight - tip.offsetHeight - 8, r.top)}px`;
|
|
883
|
+
});
|
|
884
|
+
box.addEventListener("mouseleave", () => tip.classList.add("hidden"));
|
|
885
|
+
box.addEventListener("scroll", () => {
|
|
886
|
+
tip.classList.add("hidden");
|
|
887
|
+
if (sidebarMenuOpen()) closeMenu?.();
|
|
888
|
+
});
|
|
889
|
+
$("#wsSearchBtn").addEventListener("click", () => {
|
|
890
|
+
const input = $("#wsSearch");
|
|
891
|
+
input.classList.toggle("hidden");
|
|
892
|
+
if (!input.classList.contains("hidden")) input.focus(); else { input.value = ""; ws.q = ""; drawWorkspace(); }
|
|
893
|
+
});
|
|
894
|
+
$("#wsSearch").addEventListener("input", (e) => { ws.q = e.target.value.trim(); drawWorkspace(); });
|
|
895
|
+
$("#wsRefresh").addEventListener("click", () => loadWorkspace());
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// ---------------------------------------------------------------- the message box (new conversation and live)
|
|
899
|
+
|
|
900
|
+
// What was typed and not sent, per box (`draftKey`): kept when the page shows another conversation and back. The text
|
|
901
|
+
// also in localStorage (it survives a reload), the images only in memory (their object URLs live as long as the page).
|
|
902
|
+
const draftImages = new Map();
|
|
903
|
+
const draftText = (key) => (key ? localStorage.getItem(`cpDraft:${key}`) || "" : "");
|
|
904
|
+
function saveDraft(key, text, images) {
|
|
905
|
+
if (!key) return;
|
|
906
|
+
if (text) localStorage.setItem(`cpDraft:${key}`, text); else localStorage.removeItem(`cpDraft:${key}`);
|
|
907
|
+
if (images.length) draftImages.set(key, images); else draftImages.delete(key);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// A rounded box with the text, images (pasted, dropped or added with +), what goes left and right of the send button.
|
|
911
|
+
// onSend(text, images) resolves when sent (the box is emptied) or throws (it is kept).
|
|
912
|
+
function composer(box, { placeholder, onSend, left = "", right = "", dropZone = box, draftKey = "" }) {
|
|
913
|
+
box.innerHTML = `<form class="composer"><div class="thumbs hidden"></div><textarea rows="1" placeholder="${esc(placeholder)}"></textarea>
|
|
914
|
+
<div class="composer-bar"><button type="button" class="icon-btn" data-add title="添加图片(也可以粘贴或拖进来)" aria-label="添加图片">${ICON.add}</button><input type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple hidden>
|
|
915
|
+
<span class="composer-left">${left}</span><span class="grow"></span><span class="composer-right">${right}</span>
|
|
916
|
+
<button type="button" class="round-btn stop hidden" data-stop title="停止当前任务">${ICON.stop}</button><button type="submit" class="round-btn" data-send title="发送(Enter)" disabled>${ICON.send}</button></div></form>`;
|
|
917
|
+
const form = $("form", box), input = $("textarea", box), thumbs = $(".thumbs", box), file = $("input[type=file]", box), send = $("[data-send]", box);
|
|
918
|
+
let images = [...(draftImages.get(draftKey) || [])];
|
|
919
|
+
let sending = false;
|
|
920
|
+
const keep = () => saveDraft(draftKey, input.value, images);
|
|
921
|
+
const ready = () => { send.disabled = sending || (!input.value.trim() && !images.length); };
|
|
922
|
+
const autosize = () => { input.style.height = "auto"; input.style.height = `${Math.min(240, input.scrollHeight)}px`; ready(); };
|
|
923
|
+
const paint = () => {
|
|
924
|
+
thumbs.classList.toggle("hidden", !images.length);
|
|
925
|
+
thumbs.innerHTML = images.map((img, i) => `<div class="thumb"><img src="${img.url}" alt="图片 ${i + 1}"><button type="button" data-drop="${i}" title="移除" aria-label="移除">×</button></div>`).join("");
|
|
926
|
+
keep();
|
|
927
|
+
ready();
|
|
928
|
+
};
|
|
929
|
+
async function add(files) {
|
|
930
|
+
if (sending) return;
|
|
931
|
+
const list = [...files].filter((f) => f && f.type.startsWith("image/"));
|
|
932
|
+
for (const f of list) {
|
|
933
|
+
if (images.length >= MAX_IMAGES) { toast(`一条消息最多 ${MAX_IMAGES} 张图片`, "error"); break; }
|
|
934
|
+
try { images.push(await prepareImage(f)); } catch (err) { fail(err); }
|
|
935
|
+
}
|
|
936
|
+
paint();
|
|
937
|
+
input.focus();
|
|
938
|
+
}
|
|
939
|
+
thumbs.addEventListener("click", (e) => {
|
|
940
|
+
const b = e.target.closest("[data-drop]");
|
|
941
|
+
if (!b || sending) return;
|
|
942
|
+
const [gone] = images.splice(Number(b.dataset.drop), 1);
|
|
943
|
+
if (gone) URL.revokeObjectURL(gone.url);
|
|
944
|
+
paint();
|
|
945
|
+
});
|
|
946
|
+
$("[data-add]", box).addEventListener("click", () => file.click());
|
|
947
|
+
file.addEventListener("change", async () => { await add(file.files); file.value = ""; });
|
|
948
|
+
input.addEventListener("input", () => { autosize(); keep(); });
|
|
949
|
+
input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); form.requestSubmit(); } });
|
|
950
|
+
input.addEventListener("paste", (e) => {
|
|
951
|
+
const files = [...(e.clipboardData?.items || [])].filter((it) => it.kind === "file").map((it) => it.getAsFile());
|
|
952
|
+
if (files.some((f) => f?.type.startsWith("image/"))) { e.preventDefault(); add(files); }
|
|
953
|
+
});
|
|
954
|
+
dropZone.addEventListener("dragover", (e) => { if ([...(e.dataTransfer?.types || [])].includes("Files")) { e.preventDefault(); box.classList.add("dropping"); } });
|
|
955
|
+
dropZone.addEventListener("dragleave", (e) => { if (!dropZone.contains(e.relatedTarget)) box.classList.remove("dropping"); });
|
|
956
|
+
dropZone.addEventListener("drop", (e) => { box.classList.remove("dropping"); if (e.dataTransfer?.files?.length) { e.preventDefault(); add(e.dataTransfer.files); } });
|
|
957
|
+
form.addEventListener("submit", async (e) => {
|
|
958
|
+
e.preventDefault();
|
|
959
|
+
const text = input.value;
|
|
960
|
+
if (sending || (!text.trim() && !images.length)) return;
|
|
961
|
+
sending = true;
|
|
962
|
+
input.readOnly = true;
|
|
963
|
+
ready();
|
|
964
|
+
try {
|
|
965
|
+
await onSend(text, images.map(({ media_type, data }) => ({ media_type, data })));
|
|
966
|
+
input.value = "";
|
|
967
|
+
for (const img of images) URL.revokeObjectURL(img.url);
|
|
968
|
+
images = [];
|
|
969
|
+
paint(); // (the draft goes with it)
|
|
970
|
+
autosize();
|
|
971
|
+
} catch (err) { fail(err); } finally { sending = false; input.readOnly = false; ready(); }
|
|
972
|
+
});
|
|
973
|
+
input.value = draftText(draftKey);
|
|
974
|
+
if (images.length) paint();
|
|
975
|
+
requestAnimationFrame(autosize); // (measured once the box is on the page)
|
|
976
|
+
return {
|
|
977
|
+
input,
|
|
978
|
+
submit: () => form.requestSubmit(),
|
|
979
|
+
left: $(".composer-left", box),
|
|
980
|
+
right: $(".composer-right", box),
|
|
981
|
+
setBusy(busy) { $("[data-stop]", box).classList.toggle("hidden", !busy); },
|
|
982
|
+
onStop(fn) { $("[data-stop]", box).addEventListener("click", fn); },
|
|
983
|
+
// (images of a draft stay: they come back with it)
|
|
984
|
+
dispose() { for (const img of images) if (!draftImages.get(draftKey)?.includes(img)) URL.revokeObjectURL(img.url); },
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// A small menu next to `anchor`: onPick(section, value).
|
|
989
|
+
function popMenu(anchor, sections, onPick, { dropdown = false } = {}) {
|
|
990
|
+
const wasOpen = anchor.getAttribute("aria-expanded") === "true";
|
|
991
|
+
closeMenu?.();
|
|
992
|
+
if (wasOpen) return;
|
|
993
|
+
const pop = document.createElement("div");
|
|
994
|
+
pop.className = "pop";
|
|
995
|
+
pop.innerHTML = sections.map((s) => `<div class="pop-head">${esc(s.title)}</div>${s.items.map((it, i) => `<button type="button" data-s="${esc(s.key)}" data-i="${i}" class="${it.current ? "current" : ""}${it.danger ? " danger" : ""}"><span>${esc(it.label)}</span>${it.description ? `<small>${esc(it.description)}</small>` : ""}</button>`).join("")}`).join("");
|
|
996
|
+
document.body.appendChild(pop);
|
|
997
|
+
const r = anchor.getBoundingClientRect();
|
|
998
|
+
pop.style.left = `${Math.max(8, Math.min(window.innerWidth - pop.offsetWidth - 8, r.right - pop.offsetWidth))}px`;
|
|
999
|
+
const below = dropdown && r.bottom + pop.offsetHeight + 14 <= window.innerHeight;
|
|
1000
|
+
pop.style.top = `${below ? r.bottom + 6 : Math.max(8, r.top - pop.offsetHeight - 6)}px`;
|
|
1001
|
+
const close = (focus = false) => {
|
|
1002
|
+
pop.remove();
|
|
1003
|
+
document.removeEventListener("pointerdown", outside);
|
|
1004
|
+
document.removeEventListener("keydown", escape);
|
|
1005
|
+
closeMenu = null;
|
|
1006
|
+
if (dropdown) {
|
|
1007
|
+
anchor.setAttribute("aria-expanded", "false");
|
|
1008
|
+
if (focus) anchor.focus({ preventScroll: true });
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
const outside = (e) => { if (!pop.contains(e.target) && !anchor.contains(e.target)) close(); };
|
|
1012
|
+
const escape = (e) => { if (e.key === "Escape") { e.preventDefault(); close(true); } };
|
|
1013
|
+
closeMenu = close;
|
|
1014
|
+
document.addEventListener("pointerdown", outside);
|
|
1015
|
+
document.addEventListener("keydown", escape);
|
|
1016
|
+
if (dropdown) {
|
|
1017
|
+
anchor.setAttribute("aria-expanded", "true");
|
|
1018
|
+
$("button", pop)?.focus({ preventScroll: true });
|
|
1019
|
+
}
|
|
1020
|
+
pop.addEventListener("click", (e) => {
|
|
1021
|
+
const b = e.target.closest("button");
|
|
1022
|
+
if (!b) return;
|
|
1023
|
+
const s = sections.find((x) => x.key === b.dataset.s);
|
|
1024
|
+
close(true);
|
|
1025
|
+
onPick(s.key, s.items[Number(b.dataset.i)].value);
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// ---------------------------------------------------------------- 新会话
|
|
1030
|
+
|
|
1031
|
+
let hasNativeFolderPicker = false;
|
|
1032
|
+
function browseProjectDirectories(initial, onSelect) {
|
|
1033
|
+
const m = modal({ title: "选择项目目录", sub: "目录位于运行 claude-pro 的电脑上", body: `<div class="actions"><button type="button" class="button secondary small" data-dir-root>位置</button><button type="button" class="button secondary small" data-dir-up hidden>上一级</button></div><p class="mono" data-dir-path></p><div class="panel" data-dir-list aria-live="polite"></div>`, foot: `<button type="button" class="button" data-dir-use disabled>选择此目录</button>` });
|
|
1034
|
+
let listing = null, request = 0;
|
|
1035
|
+
const box = $("[data-dir-list]", m.el), use = $("[data-dir-use]", m.el), up = $("[data-dir-up]", m.el);
|
|
1036
|
+
async function load(cwd) {
|
|
1037
|
+
const id = ++request;
|
|
1038
|
+
box.textContent = "正在读取…";
|
|
1039
|
+
use.disabled = true;
|
|
1040
|
+
try {
|
|
1041
|
+
const next = await api(`/api/projects/directories${cwd ? `?cwd=${encodeURIComponent(cwd)}` : ""}`);
|
|
1042
|
+
if (id !== request || !m.el.isConnected) return;
|
|
1043
|
+
listing = next;
|
|
1044
|
+
$("[data-dir-path]", m.el).textContent = next.cwd || "选择一个位置";
|
|
1045
|
+
up.hidden = !next.parent;
|
|
1046
|
+
use.disabled = !next.cwd;
|
|
1047
|
+
box.innerHTML = next.dirs.map((d, n) => `<div class="file-row"><button type="button" class="button secondary" data-dir="${n}">${ICON.folder}<span>${esc(d.name)}</span></button></div>`).join("") || `<div class="empty">没有子目录</div>`;
|
|
1048
|
+
} catch (e) {
|
|
1049
|
+
if (id === request) box.textContent = e.message;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
m.el.addEventListener("click", (e) => {
|
|
1053
|
+
const b = e.target.closest("button");
|
|
1054
|
+
if (!b) return;
|
|
1055
|
+
if (b.hasAttribute("data-dir-root")) load(null);
|
|
1056
|
+
else if (b.hasAttribute("data-dir-up")) load(listing?.parent);
|
|
1057
|
+
else if (b.hasAttribute("data-dir") && listing?.dirs[b.dataset.dir]) load(listing.dirs[b.dataset.dir].path);
|
|
1058
|
+
else if (b.hasAttribute("data-dir-use") && listing?.cwd) { onSelect(listing.cwd); m.close(); }
|
|
1059
|
+
});
|
|
1060
|
+
load(initial || null);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
async function newView() {
|
|
1064
|
+
const el = page(`<div class="chat-page"><div class="welcome"><div class="welcome-logo">c</div><h1>你好,今天要做什么?</h1><p class="muted">选一个项目目录,告诉它要做什么:你在这里看着它工作、随时给它发消息。</p></div><div class="chat-composer" id="ncomp"></div></div>`, "chat");
|
|
1065
|
+
let projects = [];
|
|
1066
|
+
try { projects = (await api("/api/projects")).projects; } catch { /* the folder chooser still works */ }
|
|
1067
|
+
if (!el.isConnected) return;
|
|
1068
|
+
let dir = localStorage.getItem("cpNewDir") || projects[0]?.cwd || "";
|
|
1069
|
+
let model, effort, configRequest = 0;
|
|
1070
|
+
const c = composer($("#ncomp", el), {
|
|
1071
|
+
placeholder: "描述你要它做的事,/命令 也可以。Enter 发送,Shift+Enter 换行",
|
|
1072
|
+
left: `<button type="button" class="chip" id="ndir" title="会话在哪个目录里工作">${ICON.folder}<span></span>${ICON.caret}</button>`,
|
|
1073
|
+
right: `<button type="button" class="chip" id="nmodel" title="选择模型"><span>模型</span>${ICON.caret}</button><button type="button" class="chip" id="neffort" title="选择思考强度"><span>思考强度</span>${ICON.caret}</button>`,
|
|
1074
|
+
onSend: async (text, images) => startSession(dir, text, images, { model, effort }),
|
|
1075
|
+
draftKey: "new",
|
|
1076
|
+
});
|
|
1077
|
+
const chip = $("#ndir", el);
|
|
1078
|
+
const paintDir = () => { $("span", chip).textContent = dir ? baseName(dir) : "选择目录"; chip.title = dir ? `会话在 ${dir} 里工作` : "选择目录"; };
|
|
1079
|
+
paintDir();
|
|
1080
|
+
const modelChip = $("#nmodel", el), effortChip = $("#neffort", el);
|
|
1081
|
+
const options = (kind) => api(`/api/live/new/options?${new URLSearchParams({ cwd: dir, kind, ...(model ? { model } : {}), ...(effort ? { effort } : {}) })}`);
|
|
1082
|
+
function paintChoices(info) {
|
|
1083
|
+
$("span", modelChip).textContent = info.model || "模型";
|
|
1084
|
+
modelChip.title = `选择模型${info.model ? `:${info.model}` : ""}`;
|
|
1085
|
+
$("span", effortChip).textContent = info.effort === "auto" || !info.effort ? "思考强度:自动" : `思考强度:${info.effort}`;
|
|
1086
|
+
}
|
|
1087
|
+
async function refreshChoices() {
|
|
1088
|
+
const seq = ++configRequest;
|
|
1089
|
+
try { const info = await options("summary"); if (el.isConnected && seq === configRequest) paintChoices(info); } catch { /* the menus can try again */ }
|
|
1090
|
+
}
|
|
1091
|
+
const selectDir = (value) => {
|
|
1092
|
+
if (!value || !el.isConnected) return;
|
|
1093
|
+
dir = value;
|
|
1094
|
+
localStorage.setItem("cpNewDir", dir);
|
|
1095
|
+
paintDir();
|
|
1096
|
+
refreshChoices();
|
|
1097
|
+
};
|
|
1098
|
+
for (const [anchor, kind] of [[modelChip, "models"], [effortChip, "efforts"]]) {
|
|
1099
|
+
anchor.addEventListener("click", async () => {
|
|
1100
|
+
const currentDir = dir;
|
|
1101
|
+
anchor.disabled = true;
|
|
1102
|
+
try {
|
|
1103
|
+
const info = await options(kind);
|
|
1104
|
+
if (!el.isConnected || dir !== currentDir) return;
|
|
1105
|
+
const isModel = kind === "models";
|
|
1106
|
+
const current = isModel ? info.modelChoice : info.effortChoice;
|
|
1107
|
+
const items = info[kind].map((item) => ({ ...item, label: item.value === "default" ? "项目默认" : item.label, current: item.value === current }));
|
|
1108
|
+
popMenu(anchor, [{ key: kind, title: isModel ? "模型" : "思考强度", items }], (_, value) => {
|
|
1109
|
+
if (isModel) { if (model !== value) effort = undefined; model = value; }
|
|
1110
|
+
else effort = value;
|
|
1111
|
+
refreshChoices();
|
|
1112
|
+
});
|
|
1113
|
+
} catch (e) { fail(e); } finally { anchor.disabled = false; }
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
refreshChoices();
|
|
1117
|
+
chip.addEventListener("click", () => {
|
|
1118
|
+
popMenu(chip, [
|
|
1119
|
+
{ key: "dir", title: "最近的项目", items: projects.slice(0, 12).map((p) => ({ label: baseName(p.cwd), description: shortPath(p.cwd), value: p.cwd, current: p.cwd === dir })) },
|
|
1120
|
+
{ key: "other", title: "", items: [{ label: "其他目录…", value: "" }] },
|
|
1121
|
+
], async (key, value) => {
|
|
1122
|
+
if (key !== "other") return selectDir(value);
|
|
1123
|
+
if (!hasNativeFolderPicker) return browseProjectDirectories(dir, selectDir);
|
|
1124
|
+
chip.disabled = true;
|
|
1125
|
+
try { selectDir((await api("/api/projects/pick", { method: "POST", body: {} })).cwd); }
|
|
1126
|
+
catch (e) {
|
|
1127
|
+
if (e.status === 409) fail(e);
|
|
1128
|
+
else if (el.isConnected) browseProjectDirectories(dir, selectDir);
|
|
1129
|
+
} finally { chip.disabled = false; }
|
|
1130
|
+
});
|
|
1131
|
+
});
|
|
1132
|
+
if (!mobileLayout.matches) c.input.focus();
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
const pendingFirstSends = new Set();
|
|
1136
|
+
function queueFirstMessage(peerId, text, images = []) {
|
|
1137
|
+
const key = `live:${peerId}`;
|
|
1138
|
+
if (draftText(key) || draftImages.has(key)) throw new Error("该会话已有未发送的草稿,本条消息仍保留在当前输入框");
|
|
1139
|
+
saveDraft(key, text, images.map((img) => ({ ...img, url: `data:${img.media_type};base64,${img.data}` })));
|
|
1140
|
+
pendingFirstSends.add(peerId);
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
// A new session in `dir`, run by the console; it is opened here and the message goes to it.
|
|
1144
|
+
async function startSession(dir, text, images, choices = {}) {
|
|
1145
|
+
if (!dir) throw new Error("先选一个目录");
|
|
1146
|
+
const here = location.hash;
|
|
1147
|
+
const before = new Set(ws.live.map((r) => r.peerId));
|
|
1148
|
+
const r = await api("/api/live/new", { method: "POST", body: { cwd: dir, ...choices } });
|
|
1149
|
+
localStorage.setItem("cpNewDir", r.cwd);
|
|
1150
|
+
const until = Date.now() + 30_000;
|
|
1151
|
+
let found = r.peerId ? { peerId: r.peerId } : null;
|
|
1152
|
+
while (!found && Date.now() < until) {
|
|
1153
|
+
await new Promise((res) => setTimeout(res, 1000));
|
|
1154
|
+
try { found = (await api("/api/live")).sessions.find((x) => !before.has(x.peerId) && projectKey(x.status?.cwd || x.cwd) === projectKey(r.cwd)); } catch { /* again */ }
|
|
1155
|
+
}
|
|
1156
|
+
if (!found) throw new Error("会话 30 秒内没有上线:可能是启动出错了,在终端里运行 claude-pro 看看");
|
|
1157
|
+
if (text || images?.length) queueFirstMessage(found.peerId, text, images);
|
|
1158
|
+
loadWorkspace({ afterPending: true });
|
|
1159
|
+
if (location.hash === here) location.hash = `#/live/${found.peerId}`;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// ---------------------------------------------------------------- a running session, live
|
|
1163
|
+
|
|
1164
|
+
function liveView(peerId) {
|
|
1165
|
+
const el = page(`<div class="chat-page">
|
|
1166
|
+
<header class="chat-head"><div class="chat-titles"><h2 id="ltitle">连接中…</h2><div class="chat-sub" id="lsub"></div></div><span id="lconn" class="pill warn" hidden></span><button type="button" class="icon-btn" id="lmenu" title="更多">${ICON.more}</button></header>
|
|
1167
|
+
<div class="chat-scroll" id="lscroll"><div class="chat-log" id="log"></div></div>
|
|
1168
|
+
<div class="chat-foot"><div class="chat-extra"><div class="todos" id="ltodos"></div><div class="queue" id="lqueue"></div><div id="ldialog"></div></div>
|
|
1169
|
+
<div class="status-line" id="lstatus"></div><div class="chat-composer" id="lcomp"></div><div class="chat-stats" id="lstats"></div></div>
|
|
1170
|
+
</div>`, "chat");
|
|
1171
|
+
const log = $("#log", el);
|
|
1172
|
+
const scroller = $("#lscroll", el);
|
|
1173
|
+
const elements = new Map();
|
|
1174
|
+
const full = new Map();
|
|
1175
|
+
let state = hydrate([]);
|
|
1176
|
+
let status = {};
|
|
1177
|
+
let statusAt = Date.now();
|
|
1178
|
+
let dialogShown = null;
|
|
1179
|
+
const post = (type, body = {}) => api(`/api/live/${peerId}/${type}`, { method: "POST", body });
|
|
1180
|
+
const near = () => scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 140;
|
|
1181
|
+
const c = composer($("#lcomp", el), {
|
|
1182
|
+
placeholder: "发消息继续这个对话,/命令、!命令、@会话 都可以。Enter 发送,Shift+Enter 换行",
|
|
1183
|
+
right: `<button type="button" class="chip" id="lmodel" title="切换模型"><span></span>${ICON.caret}</button><button type="button" class="chip" id="leffort" title="切换推理强度"><span></span>${ICON.caret}</button>`,
|
|
1184
|
+
dropZone: el,
|
|
1185
|
+
draftKey: `live:${peerId}`,
|
|
1186
|
+
onSend: async (text, images) => {
|
|
1187
|
+
if (/^\s*\/(exit|quit|restart|reload|update)(\s|$)/i.test(text)) throw new Error("结束、重启会话和更新 claude-pro 只能在终端里操作");
|
|
1188
|
+
const r = await post("send", { text, images });
|
|
1189
|
+
if (r.queued) toast("会话正忙:已排队,当前任务结束后处理");
|
|
1190
|
+
setTimeout(() => { scroller.scrollTop = scroller.scrollHeight; }, 50);
|
|
1191
|
+
},
|
|
1192
|
+
});
|
|
1193
|
+
c.onStop(() => post("interrupt").catch(fail));
|
|
1194
|
+
// the model and the reasoning effort, each its own menu
|
|
1195
|
+
const choose = (key, title, list) => async (e) => {
|
|
1196
|
+
const anchor = e.currentTarget;
|
|
1197
|
+
let o;
|
|
1198
|
+
try { o = await post("options"); } catch (err) { return fail(err); }
|
|
1199
|
+
const items = (o[list] || []).map((m) => ({ label: m.label || m.value, description: m.description || "", value: m.value, current: m.current }));
|
|
1200
|
+
if (!items.length) return toast(key === "effort" ? "这个模型不能调推理强度" : "没有可选的模型");
|
|
1201
|
+
popMenu(anchor, [{ key, title, items }], (k, value) => post("send", { text: `/${k} ${value}` }).catch(fail));
|
|
1202
|
+
};
|
|
1203
|
+
$("#lmodel", el).addEventListener("click", choose("model", "模型", "models"));
|
|
1204
|
+
$("#leffort", el).addEventListener("click", choose("effort", "推理强度", "efforts"));
|
|
1205
|
+
$("#lmenu", el).addEventListener("click", (e) => {
|
|
1206
|
+
const known = ws.sessions.find((s) => s.id === status.sessionId);
|
|
1207
|
+
popMenu(e.currentTarget, [{ key: "a", title: "", items: [
|
|
1208
|
+
{ label: "导出 Markdown", value: "export" },
|
|
1209
|
+
{ label: "归档", description: "从工作区收起,内容保留", value: "archive" },
|
|
1210
|
+
{ label: "删除", description: "先进回收站,7 天内可以恢复", value: "delete" },
|
|
1211
|
+
] }], async (key, value) => {
|
|
1212
|
+
if (!known) return toast("这个对话还没有内容");
|
|
1213
|
+
const sessionId = status.sessionId;
|
|
1214
|
+
const busy = Boolean(status.busy || status.turn || status.dialog);
|
|
1215
|
+
const base = known ? `/api/sessions/${encodeURIComponent(known.dir)}/${encodeURIComponent(known.id)}` : "";
|
|
1216
|
+
try {
|
|
1217
|
+
if (value === "export") location.href = `${base}/export`;
|
|
1218
|
+
if (value === "archive") {
|
|
1219
|
+
if (busy && !confirm("它正在工作,归档会停止当前任务。确定归档?")) return;
|
|
1220
|
+
await archive([sessionId], true, { force: busy });
|
|
1221
|
+
location.hash = "#/new";
|
|
1222
|
+
}
|
|
1223
|
+
if (value === "delete") {
|
|
1224
|
+
if (!confirm(`删除「${status.title || known.title}」?会先移到回收站,保留 7 天。${busy ? "它正在工作,会先停止。" : ""}`)) return;
|
|
1225
|
+
await putAway(sessionId, { force: busy });
|
|
1226
|
+
await api(base, { method: "DELETE" });
|
|
1227
|
+
toast("已移到回收站");
|
|
1228
|
+
await loadWorkspace();
|
|
1229
|
+
location.hash = "#/new";
|
|
1230
|
+
}
|
|
1231
|
+
} catch (err) { fail(err); }
|
|
1232
|
+
});
|
|
1233
|
+
});
|
|
1234
|
+
|
|
1235
|
+
function render(item) {
|
|
1236
|
+
let node = elements.get(item);
|
|
1237
|
+
const html = itemHtml(item, { full, canExpand: true, image: (n) => `/api/live/${peerId}/image/${n}` });
|
|
1238
|
+
if (!node) {
|
|
1239
|
+
if (!html) return;
|
|
1240
|
+
node = document.createElement("div");
|
|
1241
|
+
node.style.display = "contents";
|
|
1242
|
+
elements.set(item, node);
|
|
1243
|
+
log.appendChild(node);
|
|
1244
|
+
}
|
|
1245
|
+
const open = node.querySelector("details")?.open;
|
|
1246
|
+
node.innerHTML = html;
|
|
1247
|
+
if (open) { const det = node.querySelector("details"); if (det) det.open = true; }
|
|
1248
|
+
if (item.k === "tool" && item.status !== "running") wholes?.observe();
|
|
1249
|
+
}
|
|
1250
|
+
function renderAll() {
|
|
1251
|
+
log.innerHTML = "";
|
|
1252
|
+
elements.clear();
|
|
1253
|
+
for (const it of state.items) render(it);
|
|
1254
|
+
wholes?.observe();
|
|
1255
|
+
if (!state.items.length) log.innerHTML = '<div class="chat-empty">还没有消息:在下面输入,或在它的终端里输入</div>';
|
|
1256
|
+
scroller.scrollTop = scroller.scrollHeight;
|
|
1257
|
+
}
|
|
1258
|
+
function renderStatus() {
|
|
1259
|
+
const s = status;
|
|
1260
|
+
const busy = Boolean(s.turn ?? s.busy);
|
|
1261
|
+
let html = "";
|
|
1262
|
+
if (s.rateWait) html = `<span class="work">⏸ ${esc(s.rateWait.text)}</span>`;
|
|
1263
|
+
else if (busy) {
|
|
1264
|
+
const frames = ["·", "✢", "✳", "✶", "✻", "✽", "✻", "✶", "✳", "✢"];
|
|
1265
|
+
const parts = [fmtDuration((s.elapsed || 0) + Date.now() - statusAt)];
|
|
1266
|
+
if (s.tokens) parts.push(`↓ ${fmtTokens(s.tokens)} tokens`);
|
|
1267
|
+
if (s.aborting) parts.push("正在停止…");
|
|
1268
|
+
html = `<span class="work">${frames[Math.floor(Date.now() / 120) % frames.length]} ${esc(s.verb || "Working")}…</span> <span class="muted">(${parts.join(" · ")})</span>`;
|
|
1269
|
+
}
|
|
1270
|
+
$("#lstatus", el).innerHTML = html;
|
|
1271
|
+
c.setBusy(busy);
|
|
1272
|
+
}
|
|
1273
|
+
function setStatus(next) {
|
|
1274
|
+
status = next || {};
|
|
1275
|
+
statusAt = Date.now();
|
|
1276
|
+
$("#ltitle", el).textContent = status.title || status.name || "claude-pro";
|
|
1277
|
+
$("#lsub", el).textContent = `@${status.name || ""} · ${shortPath(status.cwd || "")}${status.hidden ? "" : " · 在终端窗口里运行"}`;
|
|
1278
|
+
$("#lmodel span", el).textContent = status.model || "模型";
|
|
1279
|
+
$("#leffort span", el).textContent = status.effort || "推理强度";
|
|
1280
|
+
$("#leffort", el).hidden = !status.effort;
|
|
1281
|
+
const stats = [];
|
|
1282
|
+
if (status.context?.window) stats.push(`上下文 ${fmtTokens(status.context.used || 0)} / ${fmtTokens(status.context.window)}(${Math.round(((status.context.used || 0) / status.context.window) * 100)}%)`);
|
|
1283
|
+
if (Number.isFinite(status.cost)) stats.push(`花费 ${fmtUsd(status.cost)}`);
|
|
1284
|
+
if (status.tasks) stats.push(`${status.tasks} 个后台 agent`);
|
|
1285
|
+
$("#lstats", el).textContent = stats.join(" · ");
|
|
1286
|
+
const todos = Array.isArray(status.todos) ? status.todos : [];
|
|
1287
|
+
$("#ltodos", el).innerHTML = todos.length ? `<details open><summary class="muted">待办 ${todos.filter((t) => t.status === "completed").length}/${todos.length}</summary>${todos.map((t) => `<div class="${t.status === "completed" ? "done" : t.status === "in_progress" ? "now" : ""}">${t.status === "completed" ? "☒" : t.status === "in_progress" ? "◼" : "☐"} ${esc(t.content)}</div>`).join("")}</details>` : "";
|
|
1288
|
+
$("#lqueue", el).innerHTML = (status.queue || []).map((q) => `<div>⎿ 排队中:${esc(String(q).replace(/\s+/g, " ").slice(0, 200))}</div>`).join("");
|
|
1289
|
+
renderDialog(status.dialog);
|
|
1290
|
+
renderStatus();
|
|
1291
|
+
}
|
|
1292
|
+
function renderDialog(d) {
|
|
1293
|
+
const box = $("#ldialog", el);
|
|
1294
|
+
if (!d) { box.innerHTML = ""; dialogShown = null; return; }
|
|
1295
|
+
if (dialogShown === d.id) return;
|
|
1296
|
+
dialogShown = d.id;
|
|
1297
|
+
let html = `<div class="dialog-box"><strong>${ansi(d.title || "问题")}</strong>`;
|
|
1298
|
+
if (d.markdown) html += `<div class="md">${md(d.markdown)}</div>`;
|
|
1299
|
+
else if (d.body?.length) html += `<pre style="margin:0;white-space:pre-wrap">${ansiLines(d.body)}</pre>`;
|
|
1300
|
+
if (d.question) html += `<div>${ansi(d.question)}</div>`;
|
|
1301
|
+
if (Array.isArray(d.options)) {
|
|
1302
|
+
html += '<div class="opts">';
|
|
1303
|
+
d.options.forEach((o, i) => {
|
|
1304
|
+
if (o.other) html += `<div class="actions"><input class="dlg-other" placeholder="其他:输入你自己的回答" style="flex:1"><button type="button" class="button small" data-other>发送</button></div>`;
|
|
1305
|
+
else if (d.multi) html += `<label class="opt"><input type="checkbox" value="${i}"> ${ansi(o.label)}${o.description ? `<div class="desc">${ansi(o.description)}</div>` : ""}</label>`;
|
|
1306
|
+
else html += `<button type="button" class="opt" data-i="${i}">${i + 1}. ${ansi(o.label)}${o.description ? `<div class="desc">${ansi(o.description)}</div>` : ""}</button>`;
|
|
1307
|
+
});
|
|
1308
|
+
html += `</div><div class="actions">${d.multi ? '<button type="button" class="button small" data-confirm>确认</button>' : ""}<button type="button" class="button secondary small" data-cancel>取消</button></div>`;
|
|
1309
|
+
} else html += '<div class="muted">这个问题只能在终端里回答。</div><div class="actions"><button type="button" class="button secondary small" data-cancel>取消</button></div>';
|
|
1310
|
+
box.innerHTML = `${html}</div>`;
|
|
1311
|
+
}
|
|
1312
|
+
$("#ldialog", el).addEventListener("click", async (e) => {
|
|
1313
|
+
const b = e.target.closest("button");
|
|
1314
|
+
if (!b || dialogShown == null) return;
|
|
1315
|
+
const checked = $$("#ldialog input[type=checkbox]:checked", el).map((x) => Number(x.value));
|
|
1316
|
+
let body = null;
|
|
1317
|
+
if (b.dataset.i !== undefined) body = { index: Number(b.dataset.i) };
|
|
1318
|
+
else if (b.dataset.confirm !== undefined) body = { indices: checked };
|
|
1319
|
+
else if (b.dataset.other !== undefined) { const text = $(".dlg-other", el)?.value.trim(); if (text) body = { text, indices: checked }; }
|
|
1320
|
+
else if (b.dataset.cancel !== undefined) body = { cancel: true };
|
|
1321
|
+
if (!body) return;
|
|
1322
|
+
try { await post("dialog", { id: dialogShown, ...body }); } catch (err) { fail(err); dialogShown = null; renderDialog(status.dialog); }
|
|
1323
|
+
});
|
|
1324
|
+
const wholes = wholeOutputs(log, async (id) => (await post("output", { id })).text, (id, text) => {
|
|
1325
|
+
full.set(id, text);
|
|
1326
|
+
const item = state.items.find((it) => it.id === id);
|
|
1327
|
+
if (item) render(item);
|
|
1328
|
+
});
|
|
1329
|
+
|
|
1330
|
+
function handle(msg) {
|
|
1331
|
+
if (msg.t === "snapshot") {
|
|
1332
|
+
state = hydrate(msg.items || []);
|
|
1333
|
+
renderAll();
|
|
1334
|
+
if (msg.status) setStatus(msg.status);
|
|
1335
|
+
if (pendingFirstSends.delete(peerId)) {
|
|
1336
|
+
if (status.dialog) toast("消息已保留为草稿:请先完成会话的提示,再发送");
|
|
1337
|
+
else c.submit(); // only once; the composer holds the draft on any unacknowledged send
|
|
1338
|
+
}
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
if (msg.t === "status") { setStatus(msg.status); return; }
|
|
1342
|
+
if (msg.t === "batch") {
|
|
1343
|
+
const stick = near();
|
|
1344
|
+
log.querySelector(".chat-empty")?.remove();
|
|
1345
|
+
for (const ev of msg.events || []) { const it = applyEvent(state, ev); if (it) render(it); }
|
|
1346
|
+
if (stick) scroller.scrollTop = scroller.scrollHeight;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
const conn = $("#lconn", el);
|
|
1350
|
+
const es = new EventSource(`/api/live/${peerId}/events`);
|
|
1351
|
+
// shown only when the page has lost the session (connected is the normal state, not worth a word)
|
|
1352
|
+
es.onopen = () => { conn.hidden = true; };
|
|
1353
|
+
es.onmessage = (e) => { try { handle(JSON.parse(e.data)); } catch { /* skip */ } };
|
|
1354
|
+
es.onerror = () => { conn.textContent = es.readyState === EventSource.CLOSED ? "连接已断开,请刷新页面" : "正在重新连接…"; conn.hidden = false; };
|
|
1355
|
+
const tick = setInterval(renderStatus, 250);
|
|
1356
|
+
cleanup = () => { es.close(); clearInterval(tick); c.dispose(); wholes.disconnect(); };
|
|
1357
|
+
if (!mobileLayout.matches) c.input.focus();
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// ---------------------------------------------------------------- 远程访问
|
|
1361
|
+
|
|
1362
|
+
async function remotePage() {
|
|
1363
|
+
const el = page('<h1>远程访问</h1><p class="sub">在手机或别的电脑上,通过 https://<你的通讯号>.7bit.fun 打开这台电脑的控制台,要输入密码</p><div id="body"><div class="empty">正在加载…</div></div>');
|
|
1364
|
+
let v;
|
|
1365
|
+
try { v = await api("/api/remote"); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
1366
|
+
drawRemote(el, v);
|
|
1367
|
+
const timer = setInterval(async () => { try { const next = await api("/api/remote"); if (JSON.stringify(next.tunnel) !== JSON.stringify(v.tunnel)) { v = next; drawRemote(el, v); } } catch { /* next time */ } }, 3000);
|
|
1368
|
+
cleanup = () => clearInterval(timer);
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
function drawRemote(el, v) {
|
|
1372
|
+
const t = v.tunnel || {};
|
|
1373
|
+
const state = !v.enabled ? ["off", "已关闭"] : t.status === "online" ? ["ok", "已开启"] : t.status === "error" ? ["off", "没有接上"] : ["warn", "正在连接"];
|
|
1374
|
+
const device = (ua) => { const s = String(ua || ""); return /iPhone|iPad/.test(s) ? "iPhone / iPad" : /Android/.test(s) ? "Android" : /Windows/.test(s) ? "Windows" : /Mac OS/.test(s) ? "Mac" : s.slice(0, 40) || "未知设备"; };
|
|
1375
|
+
$("#body", el).innerHTML = `
|
|
1376
|
+
<div class="panel panel-pad"><div class="actions" style="justify-content:space-between">
|
|
1377
|
+
<div><div class="muted" style="font-size:12.5px">状态</div><div style="font-size:18px;font-weight:650;margin-top:2px"><span class="pill ${state[0]}">${state[1]}</span>
|
|
1378
|
+
${t.status === "online" && t.host ? ` <a href="https://${esc(t.host)}" target="_blank" rel="noopener" class="mono" style="font-size:15px">https://${esc(t.host)}</a>` : ""}</div>
|
|
1379
|
+
${t.error ? `<div style="color:var(--danger);font-size:13px;margin-top:4px">${esc(t.error)}</div>` : ""}
|
|
1380
|
+
${!v.gateway ? '<div class="muted" style="font-size:13px;margin-top:4px">远程访问通过 7bit.fun 网关:先在「模型与供应商」里连接 7bit.fun。</div>' : ""}</div>
|
|
1381
|
+
<div class="actions">${v.enabled ? '<button class="button danger" id="rOff">关闭远程访问</button>' : `<button class="button" id="rOn" ${v.hasPassword && v.gateway ? "" : "disabled"}>开启远程访问</button>`}</div></div>
|
|
1382
|
+
<p class="muted" style="font-size:12.5px;margin:12px 0 0">地址用的是你在网关的通讯号(在网关网页「通讯录」里改)。开启后这台电脑的控制台服务常驻后台;电脑休眠或关机时打不开,claude-pro 的任何会话启动时会重新接上。</p></div>
|
|
1383
|
+
<div class="section-head"><div><h2>密码</h2><p>${v.hasPassword ? "已设置。改密码会让所有已登录的设备退出。" : `还没有设置:开启前先设一个(至少 ${v.minPassword} 位)。`}</p></div></div>
|
|
1384
|
+
<form class="panel panel-pad actions" id="rPwForm"><input type="password" id="rPw1" placeholder="新密码" autocomplete="new-password" style="flex:1;min-width:180px"><input type="password" id="rPw2" placeholder="再输一次" autocomplete="new-password" style="flex:1;min-width:180px"><button class="button" type="submit">${v.hasPassword ? "修改密码" : "设置密码"}</button></form>
|
|
1385
|
+
<div class="section-head"><div><h2>已登录的设备</h2><p>${v.sessions.length} 台</p></div>${v.sessions.length ? '<button class="button danger small" id="rLogoutAll">全部退出</button>' : ""}</div>
|
|
1386
|
+
<div class="panel">${v.sessions.length ? `<table class="list"><tbody>${v.sessions.map((s) => `<tr><td>${esc(device(s.ua))}</td><td class="mono">${esc(s.ip || "")}</td><td>最近 ${esc(ago(s.lastSeen))}</td><td class="num muted">${s.remember ? "记住 30 天" : "1 天"}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">没有</div>'}</div>
|
|
1387
|
+
<div class="section-head"><h2>最近的登录</h2></div>
|
|
1388
|
+
<div class="panel">${v.logins.length ? `<table class="list"><tbody>${v.logins.map((l) => `<tr><td>${l.ok ? '<span class="pill ok">成功</span>' : '<span class="pill off">密码错误</span>'}</td><td>${esc(device(l.ua))}</td><td class="mono">${esc(l.ip || "")}</td><td class="num">${esc(fmtTime(l.at))}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">还没有人登录过</div>'}</div>`;
|
|
1389
|
+
const post = async (body, done) => { try { drawRemote(el, await api("/api/remote", { method: "POST", body })); if (done) toast(done); } catch (e) { fail(e); } };
|
|
1390
|
+
$("#rOn", el)?.addEventListener("click", () => post({ enabled: true }, "远程访问已开启,正在连接网关…"));
|
|
1391
|
+
$("#rOff", el)?.addEventListener("click", () => { if (confirm("关闭远程访问?外网就打不开这台电脑的控制台了。")) post({ enabled: false }, "远程访问已关闭"); });
|
|
1392
|
+
$("#rLogoutAll", el)?.addEventListener("click", () => { if (confirm("让所有已登录的设备退出?")) post({ logoutAll: true }, "都已退出"); });
|
|
1393
|
+
$("#rPwForm", el).addEventListener("submit", (e) => {
|
|
1394
|
+
e.preventDefault();
|
|
1395
|
+
const a = $("#rPw1", el).value, b = $("#rPw2", el).value;
|
|
1396
|
+
if (a.length < v.minPassword) return toast(`密码至少 ${v.minPassword} 位`, "error");
|
|
1397
|
+
if (a !== b) return toast("两次输入不一样", "error");
|
|
1398
|
+
post({ password: a }, "密码已保存,所有已登录的设备都已退出");
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
// ---------------------------------------------------------------- 模型与供应商
|
|
1403
|
+
|
|
1404
|
+
async function providers() {
|
|
1405
|
+
const el = page('<h1>模型与供应商</h1><p class="sub">和终端里的 /connect、/model 是同一份配置</p><div id="body"><div class="empty">正在加载…</div></div>');
|
|
1406
|
+
let p;
|
|
1407
|
+
try { p = await api("/api/providers"); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
1408
|
+
drawProviders(el, p);
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
function drawProviders(el, p) {
|
|
1412
|
+
const card = (x) => `<div class="panel prov${x.connected ? " connected" : ""}"><div class="prov-top"><strong>${esc(x.name)}</strong>${x.connected ? '<span class="pill ok">已连接</span>' : ""}</div>
|
|
1413
|
+
<div class="meta">${esc(x.protocol === "openai" ? "OpenAI 协议" : "Anthropic 协议")} · ${esc(x.baseUrl)}</div>
|
|
1414
|
+
${x.connected ? `<div class="meta">Key ${esc(x.key || "(无需)")} · ${x.models.length} 个模型${x.model ? ` · 选的是 ${esc(x.model)}` : ""}</div>` : ""}
|
|
1415
|
+
<div class="actions">${x.connected ? `<button class="button secondary small" data-connect="${esc(x.id)}">更换 Key / 模型</button><button class="button danger small" data-remove="${esc(x.id)}">断开</button>` : `<button class="button small" data-connect="${esc(x.id)}">连接</button>`}${x.keyPage ? `<a class="button secondary small" href="${esc(x.keyPage)}" target="_blank" rel="noopener">获取 Key</a>` : ""}</div></div>`;
|
|
1416
|
+
const connected = [...p.presets, ...p.custom].filter((x) => x.connected);
|
|
1417
|
+
$("#body", el).innerHTML = `<div id="pbody">
|
|
1418
|
+
<div class="section-head"><div><h2>默认模型</h2><p>新会话用的模型和推理强度。会话里的 /model、/effort 只改那一个会话(并记住给下次用)</p></div></div>
|
|
1419
|
+
<div class="panel panel-pad" id="defaults"><div class="muted">正在读取可用模型…</div></div>
|
|
1420
|
+
<div class="section-head"><div><h2>7bit.fun 网关</h2><p>Claude、GPT 等模型,余额、远程控制、跨电脑和通讯录都通过它</p></div></div>
|
|
1421
|
+
<div class="panel prov${p.gateway.connected ? " connected" : ""}" style="max-width:640px"><div class="prov-top"><strong>7bit.fun</strong>${p.gateway.connected ? '<span class="pill ok">已连接</span>' : ""}</div>
|
|
1422
|
+
<div class="meta">${esc(p.gateway.url)}${p.gateway.connected ? ` · Key ${esc(p.gateway.key)}${p.gateway.account?.email ? ` · ${esc(p.gateway.account.email)}` : ""}` : ""}</div>
|
|
1423
|
+
<form class="actions" id="gwForm"><input type="password" id="gwKey" placeholder="${p.gateway.connected ? "粘贴新 Key 来更换" : "粘贴 7bit.fun 的 API Key"}" style="flex:1;min-width:240px" autocomplete="off"><button class="button small" type="submit">${p.gateway.connected ? "更换" : "连接"}</button>${p.gateway.connected ? '<button class="button danger small" type="button" id="gwOut">断开</button>' : ""}<a class="button secondary small" href="${esc(p.gateway.keyPage)}" target="_blank" rel="noopener">获取 Key</a></form></div>
|
|
1424
|
+
<div class="section-head"><div><h2>模型供应商</h2><p>${connected.length} 个已连接。Key 保存在 ~/.claude-pro/providers.json,页面上只显示开头和结尾</p></div><button class="button secondary small" id="addCustom">添加自定义供应商</button></div>
|
|
1425
|
+
<div class="prov-grid">${[...p.presets.filter((x) => x.connected), ...p.custom, ...p.presets.filter((x) => !x.connected)].map(card).join("")}</div></div>`;
|
|
1426
|
+
loadDefaults(el, p);
|
|
1427
|
+
$("#gwForm", el).addEventListener("submit", async (e) => {
|
|
1428
|
+
e.preventDefault();
|
|
1429
|
+
const apiKey = $("#gwKey", el).value.trim();
|
|
1430
|
+
if (!apiKey) return toast("请先粘贴 Key", "error");
|
|
1431
|
+
try { drawProviders(el, await api("/api/gateway", { method: "POST", body: { apiKey } })); toast("已连接 7bit.fun"); } catch (err) { fail(err); }
|
|
1432
|
+
});
|
|
1433
|
+
$("#gwOut", el)?.addEventListener("click", async () => {
|
|
1434
|
+
if (!confirm("断开 7bit.fun?这台电脑的会话会下线,网关上的模型也不能用了。")) return;
|
|
1435
|
+
try { drawProviders(el, await api("/api/gateway", { method: "DELETE" })); toast("已断开"); } catch (err) { fail(err); }
|
|
1436
|
+
});
|
|
1437
|
+
$("#addCustom", el).addEventListener("click", () => connectDialog(el, null));
|
|
1438
|
+
$("#pbody", el).addEventListener("click", async (e) => {
|
|
1439
|
+
const c = e.target.closest("[data-connect]"), r = e.target.closest("[data-remove]");
|
|
1440
|
+
if (c) connectDialog(el, [...p.presets, ...p.custom].find((x) => x.id === c.dataset.connect));
|
|
1441
|
+
if (r && confirm(`断开 ${r.dataset.remove}?保存的 Key 会删除。`)) {
|
|
1442
|
+
try { drawProviders(el, await api(`/api/providers/${encodeURIComponent(r.dataset.remove)}`, { method: "DELETE" })); toast("已断开"); } catch (err) { fail(err); }
|
|
1443
|
+
}
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
async function loadDefaults(el, p) {
|
|
1448
|
+
const box = $("#defaults", el);
|
|
1449
|
+
let m;
|
|
1450
|
+
try { m = await api("/api/models"); } catch (e) { box.innerHTML = `<div class="muted">读取失败:${esc(e.message)}</div>`; return; }
|
|
1451
|
+
const current = m.remembered?.model || m.current;
|
|
1452
|
+
const efforts = ["auto", "low", "medium", "high", "xhigh", "max"];
|
|
1453
|
+
const currentEffort = p.remembered?.effort || p.effort;
|
|
1454
|
+
box.innerHTML = `<div class="actions" style="align-items:flex-end">
|
|
1455
|
+
<label class="field" style="flex:2;min-width:260px;margin:0">模型<input list="modelList" id="defModel" value="${esc(current)}" placeholder="provider/model,或 opus、sonnet"><datalist id="modelList">${m.models.map((x) => `<option value="${esc(x.ref)}">${esc(x.provider)}${x.window ? ` · ${fmtTokens(x.window)} 上下文` : ""}</option>`).join("")}</datalist></label>
|
|
1456
|
+
<label class="field" style="min-width:140px;margin:0">推理强度<select id="defEffort">${efforts.map((x) => `<option${x === currentEffort ? " selected" : ""}>${x}</option>`).join("")}${efforts.includes(currentEffort) ? "" : `<option selected>${esc(currentEffort)}</option>`}</select></label>
|
|
1457
|
+
<button class="button" id="saveDefaults">保存为默认</button></div>
|
|
1458
|
+
<p class="muted" style="font-size:12.5px;margin:10px 0 0">${m.remembered?.model || m.remembered?.effort ? `现在生效的是会话里 /model、/effort 记住的选择(${esc([m.remembered.model, m.remembered.effort].filter(Boolean).join(" · "))})。保存后会写入设置的 model / effort,并清掉记住的选择。` : "保存到 ~/.claude-pro/settings.json 的 model / effort。"}已经开着的会话要 /model default 或重启才换。</p>`;
|
|
1459
|
+
$("#saveDefaults", box).addEventListener("click", async () => {
|
|
1460
|
+
const model = $("#defModel", box).value.trim();
|
|
1461
|
+
const effort = $("#defEffort", box).value;
|
|
1462
|
+
try {
|
|
1463
|
+
if (model) await api("/api/settings", { method: "POST", body: { scope: "user", key: "model", value: model } });
|
|
1464
|
+
await api("/api/settings", { method: "POST", body: { scope: "user", key: "effort", value: effort } });
|
|
1465
|
+
await api("/api/remembered", { method: "POST", body: { model: null, effort: null } });
|
|
1466
|
+
toast("已保存默认模型");
|
|
1467
|
+
providers();
|
|
1468
|
+
} catch (e) { fail(e); }
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// Connect a provider (a built-in one, or with x = null one of the user's own): key → models → test → saved.
|
|
1473
|
+
function connectDialog(el, x) {
|
|
1474
|
+
const custom = !x;
|
|
1475
|
+
const m = modal({
|
|
1476
|
+
title: custom ? "添加自定义供应商" : `连接 ${x.name}`, sub: custom ? "任何兼容 Anthropic Messages 或 OpenAI Chat Completions 的接口" : `${x.baseUrl}`,
|
|
1477
|
+
body: `${custom ? `<label class="field">名字<small>模型名会是 名字/模型,比如 myrelay/gpt-5</small><input id="cName" placeholder="myrelay"></label>
|
|
1478
|
+
<label class="field">协议<select id="cProto"><option value="openai">OpenAI 兼容(/chat/completions)</option><option value="anthropic">Anthropic 兼容(/v1/messages)</option></select></label>
|
|
1479
|
+
<label class="field">地址<input id="cUrl" placeholder="https://api.example.com/v1"></label>` : ""}
|
|
1480
|
+
<label class="field">API Key${x?.connected ? "<small>留空则继续用已保存的 Key</small>" : x?.keyless ? "<small>这个供应商不需要 Key</small>" : ""}<input type="password" id="cKey" autocomplete="off" placeholder="${x?.connected ? "留空:用已保存的" : "粘贴 Key"}"></label>
|
|
1481
|
+
<div class="actions"><button class="button secondary" id="cCheck">检查 Key 并列出模型</button></div>
|
|
1482
|
+
<div id="cModels" style="margin-top:14px"></div>`,
|
|
1483
|
+
foot: '<span class="modal-error"></span><button class="button secondary" data-close>取消</button><button class="button" id="cConnect" disabled>测试并连接</button>',
|
|
1484
|
+
});
|
|
1485
|
+
let checked = null;
|
|
1486
|
+
const err = (t) => { $(".modal-error", m.el).textContent = t || ""; };
|
|
1487
|
+
const target = () => (custom ? { custom: { name: $("#cName", m.el).value, protocol: $("#cProto", m.el).value, baseUrl: $("#cUrl", m.el).value } } : { id: x.id });
|
|
1488
|
+
$("#cCheck", m.el).addEventListener("click", async (e) => {
|
|
1489
|
+
err("");
|
|
1490
|
+
e.target.disabled = true;
|
|
1491
|
+
e.target.textContent = "检查中…";
|
|
1492
|
+
try {
|
|
1493
|
+
checked = await api("/api/providers/check", { method: "POST", body: { ...target(), apiKey: $("#cKey", m.el).value } });
|
|
1494
|
+
const list = checked.models || [];
|
|
1495
|
+
$("#cModels", m.el).innerHTML = list.length
|
|
1496
|
+
? `<input type="search" id="cFilter" placeholder="筛选 ${list.length} 个模型" style="width:100%;margin-bottom:8px"><div class="model-list">${list.map((mm, i) => `<label data-name="${esc(mm.id.toLowerCase())}"><input type="radio" name="cm" value="${i}"${mm.id === checked.current || (!checked.current && i === 0) ? " checked" : ""}> <span class="mono">${esc(mm.id)}</span><small>${[mm.window ? `${fmtTokens(mm.window)} 上下文` : "", mm.price ? `$${mm.price.input}/$${mm.price.output} 每百万` : ""].filter(Boolean).join(" · ")}</small></label>`).join("")}</div>`
|
|
1497
|
+
: '<label class="field">它没有列出模型:填写要用的模型名<input id="cManual" placeholder="模型 id"></label>';
|
|
1498
|
+
$("#cModels", m.el).insertAdjacentHTML("beforeend", '<label class="muted" style="display:block;margin-top:10px;font-size:13px"><input type="checkbox" id="cUse" checked> 连接后设为当前使用的模型(和 /model 一样)</label>');
|
|
1499
|
+
$("#cFilter", m.el)?.addEventListener("input", (ev) => { const q = ev.target.value.toLowerCase(); $$(".model-list label", m.el).forEach((l) => l.classList.toggle("hidden", !l.dataset.name.includes(q))); });
|
|
1500
|
+
$("#cConnect", m.el).disabled = false;
|
|
1501
|
+
} catch (ex) { err(ex.message); } finally { e.target.disabled = false; e.target.textContent = "检查 Key 并列出模型"; }
|
|
1502
|
+
});
|
|
1503
|
+
$("#cConnect", m.el).addEventListener("click", async (e) => {
|
|
1504
|
+
err("");
|
|
1505
|
+
const list = checked?.models || [];
|
|
1506
|
+
const picked = $("input[name=cm]:checked", m.el);
|
|
1507
|
+
const model = picked ? list[Number(picked.value)].id : $("#cManual", m.el)?.value.trim();
|
|
1508
|
+
if (!model) return err("请选择或填写一个模型");
|
|
1509
|
+
e.target.disabled = true;
|
|
1510
|
+
e.target.textContent = `正在测试 ${model}…`;
|
|
1511
|
+
try {
|
|
1512
|
+
const p = await api("/api/providers/connect", { method: "POST", body: { ...target(), apiKey: $("#cKey", m.el).value, model, models: list.length ? list : [{ id: model }], authHeader: checked?.authHeader, useNow: $("#cUse", m.el)?.checked } });
|
|
1513
|
+
m.close();
|
|
1514
|
+
toast(`已连接,模型 ${model} 测试通过`);
|
|
1515
|
+
drawProviders(el, p);
|
|
1516
|
+
} catch (ex) { err(ex.message); e.target.disabled = false; e.target.textContent = "测试并连接"; }
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
// ---------------------------------------------------------------- 设置
|
|
1521
|
+
|
|
1522
|
+
const CHOICES = { effort: ["auto", "low", "medium", "high", "xhigh", "max"], promptCacheTtl: ["5m", "1h"], subagentPromptCacheTtl: ["5m", "1h"] };
|
|
1523
|
+
// The settings' descriptions in Chinese (the terminal's /config has them in English, in config.js)
|
|
1524
|
+
const ZH = {
|
|
1525
|
+
model: "默认模型,写成 供应商/模型(如 deepseek/deepseek-v4-pro)或 opus、sonnet。没设置时:连了 Claude 就用 opus,否则用第一个连接的供应商的模型。会话里的 /model 和 --model 会覆盖它",
|
|
1526
|
+
effort: "推理强度:auto、low、medium、high、xhigh、max。会话里的 /effort 和 --effort 会覆盖它",
|
|
1527
|
+
promptCacheTtl: "主对话的提示词缓存时长:5m 或 1h",
|
|
1528
|
+
subagentPromptCacheTtl: "子 agent、压缩和辅助请求的提示词缓存时长:5m 或 1h",
|
|
1529
|
+
cleanupPeriodDays: "会话最后一次使用后保留多少天(之后连同运行记录一起删除,和 Claude Code 一样;至少 1 天,想长期保留可以填 3650)",
|
|
1530
|
+
CLAUDE_PRO_GATEWAY_URL: "网关地址(默认 https://7bit.fun)",
|
|
1531
|
+
CLAUDE_PRO_ONLINE: "设为 0:交互会话不连网关(也就不能跨电脑互发任务、不能和通讯录好友通讯)",
|
|
1532
|
+
CLAUDE_PRO_MACHINE_NAME: "这台电脑在其他电脑的会话里显示的名字(如 公司、家里;默认是主机名)",
|
|
1533
|
+
CLAUDE_CODE_MAX_OUTPUT_TOKENS: "每次回复的 max_tokens(默认 48000;网关允许的更少时会自动降低)",
|
|
1534
|
+
MAX_THINKING_TOKENS: "思考预算:0 关闭思考,N 表示预算 N 个 token",
|
|
1535
|
+
CLAUDE_PRO_CACHE_KEEPALIVE_HOURS: "Claude 模型用 1 小时缓存时:你离开期间在缓存过期前刷新它(读一次只要重写的 1/40),最多保持这么多小时(默认 8;0 关闭)",
|
|
1536
|
+
DISABLE_PROMPT_CACHING: "设为 1:完全不发缓存标记(所有模型都不用提示词缓存)",
|
|
1537
|
+
API_TIMEOUT_MS: "请求超时,毫秒",
|
|
1538
|
+
CLAUDE_PRO_MAX_RETRIES: "API 请求失败时的重试次数(0 = 不重试,也不再等待限流恢复)",
|
|
1539
|
+
CLAUDE_PRO_RATE_LIMIT_MAX_WAIT_MS: "遇到限流(比如 5 小时额度)时最多等多久再自动继续(默认 21600000 = 6 小时;0 = 直接报错不等)",
|
|
1540
|
+
CLAUDE_CODE_GIT_BASH_PATH: "Windows:bash.exe(Git Bash)的路径",
|
|
1541
|
+
CLAUDE_PRO_RIPGREP_PATH: "ripgrep(rg)的路径,Grep 和 @ 文件补全会用;off 强制用内置的 JS 扫描(默认:PATH 里的 rg,没有就用 JS)",
|
|
1542
|
+
CLAUDE_PRO_BROWSER: "Browser 工具操作哪个浏览器:auto(默认,Edge、Chrome、Brave、Chromium 中第一个打开了远程调试的)、edge、chrome、brave、chromium、own(claude-pro 自己的 Chrome 配置,无需允许)、DevTools 地址,或 off(不提供 Browser 工具)",
|
|
1543
|
+
CLAUDE_PRO_PYTHON: "REPL 工具用的 Python(默认:Windows 上 python,其他系统 python3)",
|
|
1544
|
+
CLAUDE_PRO_VERIFY_COMMAND: "agent 改完文件后运行的命令(如 npm test),失败会发回给它修",
|
|
1545
|
+
CLAUDE_PRO_DISABLE_AUTO_MEMORY: "设为 1:关闭每个项目的自动记忆",
|
|
1546
|
+
CLAUDE_PRO_DISABLE_TOPIC_TITLE: "设为 1:不再每条消息后让模型总结话题(标签页标题改为显示第一条消息)",
|
|
1547
|
+
CLAUDE_PRO_TRACE: "设为 0:关闭运行记录(默认开启,只记结构和用量,不记内容;用量页的数据来自它)",
|
|
1548
|
+
};
|
|
1549
|
+
const SCOPE_NAMES = { user: "用户(所有项目)", project: "项目(随仓库提交)", local: "项目本地(不提交)" };
|
|
1550
|
+
|
|
1551
|
+
async function projectsSelect(id, selected, { allLabel = "只看用户级" } = {}) {
|
|
1552
|
+
let list = [];
|
|
1553
|
+
try { list = (await api("/api/projects")).projects; } catch { /* only the user's */ }
|
|
1554
|
+
return `<select id="${id}"><option value="">${esc(allLabel)}</option>${list.map((p) => `<option value="${esc(p.cwd)}"${p.cwd === selected ? " selected" : ""}>${esc(shortPath(p.cwd))}</option>`).join("")}</select>`;
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
async function settings() {
|
|
1558
|
+
const project = sessionStorage.getItem("settingsProject") || "";
|
|
1559
|
+
const el = page(`<h1>设置</h1><p class="sub">和 /config、claude-pro config 是同一份设置。改动对新会话生效;已经开着的会话大多要重启才会读到</p>
|
|
1560
|
+
<div class="toolbar"><span class="muted" style="font-size:13px">项目:</span>${await projectsSelect("proj", project)}<input type="search" id="q" placeholder="筛选设置…"></div><div id="body"><div class="empty">正在加载…</div></div>`);
|
|
1561
|
+
$("#proj", el).addEventListener("change", (e) => { sessionStorage.setItem("settingsProject", e.target.value); settings(); });
|
|
1562
|
+
let s;
|
|
1563
|
+
try { s = await api(`/api/settings${project ? `?project=${encodeURIComponent(project)}` : ""}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
1564
|
+
const sourceName = (src) => {
|
|
1565
|
+
if (src === "default") return "默认值";
|
|
1566
|
+
if (src === "process environment") return "进程环境变量";
|
|
1567
|
+
if (/flag$/.test(src)) return "命令行参数";
|
|
1568
|
+
for (const [scope, file] of Object.entries(s.files)) if (file === src) return SCOPE_NAMES[scope];
|
|
1569
|
+
return src;
|
|
1570
|
+
};
|
|
1571
|
+
const row = (e) => {
|
|
1572
|
+
const scopes = e.userOnly || !s.project ? ["user"] : ["user", "project", "local"];
|
|
1573
|
+
const set = Object.entries(e.scopes).filter(([, v]) => v != null);
|
|
1574
|
+
const input = CHOICES[e.key]
|
|
1575
|
+
? `<select data-value>${CHOICES[e.key].map((c) => `<option${String(e.value) === c ? " selected" : ""}>${c}</option>`).join("")}</select>`
|
|
1576
|
+
: `<input data-value value="${esc(e.value ?? "")}" placeholder="${e.default != null ? `默认 ${esc(e.default)}` : "未设置"}">`;
|
|
1577
|
+
return `<div class="setting" data-key="${esc(e.key)}" data-search="${esc(`${e.key} ${e.description} ${ZH[e.key] || ""}`.toLowerCase())}"><div><div class="key">${esc(e.key)}</div><div class="desc" title="${esc(e.description || "")}">${esc(ZH[e.key] || e.description || "")}</div></div>
|
|
1578
|
+
<div><div class="now">当前:<strong class="mono">${e.value == null || e.value === "" ? "(未设置)" : esc(e.value)}</strong> <span class="pill${e.source === "default" ? "" : " accent"}">${esc(sourceName(e.source))}</span>
|
|
1579
|
+
${(s.project ? set : []).map(([scope, v]) => `<span class="pill" title="${esc(s.files[scope])}">${esc(SCOPE_NAMES[scope])}:${esc(v)}</span>`).join(" ")}</div>
|
|
1580
|
+
<div class="row">${input}<select data-scope>${scopes.map((sc) => `<option value="${sc}">${esc(SCOPE_NAMES[sc])}</option>`).join("")}</select><button class="button small" data-save>保存</button>${set.length ? '<button class="button secondary small" data-unset>恢复默认</button>' : ""}</div></div></div>`;
|
|
1581
|
+
};
|
|
1582
|
+
const basic = s.entries.filter((e) => e.basic), advanced = s.entries.filter((e) => !e.basic);
|
|
1583
|
+
$("#body", el).innerHTML = `${s.remembered?.model || s.remembered?.effort ? `<div class="panel panel-pad" style="margin-bottom:14px">/model、/effort 记住的选择会覆盖下面的 model、effort:<strong class="mono">${esc([s.remembered.model, s.remembered.effort].filter(Boolean).join(" · "))}</strong> <button class="button secondary small" id="forget">清除记住的选择</button></div>` : ""}
|
|
1584
|
+
<div class="section-head"><h2>常用设置</h2></div><div class="panel">${basic.map(row).join("")}</div>
|
|
1585
|
+
<div class="section-head"><div><h2>高级设置</h2><p>写在设置文件的 env 里;进程环境变量会覆盖它们</p></div></div><div class="panel">${advanced.map(row).join("")}</div>
|
|
1586
|
+
<p class="faint" style="font-size:12px;margin-top:12px">设置文件:${Object.entries(s.files).map(([k, f]) => `${esc(SCOPE_NAMES[k])} <span class="mono">${esc(f)}</span>`).join(" · ")}</p>`;
|
|
1587
|
+
$("#q", el).addEventListener("input", (e) => { const q = e.target.value.toLowerCase(); $$(".setting", el).forEach((n) => n.classList.toggle("hidden", !n.dataset.search.includes(q))); });
|
|
1588
|
+
$("#forget", el)?.addEventListener("click", async () => { try { await api("/api/remembered", { method: "POST", body: { model: null, effort: null } }); toast("已清除"); settings(); } catch (e) { fail(e); } });
|
|
1589
|
+
$("#body", el).addEventListener("click", async (e) => {
|
|
1590
|
+
const box = e.target.closest(".setting");
|
|
1591
|
+
if (!box) return;
|
|
1592
|
+
const key = box.dataset.key;
|
|
1593
|
+
const scope = $("[data-scope]", box).value;
|
|
1594
|
+
try {
|
|
1595
|
+
if (e.target.closest("[data-save]")) {
|
|
1596
|
+
const raw = $("[data-value]", box).value;
|
|
1597
|
+
const value = key === "cleanupPeriodDays" ? Number(raw) : raw;
|
|
1598
|
+
await api("/api/settings", { method: "POST", body: { key, value, scope, project } });
|
|
1599
|
+
toast(`${key} 已保存`);
|
|
1600
|
+
settings();
|
|
1601
|
+
} else if (e.target.closest("[data-unset]")) {
|
|
1602
|
+
for (const [sc, v] of Object.entries((s.entries.find((x) => x.key === key) || {}).scopes || {})) if (v != null) await api("/api/settings", { method: "POST", body: { key, unset: true, scope: sc, project } });
|
|
1603
|
+
toast(`${key} 已恢复默认`);
|
|
1604
|
+
settings();
|
|
1605
|
+
}
|
|
1606
|
+
} catch (err) { fail(err); }
|
|
1607
|
+
});
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
// ---------------------------------------------------------------- 记忆与指令
|
|
1611
|
+
|
|
1612
|
+
async function memory() {
|
|
1613
|
+
const el = page('<h1>记忆与指令</h1><p class="sub">CLAUDE.md(你写给 agent 的长期指令)和 agent 自动记下的记忆。改动从下一个新会话(或 /clear、/compact 之后)开始生效</p><div id="body"><div class="empty">正在加载…</div></div>');
|
|
1614
|
+
let m;
|
|
1615
|
+
try { m = await api("/api/memory"); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
1616
|
+
const open = new Set(JSON.parse(sessionStorage.getItem("memoryOpen") || "[]"));
|
|
1617
|
+
$("#body", el).innerHTML = `<div class="section-head"><h2>全局指令</h2></div>
|
|
1618
|
+
<div class="panel"><div class="file-row"><span class="name">~/.claude-pro/CLAUDE.md</span><span class="desc">所有项目都会加载</span><button class="button small ${m.user.exists ? "secondary" : ""}" data-edit="${esc(m.user.path)}">${m.user.exists ? "编辑" : "新建"}</button></div></div>
|
|
1619
|
+
<div class="section-head"><div><h2>各项目</h2><p>${m.projects.length} 个有会话记录的项目</p></div><input type="search" id="q" placeholder="筛选项目…"></div>
|
|
1620
|
+
<div class="panel">${m.projects.map((p) => `<details class="proj" data-path="${esc(p.cwd.toLowerCase())}"${open.has(p.cwd) ? " open" : ""} data-cwd="${esc(p.cwd)}"><summary><strong class="mono" style="font-size:13px">${esc(shortPath(p.cwd))}</strong>${p.exists ? "" : '<span class="pill off">目录不在了</span>'}<span class="muted" style="margin-left:auto;font-size:12px">${p.memory.length} 条记忆 · ${p.instructions.filter((f) => f.exists).length} 个指令文件 · ${p.sessions} 个会话</span></summary><div>
|
|
1621
|
+
${p.instructions.filter((f) => f.exists || f.name === "CLAUDE.md").map((f) => `<div class="file-row"><span class="name">${esc(f.name)}</span><span class="desc">${f.name === "CLAUDE.local.md" ? "只在本机,不提交" : "项目指令"}</span>${p.exists ? `<button class="button small ${f.exists ? "secondary" : ""}" data-edit="${esc(f.path)}">${f.exists ? "编辑" : "新建"}</button>` : ""}</div>`).join("")}
|
|
1622
|
+
${p.memory.length ? p.memory.map((f) => `<div class="file-row"><span class="name">记忆/${esc(f.name)}</span><span class="desc">${f.name === "MEMORY.md" ? "索引:每个会话都会加载" : fmtBytes(f.size)}</span><button class="button secondary small" data-edit="${esc(f.path)}" data-deletable="1">编辑</button></div>`).join("") : '<div class="file-row"><span class="desc">还没有自动记忆</span></div>'}
|
|
1623
|
+
</div></details>`).join("") || '<div class="empty">没有项目</div>'}</div>`;
|
|
1624
|
+
$("#q", el).addEventListener("input", (e) => { const q = e.target.value.toLowerCase(); $$("details.proj", el).forEach((d) => d.classList.toggle("hidden", !d.dataset.path.includes(q))); });
|
|
1625
|
+
$$("details.proj", el).forEach((d) => d.addEventListener("toggle", () => {
|
|
1626
|
+
if (d.open) open.add(d.dataset.cwd); else open.delete(d.dataset.cwd);
|
|
1627
|
+
sessionStorage.setItem("memoryOpen", JSON.stringify([...open]));
|
|
1628
|
+
}));
|
|
1629
|
+
$("#body", el).addEventListener("click", (e) => {
|
|
1630
|
+
const b = e.target.closest("[data-edit]");
|
|
1631
|
+
if (b) openEditor(b.dataset.edit, { title: "编辑", deletable: Boolean(b.dataset.deletable), onSaved: memory });
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// ---------------------------------------------------------------- 扩展
|
|
1636
|
+
|
|
1637
|
+
async function extensions() {
|
|
1638
|
+
const project = sessionStorage.getItem("extProject") || "";
|
|
1639
|
+
const el = page(`<h1>扩展</h1><p class="sub">技能、子 agent、自定义命令、MCP 服务器和 hooks。新会话会加载改动</p>
|
|
1640
|
+
<div class="toolbar"><span class="muted" style="font-size:13px">项目:</span>${await projectsSelect("proj", project)}</div><div id="body"><div class="empty">正在加载…</div></div>`);
|
|
1641
|
+
$("#proj", el).addEventListener("change", (e) => { sessionStorage.setItem("extProject", e.target.value); extensions(); });
|
|
1642
|
+
let x;
|
|
1643
|
+
try { x = await api(`/api/extensions${project ? `?project=${encodeURIComponent(project)}` : ""}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
1644
|
+
const scopePill = (s) => `<span class="pill${s === "built-in" ? "" : s === "user" ? " accent" : " ok"}">${{ "built-in": "内置", user: "用户", project: "项目" }[s] || esc(s)}</span>`;
|
|
1645
|
+
const list = (items, kind) => items.length ? items.map((i) => `<div class="file-row"><span class="name">${esc(kind === "command" ? `/${i.name}` : i.name)}</span>${scopePill(i.scope)}<span class="desc" title="${esc(i.description)}">${esc(i.description)}</span>${i.path ? `<button class="button secondary small" data-edit="${esc(i.path)}">编辑</button>` : ""}</div>`).join("") : '<div class="file-row"><span class="desc">还没有</span></div>';
|
|
1646
|
+
const newBtn = (kind, label) => `<button class="button secondary small" data-new="${kind}">新建${label}</button>`;
|
|
1647
|
+
$("#body", el).innerHTML = `
|
|
1648
|
+
<div class="section-head"><div><h2>技能</h2><p>skills/<名字>/SKILL.md:模型按描述决定何时加载</p></div>${newBtn("skill", "技能")}</div><div class="panel">${list(x.skills, "skill")}</div>
|
|
1649
|
+
<div class="section-head"><div><h2>子 agent</h2><p>agents/*.md:Task 工具可以把任务交给它们</p></div>${newBtn("agent", "子 agent")}</div><div class="panel">${list(x.agents, "agent")}</div>
|
|
1650
|
+
<div class="section-head"><div><h2>自定义命令</h2><p>commands/*.md:在会话里输入 /名字</p></div>${newBtn("command", "命令")}</div><div class="panel">${list(x.commands, "command")}</div>
|
|
1651
|
+
<div class="section-head"><div><h2>MCP 服务器</h2><p>环境变量和请求头的值不会显示(保持 ••• 就是不改)</p></div><button class="button secondary small" id="addMcp">添加 MCP 服务器</button></div>
|
|
1652
|
+
<div class="panel">${x.mcp.length ? x.mcp.map((s, i) => `<div class="file-row"><span class="name">${esc(s.name)}</span><span class="pill">${esc(s.scope)}</span><span class="desc mono">${esc(s.spec?.url || [s.spec?.command, ...(s.spec?.args || [])].filter(Boolean).join(" "))}</span>${s.scope === "user" || s.scope === ".mcp.json" ? `<button class="button secondary small" data-mcp="${i}">编辑</button>` : `<button class="button secondary small" data-edit="${esc(s.file)}">编辑文件</button>`}</div>`).join("") : '<div class="file-row"><span class="desc">没有配置 MCP 服务器</span></div>'}</div>
|
|
1653
|
+
<div class="section-head"><div><h2>Hooks</h2><p>在工具调用前后、提交消息时等运行的命令,写在设置文件的 hooks 里</p></div></div>
|
|
1654
|
+
<div class="panel">${x.hooks.length ? x.hooks.map((h) => `<div class="file-row"><span class="name">${esc(h.event)}</span><span class="pill">${esc(h.scope)}</span><span class="desc mono">${esc(JSON.stringify(h.entries))}</span><button class="button secondary small" data-edit="${esc(h.file)}">编辑文件</button></div>`).join("") : `<div class="file-row"><span class="desc">没有 hooks。要添加,编辑设置文件的 "hooks" 字段</span><button class="button secondary small" data-edit="${esc(x.settingsFiles.user)}">编辑用户设置文件</button></div>`}</div>`;
|
|
1655
|
+
$("#body", el).addEventListener("click", async (e) => {
|
|
1656
|
+
const ed = e.target.closest("[data-edit]"), nw = e.target.closest("[data-new]"), mc = e.target.closest("[data-mcp]");
|
|
1657
|
+
if (ed) openEditor(ed.dataset.edit, { title: "编辑", deletable: !/\.json$/i.test(ed.dataset.edit), onSaved: extensions });
|
|
1658
|
+
if (nw) {
|
|
1659
|
+
const kind = nw.dataset.new;
|
|
1660
|
+
const name = prompt(`新${{ skill: "技能", agent: "子 agent", command: "命令" }[kind]}的名字(字母、数字、_ . -)`);
|
|
1661
|
+
if (!name) return;
|
|
1662
|
+
const scope = project && confirm(`放在项目 ${project} 里吗?\n确定:项目级(.claude-pro/) 取消:用户级(所有项目)`) ? "project" : "user";
|
|
1663
|
+
try { const r = await api("/api/extensions", { method: "POST", body: { kind, scope, name, project } }); openEditor(r.path, { title: "编辑", onSaved: extensions }); } catch (err) { fail(err); }
|
|
1664
|
+
}
|
|
1665
|
+
if (mc) mcpDialog(x, x.mcp[Number(mc.dataset.mcp)], project);
|
|
1666
|
+
});
|
|
1667
|
+
$("#addMcp", el).addEventListener("click", () => mcpDialog(x, null, project));
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
function mcpDialog(x, server, project) {
|
|
1671
|
+
const spec = server ? server.spec : { command: "npx", args: ["-y", "some-mcp-server"] };
|
|
1672
|
+
const m = modal({
|
|
1673
|
+
title: server ? `MCP 服务器:${server.name}` : "添加 MCP 服务器", sub: server ? server.file : "",
|
|
1674
|
+
body: `<label class="field">名字<input id="mName" value="${esc(server?.name || "")}"${server ? " disabled" : ""}></label>
|
|
1675
|
+
${server ? "" : `<label class="field">放在<select id="mScope"><option value="user">用户设置(所有项目)</option>${project ? `<option value="project">项目的 .mcp.json(${esc(project)})</option>` : ""}</select></label>`}
|
|
1676
|
+
<label class="field">配置(JSON,和 Claude Code 的 mcpServers 写法一样)<small>stdio:{"command","args","env"};远程:{"type":"http","url","headers"}</small><textarea id="mSpec" class="editor" style="min-height:220px">${esc(JSON.stringify(spec, null, 2))}</textarea></label>`,
|
|
1677
|
+
foot: `<span class="modal-error"></span>${server ? '<button class="button danger" id="mDel">删除</button>' : ""}<button class="button secondary" data-close>取消</button><button class="button" id="mSave">保存</button>`,
|
|
1678
|
+
});
|
|
1679
|
+
const scope = () => (server ? (server.scope === ".mcp.json" ? "project" : "user") : $("#mScope", m.el).value);
|
|
1680
|
+
$("#mSave", m.el).addEventListener("click", async () => {
|
|
1681
|
+
let parsed;
|
|
1682
|
+
try { parsed = JSON.parse($("#mSpec", m.el).value); } catch (e) { $(".modal-error", m.el).textContent = `JSON 有误:${e.message}`; return; }
|
|
1683
|
+
try { await api("/api/mcp", { method: "POST", body: { name: $("#mName", m.el).value.trim(), scope: scope(), project, spec: parsed } }); m.close(); toast("已保存:新会话会启动它"); extensions(); } catch (e) { $(".modal-error", m.el).textContent = e.message; }
|
|
1684
|
+
});
|
|
1685
|
+
$("#mDel", m.el)?.addEventListener("click", async () => {
|
|
1686
|
+
if (!confirm(`删除 MCP 服务器 ${server.name}?`)) return;
|
|
1687
|
+
try { await api("/api/mcp", { method: "POST", body: { name: server.name, scope: scope(), project, remove: true } }); m.close(); toast("已删除"); extensions(); } catch (e) { fail(e); }
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
// ---------------------------------------------------------------- 用量
|
|
1692
|
+
|
|
1693
|
+
async function usage() {
|
|
1694
|
+
const days = Number(sessionStorage.getItem("usageDays")) || 30;
|
|
1695
|
+
const el = page(`<h1>用量</h1><p class="sub">按天、模型、项目统计(来自每次请求的运行记录;有价格的模型才算得出花费)</p>
|
|
1696
|
+
<div class="toolbar">${[7, 30, 90].map((d) => `<button class="button ${d === days ? "" : "secondary"} small" data-days="${d}">近 ${d} 天</button>`).join("")}<span style="flex:1"></span><label class="muted" style="font-size:13px">图表:<select id="metric"><option value="cost">花费</option><option value="tokens">tokens</option><option value="requests">请求数</option></select></label></div><div id="body"><div class="empty">正在统计…</div></div>`);
|
|
1697
|
+
$$("[data-days]", el).forEach((b) => b.addEventListener("click", () => { sessionStorage.setItem("usageDays", b.dataset.days); usage(); }));
|
|
1698
|
+
let u;
|
|
1699
|
+
try { u = await api(`/api/usage?days=${days}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
|
|
1700
|
+
const total = u.days.reduce((a, d) => ({ cost: a.cost + d.cost, requests: a.requests + d.requests, tokens: a.tokens + d.input + d.output + d.cacheRead + d.cacheWrite }), { cost: 0, requests: 0, tokens: 0 });
|
|
1701
|
+
const table = (rows, label) => rows.length ? `<table class="list"><thead><tr><th>${label}</th><th class="num">请求</th><th class="num">输入</th><th class="num">输出</th><th class="num">缓存读</th><th class="num">缓存写</th><th class="num">花费</th></tr></thead><tbody>
|
|
1702
|
+
${rows.map((r) => `<tr><td class="mono" style="word-break:break-all">${esc(shortPath(r.key))}</td><td class="num">${r.requests}</td><td class="num">${fmtTokens(r.input)}</td><td class="num">${fmtTokens(r.output)}</td><td class="num">${fmtTokens(r.cacheRead)}</td><td class="num">${fmtTokens(r.cacheWrite)}</td><td class="num">${r.cost ? fmtUsd(r.cost) : "—"}${r.unpriced ? ` <span class="faint" title="${r.unpriced} 次请求的模型没有价格">*</span>` : ""}</td></tr>`).join("")}
|
|
1703
|
+
</tbody></table>` : '<div class="empty">没有记录</div>';
|
|
1704
|
+
$("#body", el).innerHTML = `<div class="cards">
|
|
1705
|
+
<div class="panel stat"><div class="label">花费(近 ${days} 天,按价格估算)</div><div class="value">${fmtUsd(total.cost)}</div></div>
|
|
1706
|
+
<div class="panel stat"><div class="label">请求</div><div class="value">${total.requests}</div></div>
|
|
1707
|
+
<div class="panel stat"><div class="label">tokens(含缓存)</div><div class="value">${fmtTokens(total.tokens)}</div></div>
|
|
1708
|
+
<div class="panel stat"><div class="label">所有会话累计花费</div><div class="value">${fmtUsd(u.totalSessionCost)}</div><div class="hint">会话自己记录的花费,不限时间</div></div></div>
|
|
1709
|
+
<div class="section-head"><h2>每天</h2></div><div class="panel panel-pad"><svg class="chart" id="chart"></svg></div>
|
|
1710
|
+
<div class="section-head"><h2>按模型</h2></div><div class="panel">${table(u.models, "模型")}</div>
|
|
1711
|
+
<div class="section-head"><h2>按项目</h2></div><div class="panel">${table(u.projects, "项目")}</div>
|
|
1712
|
+
<div class="section-head"><h2>花费最多的会话</h2></div><div class="panel">${u.sessions.length ? `<table class="list"><tbody>${u.sessions.map((s) => `<tr class="click" data-open="${esc(s.dir)}/${esc(s.id)}"><td class="title-cell"><strong>${esc(s.title)}</strong><div class="path">${esc(shortPath(s.cwd || s.dir))}</div></td><td>${ago(s.mtime)}</td><td class="num">${fmtUsd(s.cost)}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">没有记录</div>'}</div>`;
|
|
1713
|
+
const drawChart = () => {
|
|
1714
|
+
const metric = $("#metric", el).value;
|
|
1715
|
+
const val = (d) => (metric === "cost" ? d.cost : metric === "tokens" ? d.input + d.output + d.cacheRead + d.cacheWrite : d.requests);
|
|
1716
|
+
const svg = $("#chart", el);
|
|
1717
|
+
const w = svg.clientWidth || 900, h = 220, pad = { l: 56, r: 10, t: 10, b: 26 };
|
|
1718
|
+
const max = Math.max(...u.days.map(val), metric === "cost" ? 0.01 : 1);
|
|
1719
|
+
const bw = (w - pad.l - pad.r) / u.days.length;
|
|
1720
|
+
const fmt = (v) => (metric === "cost" ? fmtUsd(v) : fmtTokens(v));
|
|
1721
|
+
let s = "";
|
|
1722
|
+
for (let i = 0; i <= 4; i++) { const y = pad.t + ((h - pad.t - pad.b) * i) / 4; s += `<line x1="${pad.l}" x2="${w - pad.r}" y1="${y}" y2="${y}"/><text x="${pad.l - 6}" y="${y + 3}" text-anchor="end">${esc(fmt(max * (1 - i / 4)))}</text>`; }
|
|
1723
|
+
u.days.forEach((d, i) => {
|
|
1724
|
+
const v = val(d);
|
|
1725
|
+
const bh = ((h - pad.t - pad.b) * v) / max;
|
|
1726
|
+
const x = pad.l + i * bw;
|
|
1727
|
+
s += `<rect class="bar" x="${x + bw * 0.15}" y="${h - pad.b - bh}" width="${Math.max(1, bw * 0.7)}" height="${Math.max(0, bh)}"><title>${esc(d.key)}:${esc(fmt(v))} · ${d.requests} 次请求</title></rect>`;
|
|
1728
|
+
if (u.days.length <= 31 ? i % Math.ceil(u.days.length / 10) === 0 : i % 10 === 0) s += `<text x="${x + bw / 2}" y="${h - 8}" text-anchor="middle">${esc(d.key.slice(5))}</text>`;
|
|
1729
|
+
});
|
|
1730
|
+
svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
|
|
1731
|
+
svg.innerHTML = s;
|
|
1732
|
+
};
|
|
1733
|
+
drawChart();
|
|
1734
|
+
$("#metric", el).addEventListener("change", drawChart);
|
|
1735
|
+
window.addEventListener("resize", drawChart);
|
|
1736
|
+
cleanup = () => window.removeEventListener("resize", drawChart);
|
|
1737
|
+
$("#body", el).addEventListener("click", (e) => { const r = e.target.closest("[data-open]"); if (r) location.hash = `#/session/${r.dataset.open}`; });
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
// ---------------------------------------------------------------- manual npm updates
|
|
1741
|
+
|
|
1742
|
+
let updateInfo, updateTimer, clickedVersion;
|
|
1743
|
+
const updateButton = $("#brandUpdate");
|
|
1744
|
+
function paintBrandUpdate(info) {
|
|
1745
|
+
updateInfo = info;
|
|
1746
|
+
if (info.runningVersion) $("#brandVersion").textContent = `v${info.runningVersion}`;
|
|
1747
|
+
const busy = info.status === "updating" || info.status === "restarting";
|
|
1748
|
+
const available = info.status === "available" || info.status === "installed";
|
|
1749
|
+
updateButton.classList.toggle("hidden", !available && !busy);
|
|
1750
|
+
updateButton.disabled = busy;
|
|
1751
|
+
updateButton.textContent = busy ? "…" : "↑";
|
|
1752
|
+
updateButton.title = busy ? (info.status === "updating" ? `正在安装 v${info.version}` : `等待加载 v${info.version}`) : available ? `${info.status === "installed" ? "加载" : "更新到"} v${info.version}` : "";
|
|
1753
|
+
updateButton.setAttribute("aria-label", updateButton.title);
|
|
1754
|
+
if (clickedVersion && !busy) {
|
|
1755
|
+
if (info.runningVersion === clickedVersion) { toast(`已更新到 v${info.runningVersion},刷新网页可加载新版界面`); clickedVersion = null; }
|
|
1756
|
+
else if (info.error && available) { fail(new Error(info.error)); clickedVersion = null; }
|
|
1757
|
+
else if (info.status === "current" || info.status === "dev") clickedVersion = null;
|
|
1758
|
+
}
|
|
1759
|
+
scheduleUpdateCheck(busy || clickedVersion ? 2500 : info.status === "error" ? 60_000 : 15 * 60_000);
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
function scheduleUpdateCheck(delay = 0) {
|
|
1763
|
+
clearTimeout(updateTimer);
|
|
1764
|
+
updateTimer = setTimeout(async () => {
|
|
1765
|
+
try { paintBrandUpdate(await api("/api/update")); }
|
|
1766
|
+
catch { scheduleUpdateCheck(clickedVersion ? 2500 : 60_000); }
|
|
1767
|
+
}, delay);
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
updateButton.addEventListener("click", async () => {
|
|
1771
|
+
if (!updateInfo || updateButton.disabled) return;
|
|
1772
|
+
const { status, version } = updateInfo;
|
|
1773
|
+
const promptText = status === "installed" ? `加载已安装的 v${version}?控制台会在会话空闲后重启。` : `在运行 claude-pro 的电脑上安装 v${version}?只会在会话空闲时开始。`;
|
|
1774
|
+
if (!confirm(promptText)) return;
|
|
1775
|
+
clearTimeout(updateTimer);
|
|
1776
|
+
updateButton.disabled = true;
|
|
1777
|
+
try {
|
|
1778
|
+
clickedVersion = version;
|
|
1779
|
+
paintBrandUpdate(await api("/api/update", { method: "POST", body: { version } }));
|
|
1780
|
+
} catch (e) {
|
|
1781
|
+
clickedVersion = null;
|
|
1782
|
+
paintBrandUpdate(updateInfo);
|
|
1783
|
+
fail(e);
|
|
1784
|
+
}
|
|
1785
|
+
});
|
|
1786
|
+
|
|
1787
|
+
// ---------------------------------------------------------------- start
|
|
1788
|
+
|
|
1789
|
+
const theme = localStorage.getItem("cpTheme") || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
|
|
1790
|
+
document.documentElement.dataset.theme = theme;
|
|
1791
|
+
$("#themeToggle").addEventListener("click", () => {
|
|
1792
|
+
const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
|
|
1793
|
+
document.documentElement.dataset.theme = next;
|
|
1794
|
+
localStorage.setItem("cpTheme", next);
|
|
1795
|
+
});
|
|
1796
|
+
window.addEventListener("hashchange", route);
|
|
1797
|
+
wireSidebar();
|
|
1798
|
+
// the account's menu: settings and the other pages
|
|
1799
|
+
function showUserMenu(open) {
|
|
1800
|
+
$("#userMenu").classList.toggle("hidden", !open);
|
|
1801
|
+
$("#sideMe").classList.toggle("open", open);
|
|
1802
|
+
$("#sideMe").setAttribute("aria-expanded", String(open));
|
|
1803
|
+
}
|
|
1804
|
+
$("#sideMe").addEventListener("click", () => showUserMenu($("#userMenu").classList.contains("hidden")));
|
|
1805
|
+
document.addEventListener("mousedown", (e) => { if (!e.target.closest("#userMenu, #sideMe")) showUserMenu(false); });
|
|
1806
|
+
document.addEventListener("keydown", (e) => { if (e.key === "Escape") showUserMenu(false); });
|
|
1807
|
+
const mobileLayout = matchMedia("(max-width: 860px)");
|
|
1808
|
+
const drawer = $(".side"), mobileMenu = $("#menuBtn");
|
|
1809
|
+
function setDrawer(open, { focus = false } = {}) {
|
|
1810
|
+
const mobile = mobileLayout.matches;
|
|
1811
|
+
open = mobile && open;
|
|
1812
|
+
if (focus && !open) mobileMenu.focus({ preventScroll: true });
|
|
1813
|
+
$(".app").classList.toggle("nav-open", open);
|
|
1814
|
+
mobileMenu.setAttribute("aria-expanded", String(open));
|
|
1815
|
+
drawer.inert = mobile && !open;
|
|
1816
|
+
main.inert = open;
|
|
1817
|
+
if (open && focus) $("#drawerClose")?.focus({ preventScroll: true });
|
|
1818
|
+
if (!open) showUserMenu(false);
|
|
1819
|
+
}
|
|
1820
|
+
const toggleDrawer = () => {
|
|
1821
|
+
closeMenu?.();
|
|
1822
|
+
setDrawer(!$(".app").classList.contains("nav-open"), { focus: true });
|
|
1823
|
+
};
|
|
1824
|
+
mobileMenu.addEventListener("click", toggleDrawer);
|
|
1825
|
+
$("#drawerClose")?.addEventListener("click", toggleDrawer);
|
|
1826
|
+
$("#sideBackdrop").addEventListener("click", () => { closeMenu?.(); setDrawer(false, { focus: true }); });
|
|
1827
|
+
drawer.addEventListener("click", (e) => { if (e.target.closest('a[href^="#/"]')) { closeMenu?.(); setDrawer(false); } });
|
|
1828
|
+
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !closeMenu && !$(".modal-back") && $(".app").classList.contains("nav-open")) setDrawer(false, { focus: true }); });
|
|
1829
|
+
mobileLayout.addEventListener("change", () => { closeMenu?.(); setDrawer(false); syncVisualHeight(); });
|
|
1830
|
+
function syncVisualHeight() {
|
|
1831
|
+
const viewport = window.visualViewport;
|
|
1832
|
+
if (!mobileLayout.matches || !viewport || Math.abs(viewport.scale - 1) > 0.03) { document.documentElement.style.removeProperty("--visible-height"); return; }
|
|
1833
|
+
document.documentElement.style.setProperty("--visible-height", `${Math.round(viewport.height)}px`);
|
|
1834
|
+
}
|
|
1835
|
+
window.visualViewport?.addEventListener("resize", syncVisualHeight);
|
|
1836
|
+
setDrawer(false);
|
|
1837
|
+
syncVisualHeight();
|
|
1838
|
+
$("#logoutBtn").addEventListener("click", async () => { await api("/api/logout", { method: "POST" }).catch(() => {}); location.reload(); });
|
|
1839
|
+
api("/api/ping").then((p) => {
|
|
1840
|
+
$("#brandVersion").textContent = `v${p.version}`;
|
|
1841
|
+
hasNativeFolderPicker = p.nativeFolderPicker === true;
|
|
1842
|
+
$("#remoteLinks").classList.toggle("hidden", !p.remote); // opened through 远程访问: switch computer, log out
|
|
1843
|
+
route();
|
|
1844
|
+
loadWorkspace();
|
|
1845
|
+
scheduleUpdateCheck();
|
|
1846
|
+
}).catch(() => {});
|
|
1847
|
+
// the sidebar follows the sessions (and keeps the server from stopping while the page is open)
|
|
1848
|
+
setInterval(() => { if (document.visibilityState === "visible") loadWorkspace(); else api("/api/ping").catch(() => {}); }, 5000);
|
|
1849
|
+
api("/api/overview").then((o) => { const who = o.gateway?.account?.name || o.gateway?.account?.email || o.host; $("#sideUser").textContent = who; $("#sideAvatar").textContent = String(who || "?").slice(0, 1).toUpperCase(); }).catch(() => {});
|
|
1850
|
+
})();
|