pi-hub-server 0.0.0-stage → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +403 -2
- package/bin/pi-hub.mjs +353 -0
- package/docs/AUTH.md +141 -0
- package/package.json +45 -4
- package/src/config.mjs +54 -0
- package/src/otp.mjs +162 -0
- package/src/pairing.mjs +403 -0
- package/src/pi-args.mjs +51 -0
- package/src/pi-session.mjs +635 -0
- package/src/proxy-auth.mjs +181 -0
- package/src/registry.mjs +145 -0
- package/src/rpc-once.mjs +83 -0
- package/src/server.mjs +1532 -0
- package/src/session-lock.mjs +42 -0
- package/src/sessions-index.mjs +179 -0
- package/src/static.mjs +148 -0
- package/src/totp.mjs +151 -0
- package/src/update-check.mjs +218 -0
- package/src/web-auth.mjs +450 -0
- package/systemd/pi-hub.service +22 -0
- package/web/app.js +1339 -0
- package/web/icons/icon.svg +7 -0
- package/web/index.html +121 -0
- package/web/manifest.webmanifest +20 -0
- package/web/style.css +782 -0
- package/web/sw.js +45 -0
package/web/app.js
ADDED
|
@@ -0,0 +1,1339 @@
|
|
|
1
|
+
// pi hub 网页端:原生 ES module(无 CDN、无框架、无构建)。
|
|
2
|
+
// 鉴权:cookie 会话(GET 免 CSRF,非 GET 带 x-pi-csrf)。上传与流式都走同源 /v1。
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
const $ = (id) => document.getElementById(id);
|
|
6
|
+
|
|
7
|
+
const STORE_KEYS = { session: "pihub.session", cwd: "pihub.cwd" };
|
|
8
|
+
const IMAGE_MAX_EDGE = 1568;
|
|
9
|
+
const IMAGE_QUALITY = 0.82;
|
|
10
|
+
|
|
11
|
+
const state = {
|
|
12
|
+
csrf: null,
|
|
13
|
+
sessions: [],
|
|
14
|
+
sessionId: null,
|
|
15
|
+
session: null,
|
|
16
|
+
items: [],
|
|
17
|
+
stream: null,
|
|
18
|
+
models: [],
|
|
19
|
+
levels: [],
|
|
20
|
+
level: null,
|
|
21
|
+
streaming: false,
|
|
22
|
+
images: [],
|
|
23
|
+
docs: [],
|
|
24
|
+
stats: null,
|
|
25
|
+
usage: null,
|
|
26
|
+
search: "",
|
|
27
|
+
pinned: true,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function store(key, value) {
|
|
31
|
+
try {
|
|
32
|
+
if (value === undefined) return localStorage.getItem(key);
|
|
33
|
+
localStorage.setItem(key, value);
|
|
34
|
+
} catch {
|
|
35
|
+
// 隐私模式下 localStorage 可能不可写:会话记忆丢失不算错误
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
class ApiError extends Error {
|
|
41
|
+
constructor(status, code, message) {
|
|
42
|
+
super(message || `HTTP ${status}`);
|
|
43
|
+
this.status = status;
|
|
44
|
+
this.code = code;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function request(path, { method = "GET", body, raw = false, contentType } = {}) {
|
|
49
|
+
const headers = {};
|
|
50
|
+
const opts = { method, credentials: "same-origin", headers };
|
|
51
|
+
if (body !== undefined && body !== null) {
|
|
52
|
+
if (raw) {
|
|
53
|
+
opts.body = body;
|
|
54
|
+
if (contentType) headers["content-type"] = contentType;
|
|
55
|
+
} else {
|
|
56
|
+
headers["content-type"] = "application/json";
|
|
57
|
+
opts.body = JSON.stringify(body);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (method !== "GET" && method !== "HEAD" && state.csrf) headers["x-pi-csrf"] = state.csrf;
|
|
61
|
+
const res = await fetch(path, opts);
|
|
62
|
+
const text = await res.text();
|
|
63
|
+
let payload = null;
|
|
64
|
+
if (text) {
|
|
65
|
+
try {
|
|
66
|
+
payload = JSON.parse(text);
|
|
67
|
+
} catch {
|
|
68
|
+
payload = null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (!res.ok) {
|
|
72
|
+
throw new ApiError(res.status, payload?.error?.code ?? null, payload?.error?.message ?? `HTTP ${res.status}`);
|
|
73
|
+
}
|
|
74
|
+
return payload;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** CSRF 过期/会话重建时刷新一次再重试(其余错误原样抛)。 */
|
|
78
|
+
async function api(path, options = {}) {
|
|
79
|
+
try {
|
|
80
|
+
return await request(path, options);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
if (err instanceof ApiError && err.code === "csrf") {
|
|
83
|
+
await loadCsrf();
|
|
84
|
+
return await request(path, options);
|
|
85
|
+
}
|
|
86
|
+
throw err;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ---------- markdown(自研轻渲染:先转义再拼标签,代码块整体转义) ----------
|
|
91
|
+
|
|
92
|
+
const HTML_ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
93
|
+
|
|
94
|
+
function escapeHtml(value) {
|
|
95
|
+
return String(value ?? "").replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function safeHref(href) {
|
|
99
|
+
const raw = href.replace(/&/g, "&");
|
|
100
|
+
if (/^https?:\/\//i.test(raw) || /^mailto:/i.test(raw) || raw.startsWith("/")) return true;
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 输入必须是已转义文本,输出只含我们自己生成的标签。 */
|
|
105
|
+
function inlineMarkdown(escaped) {
|
|
106
|
+
let out = escaped;
|
|
107
|
+
out = out.replace(/`([^`\n]+)`/g, "<code>$1</code>");
|
|
108
|
+
out = out.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>");
|
|
109
|
+
out = out.replace(/(^|[\s(])\*([^*\s][^*\n]*)\*/g, "$1<em>$2</em>");
|
|
110
|
+
out = out.replace(/~~([^~\n]+)~~/g, "<del>$1</del>");
|
|
111
|
+
out = out.replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, (match, label, href) =>
|
|
112
|
+
safeHref(href) ? `<a href="${href}" target="_blank" rel="noopener noreferrer">${label}</a>` : label,
|
|
113
|
+
);
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function isTableSeparator(line) {
|
|
118
|
+
return /^\s*\|?[\s:-]*-[\s|:-]*$/.test(line) && line.includes("-");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function renderMarkdown(source) {
|
|
122
|
+
const lines = String(source ?? "").replace(/\r\n?/g, "\n").split("\n");
|
|
123
|
+
const out = [];
|
|
124
|
+
let para = [];
|
|
125
|
+
const flush = () => {
|
|
126
|
+
if (para.length) {
|
|
127
|
+
out.push(`<p>${para.map((l) => inlineMarkdown(escapeHtml(l))).join("<br>")}</p>`);
|
|
128
|
+
para = [];
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
let i = 0;
|
|
133
|
+
while (i < lines.length) {
|
|
134
|
+
const line = lines[i];
|
|
135
|
+
|
|
136
|
+
// 代码块:内容整体转义,语言标记只用于角标
|
|
137
|
+
const fence = /^\s{0,3}(`{3,}|~{3,})\s*([\w+-]*)\s*$/.exec(line);
|
|
138
|
+
if (fence) {
|
|
139
|
+
flush();
|
|
140
|
+
const marker = fence[1][0];
|
|
141
|
+
const lang = fence[2] || "";
|
|
142
|
+
const body = [];
|
|
143
|
+
i += 1;
|
|
144
|
+
while (i < lines.length) {
|
|
145
|
+
const closing = new RegExp(`^\\s{0,3}${marker}{${fence[1].length},}\\s*$`);
|
|
146
|
+
if (closing.test(lines[i])) {
|
|
147
|
+
i += 1;
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
body.push(lines[i]);
|
|
151
|
+
i += 1;
|
|
152
|
+
}
|
|
153
|
+
out.push(
|
|
154
|
+
`<div class="code-card"><div class="code-head"><span>${escapeHtml(lang || "code")}</span>` +
|
|
155
|
+
`<button type="button" class="copy" data-copy>复制</button></div>` +
|
|
156
|
+
`<pre><code>${escapeHtml(body.join("\n"))}</code></pre></div>`,
|
|
157
|
+
);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (/^\s*$/.test(line)) {
|
|
162
|
+
flush();
|
|
163
|
+
i += 1;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const heading = /^\s{0,3}(#{1,6})\s+(.*)$/.exec(line);
|
|
168
|
+
if (heading) {
|
|
169
|
+
flush();
|
|
170
|
+
const level = Math.min(heading[1].length, 4);
|
|
171
|
+
out.push(`<h${level}>${inlineMarkdown(escapeHtml(heading[2]))}</h${level}>`);
|
|
172
|
+
i += 1;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(line)) {
|
|
177
|
+
flush();
|
|
178
|
+
out.push("<hr />");
|
|
179
|
+
i += 1;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const quote = /^\s{0,3}>\s?(.*)$/.exec(line);
|
|
184
|
+
if (quote) {
|
|
185
|
+
flush();
|
|
186
|
+
const body = [];
|
|
187
|
+
while (i < lines.length) {
|
|
188
|
+
const q = /^\s{0,3}>\s?(.*)$/.exec(lines[i]);
|
|
189
|
+
if (!q) break;
|
|
190
|
+
body.push(q[1]);
|
|
191
|
+
i += 1;
|
|
192
|
+
}
|
|
193
|
+
out.push(`<blockquote>${inlineMarkdown(escapeHtml(body.join("\n")))}</blockquote>`);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const bullet = /^\s{0,3}([-*+])\s+(.*)$/.exec(line);
|
|
198
|
+
const numbered = /^\s{0,3}(\d{1,9})[.)]\s+(.*)$/.exec(line);
|
|
199
|
+
if (bullet || numbered) {
|
|
200
|
+
flush();
|
|
201
|
+
const ordered = Boolean(numbered);
|
|
202
|
+
const items = [];
|
|
203
|
+
while (i < lines.length) {
|
|
204
|
+
const b = ordered ? /^\s{0,3}(\d{1,9})[.)]\s+(.*)$/.exec(lines[i]) : /^\s{0,3}([-*+])\s+(.*)$/.exec(lines[i]);
|
|
205
|
+
if (!b) break;
|
|
206
|
+
items.push(`<li>${inlineMarkdown(escapeHtml(b[2]))}</li>`);
|
|
207
|
+
i += 1;
|
|
208
|
+
}
|
|
209
|
+
out.push(ordered ? `<ol>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// 表格:表头 + 分隔行才认,否则按普通段落
|
|
214
|
+
if (line.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
|
|
215
|
+
flush();
|
|
216
|
+
const cells = (row) =>
|
|
217
|
+
row
|
|
218
|
+
.replace(/^\s*\|/, "")
|
|
219
|
+
.replace(/\|\s*$/, "")
|
|
220
|
+
.split("|")
|
|
221
|
+
.map((c) => inlineMarkdown(escapeHtml(c.trim())));
|
|
222
|
+
const head = cells(line);
|
|
223
|
+
i += 2;
|
|
224
|
+
const rows = [];
|
|
225
|
+
while (i < lines.length && lines[i].includes("|") && !/^\s*$/.test(lines[i])) {
|
|
226
|
+
rows.push(`<tr>${cells(lines[i]).map((c) => `<td>${c}</td>`).join("")}</tr>`);
|
|
227
|
+
i += 1;
|
|
228
|
+
}
|
|
229
|
+
out.push(
|
|
230
|
+
`<table><thead><tr>${head.map((c) => `<th>${c}</th>`).join("")}</tr></thead><tbody>${rows.join("")}</tbody></table>`,
|
|
231
|
+
);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
para.push(line);
|
|
236
|
+
i += 1;
|
|
237
|
+
}
|
|
238
|
+
flush();
|
|
239
|
+
return out.join("");
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------- 会话列表 ----------
|
|
243
|
+
|
|
244
|
+
function formatTime(iso) {
|
|
245
|
+
const ts = Date.parse(iso);
|
|
246
|
+
if (!Number.isFinite(ts)) return "";
|
|
247
|
+
const diff = Date.now() - ts;
|
|
248
|
+
if (diff < 60_000) return "刚刚";
|
|
249
|
+
if (diff < 3_600_000) return `${Math.floor(diff / 60_000)} 分钟前`;
|
|
250
|
+
if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)} 小时前`;
|
|
251
|
+
const d = new Date(ts);
|
|
252
|
+
return `${d.getMonth() + 1}/${d.getDate()} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function groupSessions(sessions) {
|
|
256
|
+
const groups = new Map();
|
|
257
|
+
for (const s of sessions) {
|
|
258
|
+
const cwd = s.cwd || "(未知工作区)";
|
|
259
|
+
if (!groups.has(cwd)) groups.set(cwd, []);
|
|
260
|
+
groups.get(cwd).push(s);
|
|
261
|
+
}
|
|
262
|
+
return [...groups.entries()]
|
|
263
|
+
.map(([cwd, rows]) => ({ cwd, rows: rows.slice().sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt)) }))
|
|
264
|
+
.sort((a, b) => Date.parse(b.rows[0].updatedAt) - Date.parse(a.rows[0].updatedAt));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function loadSessions() {
|
|
268
|
+
const data = await api("/v1/sessions?limit=200");
|
|
269
|
+
state.sessions = data?.sessions ?? [];
|
|
270
|
+
renderDrawer();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function renderDrawer() {
|
|
274
|
+
const list = $("session-list");
|
|
275
|
+
list.textContent = "";
|
|
276
|
+
const needle = state.search.trim().toLowerCase();
|
|
277
|
+
const filtered = needle
|
|
278
|
+
? state.sessions.filter((s) =>
|
|
279
|
+
[s.name, s.preview, s.cwd].filter(Boolean).some((v) => String(v).toLowerCase().includes(needle)),
|
|
280
|
+
)
|
|
281
|
+
: state.sessions;
|
|
282
|
+
|
|
283
|
+
if (!filtered.length) {
|
|
284
|
+
const empty = document.createElement("div");
|
|
285
|
+
empty.className = "empty";
|
|
286
|
+
empty.textContent = needle ? "没有匹配的会话" : "还没有会话,下面新建一个";
|
|
287
|
+
list.append(empty);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
for (const group of groupSessions(filtered)) {
|
|
291
|
+
const title = document.createElement("div");
|
|
292
|
+
title.className = "group-title";
|
|
293
|
+
title.textContent = group.cwd;
|
|
294
|
+
title.title = group.cwd;
|
|
295
|
+
list.append(title);
|
|
296
|
+
for (const row of group.rows) {
|
|
297
|
+
const item = document.createElement("div");
|
|
298
|
+
item.className = "session-item" + (row.id === state.sessionId ? " active" : "");
|
|
299
|
+
const name = document.createElement("div");
|
|
300
|
+
name.className = "name";
|
|
301
|
+
name.textContent = row.name || row.preview || row.id.slice(0, 8);
|
|
302
|
+
const line = document.createElement("div");
|
|
303
|
+
line.className = "line";
|
|
304
|
+
const badge = document.createElement("span");
|
|
305
|
+
badge.className = "badge" + (row.live ? " live" : "");
|
|
306
|
+
badge.textContent = row.live ? "运行中" : formatTime(row.updatedAt);
|
|
307
|
+
line.append(badge, document.createTextNode(` ${row.preview || ""}`));
|
|
308
|
+
item.append(name, line);
|
|
309
|
+
item.addEventListener("click", () => openSession(row.id));
|
|
310
|
+
list.append(item);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const datalist = $("cwd-options");
|
|
315
|
+
datalist.textContent = "";
|
|
316
|
+
for (const cwd of [...new Set(state.sessions.map((s) => s.cwd).filter(Boolean))]) {
|
|
317
|
+
const option = document.createElement("option");
|
|
318
|
+
option.value = cwd;
|
|
319
|
+
datalist.append(option);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ---------- 消息渲染 ----------
|
|
324
|
+
|
|
325
|
+
function lastAssistant() {
|
|
326
|
+
for (let i = state.items.length - 1; i >= 0; i -= 1) {
|
|
327
|
+
if (state.items[i].role === "assistant") return state.items[i];
|
|
328
|
+
}
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function ensureAssistant() {
|
|
333
|
+
const current = lastAssistant();
|
|
334
|
+
if (current && current.streaming) return current;
|
|
335
|
+
const item = {
|
|
336
|
+
role: "assistant",
|
|
337
|
+
text: "",
|
|
338
|
+
thinking: "",
|
|
339
|
+
tools: new Map(),
|
|
340
|
+
toolOrder: [],
|
|
341
|
+
streaming: true,
|
|
342
|
+
usage: null,
|
|
343
|
+
model: null,
|
|
344
|
+
ts: Date.now(),
|
|
345
|
+
el: null,
|
|
346
|
+
refs: null,
|
|
347
|
+
};
|
|
348
|
+
state.items.push(item);
|
|
349
|
+
appendItemEl(item);
|
|
350
|
+
return item;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function createToolCard(item, tool) {
|
|
354
|
+
const card = document.createElement("details");
|
|
355
|
+
card.className = "tool-card";
|
|
356
|
+
const summary = document.createElement("summary");
|
|
357
|
+
const name = document.createElement("span");
|
|
358
|
+
name.className = "tool-name";
|
|
359
|
+
const status = document.createElement("span");
|
|
360
|
+
status.className = "tool-state";
|
|
361
|
+
summary.append(name, status);
|
|
362
|
+
const body = document.createElement("div");
|
|
363
|
+
body.className = "tool-body";
|
|
364
|
+
const pre = document.createElement("pre");
|
|
365
|
+
body.append(pre);
|
|
366
|
+
card.append(summary, body);
|
|
367
|
+
const existing = item.refs.toolEls.get(tool.id);
|
|
368
|
+
if (existing) existing.remove();
|
|
369
|
+
item.refs.toolEls.set(tool.id, card);
|
|
370
|
+
item.refs.tools.append(card);
|
|
371
|
+
return card;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function toolStateText(tool) {
|
|
375
|
+
if (tool.isError) return "失败";
|
|
376
|
+
if (tool.state === "done") return tool.durationMs ? `完成 · ${Math.round(tool.durationMs)}ms` : "完成";
|
|
377
|
+
if (tool.state === "running") return "运行中…";
|
|
378
|
+
return "排队中";
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function toolBodyText(tool) {
|
|
382
|
+
if (tool.preview) return tool.preview;
|
|
383
|
+
if (tool.args !== undefined) {
|
|
384
|
+
try {
|
|
385
|
+
return JSON.stringify(tool.args, null, 2);
|
|
386
|
+
} catch {
|
|
387
|
+
return String(tool.args);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return "";
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function buildItemEl(item) {
|
|
394
|
+
const wrap = document.createElement("div");
|
|
395
|
+
wrap.className = `msg ${item.role}`;
|
|
396
|
+
|
|
397
|
+
if (item.role === "user") {
|
|
398
|
+
const bubble = document.createElement("div");
|
|
399
|
+
bubble.className = "bubble md";
|
|
400
|
+
wrap.append(bubble);
|
|
401
|
+
item.refs = { bubble };
|
|
402
|
+
item.el = wrap;
|
|
403
|
+
return wrap;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const thinking = document.createElement("details");
|
|
407
|
+
thinking.className = "thinking-block";
|
|
408
|
+
const summary = document.createElement("summary");
|
|
409
|
+
summary.textContent = "思考过程";
|
|
410
|
+
const thinkingBody = document.createElement("div");
|
|
411
|
+
thinkingBody.className = "thinking-body";
|
|
412
|
+
thinking.append(summary, thinkingBody);
|
|
413
|
+
|
|
414
|
+
const bubble = document.createElement("div");
|
|
415
|
+
bubble.className = "bubble md";
|
|
416
|
+
const tools = document.createElement("div");
|
|
417
|
+
tools.className = "tools";
|
|
418
|
+
const meta = document.createElement("div");
|
|
419
|
+
meta.className = "meta";
|
|
420
|
+
|
|
421
|
+
wrap.append(thinking, bubble, tools, meta);
|
|
422
|
+
item.refs = { thinking, thinkingBody, bubble, tools, meta, toolEls: new Map() };
|
|
423
|
+
item.el = wrap;
|
|
424
|
+
return wrap;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function appendItemEl(item) {
|
|
428
|
+
const box = $("messages");
|
|
429
|
+
const empty = box.querySelector(".empty");
|
|
430
|
+
if (empty) empty.remove();
|
|
431
|
+
const el = buildItemEl(item);
|
|
432
|
+
box.append(el);
|
|
433
|
+
patchItem(item);
|
|
434
|
+
if (state.pinned) scrollToBottom();
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function patchItem(item) {
|
|
438
|
+
const refs = item.refs;
|
|
439
|
+
if (!refs) return;
|
|
440
|
+
if (item.role === "user") {
|
|
441
|
+
refs.bubble.innerHTML = renderMarkdown(item.text);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (item.thinking) {
|
|
445
|
+
refs.thinking.hidden = false;
|
|
446
|
+
refs.thinkingBody.textContent = item.thinking;
|
|
447
|
+
// 用户手动折叠/展开过就不再自动覆盖;否则流式中展开、结束后收起
|
|
448
|
+
const touched = refs.thinking.dataset.touched === "1";
|
|
449
|
+
refs.thinking.open = touched ? refs.thinking.open : item.streaming;
|
|
450
|
+
}
|
|
451
|
+
refs.bubble.innerHTML = renderMarkdown(item.text) + (item.streaming ? '<span class="typing"></span>' : "");
|
|
452
|
+
for (const id of item.toolOrder) {
|
|
453
|
+
const tool = item.tools.get(id);
|
|
454
|
+
if (!tool) continue;
|
|
455
|
+
const card = refs.toolEls.get(id) ?? createToolCard(item, tool);
|
|
456
|
+
card.querySelector(".tool-name").textContent = tool.name || "tool";
|
|
457
|
+
const status = card.querySelector(".tool-state");
|
|
458
|
+
status.textContent = toolStateText(tool);
|
|
459
|
+
status.classList.toggle("err", Boolean(tool.isError));
|
|
460
|
+
const pre = card.querySelector("pre");
|
|
461
|
+
const body = toolBodyText(tool);
|
|
462
|
+
if (pre.textContent !== body) pre.textContent = body;
|
|
463
|
+
if (tool.state === "running") card.open = true;
|
|
464
|
+
}
|
|
465
|
+
const metaParts = [];
|
|
466
|
+
if (item.model) metaParts.push(item.model);
|
|
467
|
+
if (item.durationMs) metaParts.push(`${(item.durationMs / 1000).toFixed(1)}s`);
|
|
468
|
+
if (item.usage?.totalTokens) metaParts.push(`${formatTokens(item.usage.totalTokens)} tokens`);
|
|
469
|
+
if (item.stopReason && item.stopReason !== "stop") metaParts.push(item.stopReason);
|
|
470
|
+
refs.meta.textContent = metaParts.join(" · ");
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function formatTokens(n) {
|
|
474
|
+
const v = Number(n) || 0;
|
|
475
|
+
if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
|
|
476
|
+
if (v >= 1000) return `${(v / 1000).toFixed(1)}k`;
|
|
477
|
+
return String(v);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function renderMessages() {
|
|
481
|
+
const box = $("messages");
|
|
482
|
+
box.textContent = "";
|
|
483
|
+
if (!state.items.length) {
|
|
484
|
+
const empty = document.createElement("div");
|
|
485
|
+
empty.className = "empty";
|
|
486
|
+
empty.textContent = state.sessionId ? "还没有消息,直接发第一条吧。" : "从左上角选一个会话,或新建一个。";
|
|
487
|
+
box.append(empty);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
for (const item of state.items) {
|
|
491
|
+
const el = buildItemEl(item);
|
|
492
|
+
box.append(el);
|
|
493
|
+
patchItem(item);
|
|
494
|
+
}
|
|
495
|
+
scrollToBottom();
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function scrollToBottom() {
|
|
499
|
+
const box = $("messages");
|
|
500
|
+
box.scrollTop = box.scrollHeight;
|
|
501
|
+
state.pinned = true;
|
|
502
|
+
$("btn-jump").hidden = true;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function historyToItems(messages) {
|
|
506
|
+
const items = [];
|
|
507
|
+
for (const m of messages ?? []) {
|
|
508
|
+
if (m.role === "user") {
|
|
509
|
+
items.push({ role: "user", text: m.text ?? "", ts: m.ts });
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (m.role !== "assistant") continue;
|
|
513
|
+
const toolMap = new Map();
|
|
514
|
+
const order = [];
|
|
515
|
+
for (const call of m.toolCalls ?? []) {
|
|
516
|
+
if (!call?.id) continue;
|
|
517
|
+
toolMap.set(call.id, { id: call.id, name: call.name ?? "tool", args: call.args, state: "done" });
|
|
518
|
+
order.push(call.id);
|
|
519
|
+
}
|
|
520
|
+
items.push({
|
|
521
|
+
role: "assistant",
|
|
522
|
+
text: m.text ?? "",
|
|
523
|
+
thinking: m.thinking ?? "",
|
|
524
|
+
tools: toolMap,
|
|
525
|
+
toolOrder: order,
|
|
526
|
+
streaming: false,
|
|
527
|
+
usage: m.usage ?? null,
|
|
528
|
+
model: m.model ?? null,
|
|
529
|
+
durationMs: m.durationMs ?? null,
|
|
530
|
+
stopReason: m.stopReason ?? null,
|
|
531
|
+
ts: m.ts,
|
|
532
|
+
el: null,
|
|
533
|
+
refs: null,
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
return items;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ---------- 用量 ----------
|
|
540
|
+
|
|
541
|
+
function renderUsage() {
|
|
542
|
+
const bar = $("usage-bar");
|
|
543
|
+
const ctx = state.stats?.contextUsage ?? null;
|
|
544
|
+
const parts = [];
|
|
545
|
+
if (ctx && Number.isFinite(ctx.percent)) {
|
|
546
|
+
const pct = Math.round(ctx.percent);
|
|
547
|
+
const used = formatTokens(ctx.tokens);
|
|
548
|
+
const window = ctx.contextWindow ? ` / ${formatTokens(ctx.contextWindow)}` : "";
|
|
549
|
+
parts.push(`上下文 ${pct}% · ${used}${window}`);
|
|
550
|
+
} else if (state.usage?.totalTokens) {
|
|
551
|
+
parts.push(`本机累计 ${formatTokens(state.usage.totalTokens)} tokens`);
|
|
552
|
+
}
|
|
553
|
+
const cost = state.stats?.cost ?? state.usage?.cost ?? null;
|
|
554
|
+
$("usage-context").textContent = parts.join(" · ");
|
|
555
|
+
$("usage-cost").textContent = typeof cost === "number" && cost > 0 ? `$${cost.toFixed(4)}` : "";
|
|
556
|
+
bar.hidden = !(parts.length || $("usage-cost").textContent);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
async function refreshStats() {
|
|
560
|
+
if (!state.sessionId) return;
|
|
561
|
+
try {
|
|
562
|
+
const data = await api(`/v1/sessions/${state.sessionId}/stats`);
|
|
563
|
+
state.stats = data?.stats ?? null;
|
|
564
|
+
renderUsage();
|
|
565
|
+
} catch {
|
|
566
|
+
// 统计失败不影响聊天
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// ---------- 流式 ----------
|
|
571
|
+
|
|
572
|
+
function setConn(cls, title) {
|
|
573
|
+
const dot = $("conn-dot");
|
|
574
|
+
dot.className = `dot ${cls}`;
|
|
575
|
+
dot.title = title;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function connectStream() {
|
|
579
|
+
if (state.stream) {
|
|
580
|
+
state.stream.close();
|
|
581
|
+
state.stream = null;
|
|
582
|
+
}
|
|
583
|
+
if (!state.sessionId) return;
|
|
584
|
+
setConn("busy", "连接中");
|
|
585
|
+
const es = new EventSource(`/v1/sessions/${state.sessionId}/events?since=0`);
|
|
586
|
+
state.stream = es;
|
|
587
|
+
es.onopen = () => setConn("", "已连接");
|
|
588
|
+
es.onerror = () => setConn("off", "连接断开,浏览器会自动重连");
|
|
589
|
+
es.onmessage = (event) => {
|
|
590
|
+
let payload = null;
|
|
591
|
+
try {
|
|
592
|
+
payload = JSON.parse(event.data);
|
|
593
|
+
} catch {
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
handleEvent(payload);
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function handleEvent(ev) {
|
|
601
|
+
switch (ev.type) {
|
|
602
|
+
case "ready": {
|
|
603
|
+
if (ev.session) applySession(ev.session);
|
|
604
|
+
break;
|
|
605
|
+
}
|
|
606
|
+
case "user_message": {
|
|
607
|
+
state.items.push({ role: "user", text: ev.text ?? "", ts: ev.ts, el: null, refs: null });
|
|
608
|
+
appendItemEl(state.items[state.items.length - 1]);
|
|
609
|
+
break;
|
|
610
|
+
}
|
|
611
|
+
case "assistant_start": {
|
|
612
|
+
const item = ensureAssistant();
|
|
613
|
+
item.streaming = true;
|
|
614
|
+
patchItem(item);
|
|
615
|
+
setStreamingUi(true);
|
|
616
|
+
break;
|
|
617
|
+
}
|
|
618
|
+
case "text_delta": {
|
|
619
|
+
const item = ensureAssistant();
|
|
620
|
+
item.text += ev.delta ?? "";
|
|
621
|
+
patchItem(item);
|
|
622
|
+
if (state.pinned) scrollToBottom();
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
case "text_end": {
|
|
626
|
+
const item = ensureAssistant();
|
|
627
|
+
item.text = ev.text ?? item.text;
|
|
628
|
+
patchItem(item);
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
case "thinking_delta": {
|
|
632
|
+
const item = ensureAssistant();
|
|
633
|
+
item.thinking += ev.delta ?? "";
|
|
634
|
+
patchItem(item);
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
637
|
+
case "thinking_end": {
|
|
638
|
+
const item = ensureAssistant();
|
|
639
|
+
item.thinking = ev.text ?? item.thinking;
|
|
640
|
+
patchItem(item);
|
|
641
|
+
break;
|
|
642
|
+
}
|
|
643
|
+
case "tool_call":
|
|
644
|
+
case "tool_start":
|
|
645
|
+
case "tool_progress":
|
|
646
|
+
case "tool_end": {
|
|
647
|
+
const item = ensureAssistant();
|
|
648
|
+
const id = ev.id ?? `${ev.name}-${item.toolOrder.length}`;
|
|
649
|
+
let tool = item.tools.get(id);
|
|
650
|
+
if (!tool) {
|
|
651
|
+
tool = { id, name: ev.name ?? "tool", args: ev.args, state: "queued", preview: null, isError: false };
|
|
652
|
+
item.tools.set(id, tool);
|
|
653
|
+
item.toolOrder.push(id);
|
|
654
|
+
}
|
|
655
|
+
if (ev.args !== undefined) tool.args = ev.args;
|
|
656
|
+
if (ev.type === "tool_start") tool.state = "running";
|
|
657
|
+
if (ev.type === "tool_call") tool.state = tool.state === "running" ? "running" : "queued";
|
|
658
|
+
if (ev.type === "tool_progress") {
|
|
659
|
+
tool.state = "running";
|
|
660
|
+
tool.preview = ev.preview ?? tool.preview;
|
|
661
|
+
}
|
|
662
|
+
if (ev.type === "tool_end") {
|
|
663
|
+
tool.state = "done";
|
|
664
|
+
tool.isError = ev.isError === true;
|
|
665
|
+
tool.durationMs = ev.durationMs ?? null;
|
|
666
|
+
tool.preview = ev.preview ?? tool.preview;
|
|
667
|
+
}
|
|
668
|
+
patchItem(item);
|
|
669
|
+
if (state.pinned) scrollToBottom();
|
|
670
|
+
break;
|
|
671
|
+
}
|
|
672
|
+
case "assistant_message": {
|
|
673
|
+
const item = ensureAssistant();
|
|
674
|
+
item.text = ev.text ?? item.text;
|
|
675
|
+
if (ev.thinking !== undefined) item.thinking = ev.thinking;
|
|
676
|
+
item.streaming = false;
|
|
677
|
+
patchItem(item);
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
case "turn_end": {
|
|
681
|
+
const item = lastAssistant();
|
|
682
|
+
if (item && ev.usage) {
|
|
683
|
+
item.usage = ev.usage;
|
|
684
|
+
state.usage = ev.usage;
|
|
685
|
+
patchItem(item);
|
|
686
|
+
renderUsage();
|
|
687
|
+
}
|
|
688
|
+
break;
|
|
689
|
+
}
|
|
690
|
+
case "settled": {
|
|
691
|
+
const item = lastAssistant();
|
|
692
|
+
if (item) {
|
|
693
|
+
item.streaming = false;
|
|
694
|
+
patchItem(item);
|
|
695
|
+
}
|
|
696
|
+
setStreamingUi(false);
|
|
697
|
+
refreshStats();
|
|
698
|
+
break;
|
|
699
|
+
}
|
|
700
|
+
case "status": {
|
|
701
|
+
const busy = ev.status === "running" || ev.status === "thinking" || ev.status === "compacting";
|
|
702
|
+
setConn(busy ? "busy" : "", busy ? `状态:${ev.status}` : "空闲");
|
|
703
|
+
setStreamingUi(busy);
|
|
704
|
+
break;
|
|
705
|
+
}
|
|
706
|
+
case "session_renamed": {
|
|
707
|
+
if (ev.name) {
|
|
708
|
+
$("session-title").textContent = ev.name;
|
|
709
|
+
if (state.session) state.session.name = ev.name;
|
|
710
|
+
}
|
|
711
|
+
loadSessions().catch(() => {});
|
|
712
|
+
break;
|
|
713
|
+
}
|
|
714
|
+
case "queue": {
|
|
715
|
+
const n = (ev.steering?.length ?? 0) + (ev.followUp?.length ?? 0);
|
|
716
|
+
$("session-sub").textContent = n ? `排队 ${n} 条` : "";
|
|
717
|
+
break;
|
|
718
|
+
}
|
|
719
|
+
case "compaction_end": {
|
|
720
|
+
toast("上下文已压缩");
|
|
721
|
+
refreshStats();
|
|
722
|
+
break;
|
|
723
|
+
}
|
|
724
|
+
case "ui_request": {
|
|
725
|
+
renderUiRequest(ev);
|
|
726
|
+
break;
|
|
727
|
+
}
|
|
728
|
+
case "ui_notify": {
|
|
729
|
+
if (ev.message || ev.text) toast(ev.message ?? ev.text);
|
|
730
|
+
break;
|
|
731
|
+
}
|
|
732
|
+
case "error": {
|
|
733
|
+
toast(`会话错误:${ev.message ?? "未知"}`);
|
|
734
|
+
break;
|
|
735
|
+
}
|
|
736
|
+
case "closed": {
|
|
737
|
+
setConn("off", "子进程已退出");
|
|
738
|
+
setStreamingUi(false);
|
|
739
|
+
break;
|
|
740
|
+
}
|
|
741
|
+
default:
|
|
742
|
+
break;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function setStreamingUi(busy) {
|
|
747
|
+
state.streaming = busy;
|
|
748
|
+
$("btn-send").hidden = busy;
|
|
749
|
+
$("btn-stop").hidden = !busy;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// ---------- UI 对话框(扩展 UI 桥) ----------
|
|
753
|
+
|
|
754
|
+
function renderUiRequest(ev) {
|
|
755
|
+
const box = $("ui-requests");
|
|
756
|
+
const wrap = document.createElement("div");
|
|
757
|
+
wrap.className = "ui-request";
|
|
758
|
+
const title = document.createElement("div");
|
|
759
|
+
title.textContent = ev.title || ev.message || "需要你的确认";
|
|
760
|
+
wrap.append(title);
|
|
761
|
+
const row = document.createElement("div");
|
|
762
|
+
row.className = "row";
|
|
763
|
+
const answer = async (payload) => {
|
|
764
|
+
try {
|
|
765
|
+
await api(`/v1/sessions/${state.sessionId}/ui/${ev.uiId}`, { method: "POST", body: payload });
|
|
766
|
+
wrap.remove();
|
|
767
|
+
if (!box.children.length) box.hidden = true;
|
|
768
|
+
} catch (err) {
|
|
769
|
+
toast(`回答失败:${err.message}`);
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
const button = (label, payload, cls = "btn") => {
|
|
773
|
+
const b = document.createElement("button");
|
|
774
|
+
b.type = "button";
|
|
775
|
+
b.className = cls;
|
|
776
|
+
b.textContent = label;
|
|
777
|
+
b.addEventListener("click", () => answer(payload));
|
|
778
|
+
row.append(b);
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
if (ev.method === "select") {
|
|
782
|
+
for (const option of ev.options ?? []) {
|
|
783
|
+
const value = typeof option === "string" ? option : (option.value ?? option.label);
|
|
784
|
+
button(typeof option === "string" ? option : (option.label ?? String(value)), { value: String(value) });
|
|
785
|
+
}
|
|
786
|
+
} else if (ev.method === "confirm") {
|
|
787
|
+
button("确定", { confirmed: true }, "btn primary");
|
|
788
|
+
button("取消", { confirmed: false });
|
|
789
|
+
} else {
|
|
790
|
+
const input = document.createElement("input");
|
|
791
|
+
input.type = "text";
|
|
792
|
+
input.placeholder = ev.placeholder ?? "";
|
|
793
|
+
input.value = ev.prefill ?? "";
|
|
794
|
+
row.append(input);
|
|
795
|
+
button("提交", null, "btn primary");
|
|
796
|
+
row.lastChild.addEventListener("click", () => answer({ value: input.value }));
|
|
797
|
+
}
|
|
798
|
+
button("取消", { cancelled: true });
|
|
799
|
+
wrap.append(row);
|
|
800
|
+
box.hidden = false;
|
|
801
|
+
box.append(wrap);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// ---------- 发送 / 附件 ----------
|
|
805
|
+
|
|
806
|
+
function autosize() {
|
|
807
|
+
const el = $("prompt");
|
|
808
|
+
el.style.height = "auto";
|
|
809
|
+
el.style.height = `${Math.min(el.scrollHeight, window.innerHeight * 0.4)}px`;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
function renderAttachments() {
|
|
813
|
+
const box = $("attachments");
|
|
814
|
+
box.textContent = "";
|
|
815
|
+
for (const [index, img] of state.images.entries()) {
|
|
816
|
+
const chip = document.createElement("span");
|
|
817
|
+
chip.className = "chip";
|
|
818
|
+
const thumb = document.createElement("img");
|
|
819
|
+
thumb.src = `data:${img.mimeType};base64,${img.data}`;
|
|
820
|
+
thumb.alt = "";
|
|
821
|
+
const label = document.createElement("span");
|
|
822
|
+
label.textContent = `图片 ${index + 1}`;
|
|
823
|
+
const remove = document.createElement("button");
|
|
824
|
+
remove.type = "button";
|
|
825
|
+
remove.textContent = "✕";
|
|
826
|
+
remove.addEventListener("click", () => {
|
|
827
|
+
state.images.splice(index, 1);
|
|
828
|
+
renderAttachments();
|
|
829
|
+
});
|
|
830
|
+
chip.append(thumb, label, remove);
|
|
831
|
+
box.append(chip);
|
|
832
|
+
}
|
|
833
|
+
for (const [index, doc] of state.docs.entries()) {
|
|
834
|
+
const chip = document.createElement("span");
|
|
835
|
+
chip.className = "chip";
|
|
836
|
+
const label = document.createElement("span");
|
|
837
|
+
label.textContent = doc.name;
|
|
838
|
+
label.title = doc.path;
|
|
839
|
+
const remove = document.createElement("button");
|
|
840
|
+
remove.type = "button";
|
|
841
|
+
remove.textContent = "✕";
|
|
842
|
+
remove.addEventListener("click", () => {
|
|
843
|
+
state.docs.splice(index, 1);
|
|
844
|
+
renderAttachments();
|
|
845
|
+
});
|
|
846
|
+
chip.append(label, remove);
|
|
847
|
+
box.append(chip);
|
|
848
|
+
}
|
|
849
|
+
box.hidden = !(state.images.length || state.docs.length);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/** 浏览器端压图:长边 1568 / JPEG 0.82,和手机客户端一致。 */
|
|
853
|
+
async function compressImage(file) {
|
|
854
|
+
const bitmap = await createImageBitmap(file);
|
|
855
|
+
const scale = Math.min(1, IMAGE_MAX_EDGE / Math.max(bitmap.width, bitmap.height));
|
|
856
|
+
const canvas = document.createElement("canvas");
|
|
857
|
+
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
|
858
|
+
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
|
859
|
+
const ctx = canvas.getContext("2d");
|
|
860
|
+
ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
|
861
|
+
bitmap.close?.();
|
|
862
|
+
const dataUrl = canvas.toDataURL("image/jpeg", IMAGE_QUALITY);
|
|
863
|
+
return { type: "image", mimeType: "image/jpeg", data: dataUrl.slice(dataUrl.indexOf(",") + 1) };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
async function addImages(fileList) {
|
|
867
|
+
for (const file of fileList) {
|
|
868
|
+
if (state.images.length >= 4) {
|
|
869
|
+
toast("最多 4 张图片");
|
|
870
|
+
break;
|
|
871
|
+
}
|
|
872
|
+
try {
|
|
873
|
+
state.images.push(await compressImage(file));
|
|
874
|
+
} catch (err) {
|
|
875
|
+
toast(`图片处理失败:${err.message}`);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
renderAttachments();
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
async function addDoc(file) {
|
|
882
|
+
try {
|
|
883
|
+
const payload = await api(`/v1/upload?name=${encodeURIComponent(file.name)}`, {
|
|
884
|
+
method: "POST",
|
|
885
|
+
raw: true,
|
|
886
|
+
contentType: file.type || "application/octet-stream",
|
|
887
|
+
body: await file.arrayBuffer(),
|
|
888
|
+
});
|
|
889
|
+
state.docs.push({ name: payload.name ?? file.name, path: payload.path });
|
|
890
|
+
renderAttachments();
|
|
891
|
+
} catch (err) {
|
|
892
|
+
toast(`上传失败:${err.message}`);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
async function ensureSession() {
|
|
897
|
+
if (state.sessionId) return state.sessionId;
|
|
898
|
+
const cwd = store(STORE_KEYS.cwd) || "";
|
|
899
|
+
if (!cwd) {
|
|
900
|
+
openDrawer();
|
|
901
|
+
toast("先选一个工作区并新建会话");
|
|
902
|
+
throw new ApiError(400, "no_workspace", "先新建会话");
|
|
903
|
+
}
|
|
904
|
+
const data = await api("/v1/sessions", { method: "POST", body: { cwd } });
|
|
905
|
+
await openSession(data.session.id);
|
|
906
|
+
return data.session.id;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function send() {
|
|
910
|
+
const input = $("prompt");
|
|
911
|
+
const text = input.value.trim();
|
|
912
|
+
if (!text && !state.images.length && !state.docs.length) return;
|
|
913
|
+
let finalText = text;
|
|
914
|
+
for (const doc of state.docs) {
|
|
915
|
+
finalText += `${finalText ? "\n\n" : ""}[附件] ${doc.path}`;
|
|
916
|
+
}
|
|
917
|
+
const images = state.images.slice();
|
|
918
|
+
try {
|
|
919
|
+
const id = await ensureSession();
|
|
920
|
+
input.value = "";
|
|
921
|
+
autosize();
|
|
922
|
+
state.images = [];
|
|
923
|
+
state.docs = [];
|
|
924
|
+
renderAttachments();
|
|
925
|
+
state.pinned = true;
|
|
926
|
+
const body = { text: finalText };
|
|
927
|
+
if (images.length) body.images = images;
|
|
928
|
+
const data = await api(`/v1/sessions/${id}/prompt`, { method: "POST", body });
|
|
929
|
+
if (data?.disposition === "queued") toast("已排队(正在生成)");
|
|
930
|
+
setStreamingUi(true);
|
|
931
|
+
} catch (err) {
|
|
932
|
+
input.value = text;
|
|
933
|
+
toast(`发送失败:${err.message}`);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
async function stop() {
|
|
938
|
+
try {
|
|
939
|
+
await api(`/v1/sessions/${state.sessionId}/abort`, { method: "POST", body: {} });
|
|
940
|
+
} catch (err) {
|
|
941
|
+
toast(`停止失败:${err.message}`);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// ---------- 会话切换 ----------
|
|
946
|
+
|
|
947
|
+
function applySession(session) {
|
|
948
|
+
state.session = session;
|
|
949
|
+
const title = session?.name || session?.sessionId || state.sessionId || "pi hub";
|
|
950
|
+
$("session-title").textContent = title;
|
|
951
|
+
const parts = [];
|
|
952
|
+
if (session?.cwd) parts.push(session.cwd);
|
|
953
|
+
if (session?.model) parts.push(session.model);
|
|
954
|
+
if (session?.status) parts.push(session.status);
|
|
955
|
+
$("session-sub").textContent = parts.join(" · ");
|
|
956
|
+
if (session?.model) selectIfPresent($("model-select"), modelValueOf(session.model));
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
function modelValueOf(model) {
|
|
960
|
+
if (model && typeof model === "object") {
|
|
961
|
+
return model.provider ? `${model.provider}/${model.id}` : (model.id ?? "");
|
|
962
|
+
}
|
|
963
|
+
return String(model ?? "");
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function selectIfPresent(select, value) {
|
|
967
|
+
if (!value) return;
|
|
968
|
+
const option = [...select.options].find((o) => o.value === value);
|
|
969
|
+
if (option) select.value = value;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
async function openSession(id) {
|
|
973
|
+
state.sessionId = id;
|
|
974
|
+
state.items = [];
|
|
975
|
+
state.streaming = false;
|
|
976
|
+
state.stats = null;
|
|
977
|
+
state.usage = null;
|
|
978
|
+
renderUsage();
|
|
979
|
+
setStreamingUi(false);
|
|
980
|
+
$("session-title").textContent = id.slice(0, 8);
|
|
981
|
+
$("session-sub").textContent = "";
|
|
982
|
+
renderMessages();
|
|
983
|
+
closeDrawer();
|
|
984
|
+
store(STORE_KEYS.session, id);
|
|
985
|
+
renderDrawer();
|
|
986
|
+
|
|
987
|
+
try {
|
|
988
|
+
const hist = await api(`/v1/sessions/${id}/history`);
|
|
989
|
+
state.items = historyToItems(hist?.messages ?? []);
|
|
990
|
+
renderMessages();
|
|
991
|
+
} catch (err) {
|
|
992
|
+
toast(`历史加载失败:${err.message}`);
|
|
993
|
+
}
|
|
994
|
+
connectStream();
|
|
995
|
+
refreshStats();
|
|
996
|
+
loadThinking(id).catch(() => {});
|
|
997
|
+
loadSessions().catch(() => {});
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
async function loadThinking(id) {
|
|
1001
|
+
const info = await api(`/v1/sessions/${id}/state`).catch(() => null);
|
|
1002
|
+
const live = info?.live === true;
|
|
1003
|
+
const data = live ? await api(`/v1/sessions/${id}/thinking`) : await api("/v1/thinking");
|
|
1004
|
+
state.levels = data?.levels ?? [];
|
|
1005
|
+
state.level = data?.level ?? null;
|
|
1006
|
+
const select = $("thinking-select");
|
|
1007
|
+
select.textContent = "";
|
|
1008
|
+
for (const level of state.levels) {
|
|
1009
|
+
const option = document.createElement("option");
|
|
1010
|
+
option.value = level;
|
|
1011
|
+
option.textContent = level;
|
|
1012
|
+
select.append(option);
|
|
1013
|
+
}
|
|
1014
|
+
if (state.level) select.value = state.level;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
async function loadModels() {
|
|
1018
|
+
try {
|
|
1019
|
+
const data = await api("/v1/models");
|
|
1020
|
+
state.models = data?.models ?? [];
|
|
1021
|
+
} catch {
|
|
1022
|
+
state.models = [];
|
|
1023
|
+
}
|
|
1024
|
+
for (const id of ["model-select", "new-model"]) {
|
|
1025
|
+
const select = $(id);
|
|
1026
|
+
select.textContent = "";
|
|
1027
|
+
select.append(new Option(id === "new-model" ? "默认" : "模型…", ""));
|
|
1028
|
+
for (const model of state.models) {
|
|
1029
|
+
const value = `${model.provider}/${model.id}`;
|
|
1030
|
+
select.append(new Option(model.name || model.id, value));
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
async function loadCsrf() {
|
|
1036
|
+
try {
|
|
1037
|
+
const data = await api("/v1/web/csrf");
|
|
1038
|
+
state.csrf = data?.csrf ?? null;
|
|
1039
|
+
} catch {
|
|
1040
|
+
state.csrf = null;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// ---------- 界面切换 ----------
|
|
1045
|
+
|
|
1046
|
+
function toast(message) {
|
|
1047
|
+
const box = $("toast");
|
|
1048
|
+
box.textContent = message;
|
|
1049
|
+
box.hidden = false;
|
|
1050
|
+
clearTimeout(toast.timer);
|
|
1051
|
+
toast.timer = setTimeout(() => {
|
|
1052
|
+
box.hidden = true;
|
|
1053
|
+
}, 3200);
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
function openDrawer() {
|
|
1057
|
+
$("drawer").hidden = false;
|
|
1058
|
+
$("scrim").hidden = false;
|
|
1059
|
+
loadSessions().catch(() => {});
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
function closeDrawer() {
|
|
1063
|
+
$("drawer").hidden = true;
|
|
1064
|
+
$("scrim").hidden = true;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
function showLogin(message) {
|
|
1068
|
+
$("app").hidden = true;
|
|
1069
|
+
$("login").hidden = false;
|
|
1070
|
+
if (message) {
|
|
1071
|
+
$("login-error").textContent = message;
|
|
1072
|
+
$("login-error").hidden = false;
|
|
1073
|
+
}
|
|
1074
|
+
$("login-token").focus();
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
function showApp() {
|
|
1078
|
+
$("login").hidden = true;
|
|
1079
|
+
$("app").hidden = false;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
async function start() {
|
|
1083
|
+
showApp();
|
|
1084
|
+
await loadCsrf();
|
|
1085
|
+
await loadModels();
|
|
1086
|
+
await loadSessions();
|
|
1087
|
+
const remembered = store(STORE_KEYS.session);
|
|
1088
|
+
if (remembered && state.sessions.some((s) => s.id === remembered)) {
|
|
1089
|
+
await openSession(remembered);
|
|
1090
|
+
} else {
|
|
1091
|
+
renderMessages();
|
|
1092
|
+
openDrawer();
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/** 一次性码形如 XXXX-XXXX(Crockford base32),也接受不带连字符。 */
|
|
1097
|
+
function isOneTimeCode(value) {
|
|
1098
|
+
return /^[0-9A-HJKMNP-TV-Z]{4}-?[0-9A-HJKMNP-TV-Z]{4}$/i.test(value.replace(/\s+/g, ""));
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
async function redeemCode(code) {
|
|
1102
|
+
const body = { code: code.replace(/\s+/g, "") };
|
|
1103
|
+
const totp = $("login-totp")?.value.trim();
|
|
1104
|
+
if (totp) body.totp = totp;
|
|
1105
|
+
await api("/v1/web/otp/redeem", { method: "POST", body });
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
async function login(event) {
|
|
1109
|
+
event.preventDefault();
|
|
1110
|
+
const token = $("login-token").value.trim();
|
|
1111
|
+
if (!token) return;
|
|
1112
|
+
const button = $("login-submit");
|
|
1113
|
+
button.disabled = true;
|
|
1114
|
+
try {
|
|
1115
|
+
if (isOneTimeCode(token)) {
|
|
1116
|
+
await redeemCode(token);
|
|
1117
|
+
} else {
|
|
1118
|
+
const body = { token };
|
|
1119
|
+
const totp = $("login-totp")?.value.trim();
|
|
1120
|
+
if (totp) body.totp = totp;
|
|
1121
|
+
await api("/v1/web/login", { method: "POST", body });
|
|
1122
|
+
}
|
|
1123
|
+
$("login-token").value = "";
|
|
1124
|
+
$("login-totp") && ($("login-totp").value = "");
|
|
1125
|
+
$("login-totp-wrap") && ($("login-totp-wrap").hidden = true);
|
|
1126
|
+
$("login-error").hidden = true;
|
|
1127
|
+
await start();
|
|
1128
|
+
} catch (err) {
|
|
1129
|
+
if (err.status === 429) showLogin("尝试太频繁,等一分钟再试");
|
|
1130
|
+
else if (err.code === "bad_totp") {
|
|
1131
|
+
$("login-totp-wrap").hidden = false;
|
|
1132
|
+
$("login-totp").focus();
|
|
1133
|
+
showLogin("需要验证器 6 位码(TOTP)");
|
|
1134
|
+
return;
|
|
1135
|
+
} else if (err.status === 410) showLogin("一次性码已过期或已用过,请在主机上重新生成");
|
|
1136
|
+
else if (err.status === 401) showLogin("令牌错误");
|
|
1137
|
+
else showLogin(`登录失败:${err.message}`);
|
|
1138
|
+
} finally {
|
|
1139
|
+
button.disabled = false;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
async function logout() {
|
|
1144
|
+
try {
|
|
1145
|
+
await api("/v1/web/logout", { method: "POST", body: {} });
|
|
1146
|
+
} catch {
|
|
1147
|
+
// 即使 csrf 过期也要清本地状态
|
|
1148
|
+
}
|
|
1149
|
+
state.stream?.close();
|
|
1150
|
+
state.stream = null;
|
|
1151
|
+
state.sessionId = null;
|
|
1152
|
+
state.csrf = null;
|
|
1153
|
+
store(STORE_KEYS.session, "");
|
|
1154
|
+
showLogin();
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
async function checkUpdate() {
|
|
1158
|
+
try {
|
|
1159
|
+
const data = await api("/v1/update");
|
|
1160
|
+
if (data?.error) {
|
|
1161
|
+
toast(`检查失败:${data.error}`);
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
const parts = [`服务端 ${data.server.current} → ${data.server.latest ?? "?"}`];
|
|
1165
|
+
if (data.android?.current) parts.push(`安卓 ${data.android.current} → ${data.android.latest ?? "?"}`);
|
|
1166
|
+
toast(parts.join(" · "));
|
|
1167
|
+
} catch (err) {
|
|
1168
|
+
toast(`检查失败:${err.message}`);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// ---------- 事件绑定 ----------
|
|
1173
|
+
|
|
1174
|
+
function wire() {
|
|
1175
|
+
$("login-form").addEventListener("submit", login);
|
|
1176
|
+
$("btn-drawer").addEventListener("click", openDrawer);
|
|
1177
|
+
$("btn-drawer-close").addEventListener("click", closeDrawer);
|
|
1178
|
+
$("scrim").addEventListener("click", closeDrawer);
|
|
1179
|
+
$("session-search").addEventListener("input", (event) => {
|
|
1180
|
+
state.search = event.target.value;
|
|
1181
|
+
renderDrawer();
|
|
1182
|
+
});
|
|
1183
|
+
$("new-session").addEventListener("submit", async (event) => {
|
|
1184
|
+
event.preventDefault();
|
|
1185
|
+
const cwd = $("new-cwd").value.trim();
|
|
1186
|
+
const model = $("new-model").value;
|
|
1187
|
+
const error = $("new-error");
|
|
1188
|
+
error.hidden = true;
|
|
1189
|
+
try {
|
|
1190
|
+
const check = await api(`/v1/workspace?path=${encodeURIComponent(cwd)}`);
|
|
1191
|
+
if (!check.exists || !check.isDir) throw new Error(`${cwd} 不是目录`);
|
|
1192
|
+
const body = { cwd: check.path };
|
|
1193
|
+
if (model) body.model = model;
|
|
1194
|
+
const data = await api("/v1/sessions", { method: "POST", body });
|
|
1195
|
+
store(STORE_KEYS.cwd, check.path);
|
|
1196
|
+
await openSession(data.session.id);
|
|
1197
|
+
} catch (err) {
|
|
1198
|
+
error.textContent = `新建失败:${err.message}`;
|
|
1199
|
+
error.hidden = false;
|
|
1200
|
+
}
|
|
1201
|
+
});
|
|
1202
|
+
$("prompt").addEventListener("input", autosize);
|
|
1203
|
+
$("prompt").addEventListener("keydown", (event) => {
|
|
1204
|
+
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
|
|
1205
|
+
event.preventDefault();
|
|
1206
|
+
send();
|
|
1207
|
+
}
|
|
1208
|
+
});
|
|
1209
|
+
$("btn-send").addEventListener("click", send);
|
|
1210
|
+
$("btn-stop").addEventListener("click", stop);
|
|
1211
|
+
$("image-input").addEventListener("change", async (event) => {
|
|
1212
|
+
await addImages([...event.target.files]);
|
|
1213
|
+
event.target.value = "";
|
|
1214
|
+
});
|
|
1215
|
+
$("doc-input").addEventListener("change", async (event) => {
|
|
1216
|
+
for (const file of event.target.files) await addDoc(file);
|
|
1217
|
+
event.target.value = "";
|
|
1218
|
+
});
|
|
1219
|
+
$("model-select").addEventListener("change", async (event) => {
|
|
1220
|
+
const [provider, ...rest] = event.target.value.split("/");
|
|
1221
|
+
const modelId = rest.join("/");
|
|
1222
|
+
if (!provider || !modelId || !state.sessionId) return;
|
|
1223
|
+
try {
|
|
1224
|
+
await api(`/v1/sessions/${state.sessionId}/model`, { method: "POST", body: { provider, modelId } });
|
|
1225
|
+
$("session-sub").textContent = [state.session?.cwd, `${provider}/${modelId}`].filter(Boolean).join(" · ");
|
|
1226
|
+
} catch (err) {
|
|
1227
|
+
toast(`切换模型失败:${err.message}`);
|
|
1228
|
+
}
|
|
1229
|
+
});
|
|
1230
|
+
$("thinking-select").addEventListener("change", async (event) => {
|
|
1231
|
+
if (!state.sessionId) return;
|
|
1232
|
+
try {
|
|
1233
|
+
await api(`/v1/sessions/${state.sessionId}/thinking`, { method: "POST", body: { level: event.target.value } });
|
|
1234
|
+
} catch (err) {
|
|
1235
|
+
toast(`切换强度失败:${err.message}`);
|
|
1236
|
+
}
|
|
1237
|
+
});
|
|
1238
|
+
$("messages").addEventListener("scroll", () => {
|
|
1239
|
+
const box = $("messages");
|
|
1240
|
+
const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 60;
|
|
1241
|
+
state.pinned = atBottom;
|
|
1242
|
+
$("btn-jump").hidden = atBottom;
|
|
1243
|
+
});
|
|
1244
|
+
$("btn-jump").addEventListener("click", scrollToBottom);
|
|
1245
|
+
$("messages").addEventListener("click", async (event) => {
|
|
1246
|
+
const copy = event.target.closest("[data-copy]");
|
|
1247
|
+
if (!copy) return;
|
|
1248
|
+
const code = copy.closest(".code-card")?.querySelector("code");
|
|
1249
|
+
if (!code) return;
|
|
1250
|
+
try {
|
|
1251
|
+
await navigator.clipboard.writeText(code.textContent ?? "");
|
|
1252
|
+
copy.textContent = "已复制";
|
|
1253
|
+
setTimeout(() => {
|
|
1254
|
+
copy.textContent = "复制";
|
|
1255
|
+
}, 1500);
|
|
1256
|
+
} catch {
|
|
1257
|
+
toast("复制失败(浏览器不允许)");
|
|
1258
|
+
}
|
|
1259
|
+
});
|
|
1260
|
+
// toggle 不冒泡,但捕获阶段仍会经过祖先:记下用户手动开关过思考块
|
|
1261
|
+
$("messages").addEventListener(
|
|
1262
|
+
"toggle",
|
|
1263
|
+
(event) => {
|
|
1264
|
+
const block = event.target;
|
|
1265
|
+
if (block?.classList?.contains("thinking-block")) block.dataset.touched = "1";
|
|
1266
|
+
},
|
|
1267
|
+
true,
|
|
1268
|
+
);
|
|
1269
|
+
$("btn-menu").addEventListener("click", () => {
|
|
1270
|
+
$("menu").hidden = !$("menu").hidden;
|
|
1271
|
+
});
|
|
1272
|
+
$("btn-rename").addEventListener("click", async () => {
|
|
1273
|
+
$("menu").hidden = true;
|
|
1274
|
+
if (!state.sessionId) return;
|
|
1275
|
+
const name = window.prompt("会话名称", state.session?.name ?? "");
|
|
1276
|
+
if (!name) return;
|
|
1277
|
+
try {
|
|
1278
|
+
await api(`/v1/sessions/${state.sessionId}/name`, { method: "POST", body: { name } });
|
|
1279
|
+
$("session-title").textContent = name;
|
|
1280
|
+
} catch (err) {
|
|
1281
|
+
toast(`重命名失败:${err.message}`);
|
|
1282
|
+
}
|
|
1283
|
+
});
|
|
1284
|
+
$("btn-compact").addEventListener("click", async () => {
|
|
1285
|
+
$("menu").hidden = true;
|
|
1286
|
+
if (!state.sessionId) return;
|
|
1287
|
+
try {
|
|
1288
|
+
await api(`/v1/sessions/${state.sessionId}/compact`, { method: "POST", body: {} });
|
|
1289
|
+
toast("已请求压缩");
|
|
1290
|
+
} catch (err) {
|
|
1291
|
+
toast(`压缩失败:${err.message}`);
|
|
1292
|
+
}
|
|
1293
|
+
});
|
|
1294
|
+
$("btn-update").addEventListener("click", async () => {
|
|
1295
|
+
$("menu").hidden = true;
|
|
1296
|
+
await checkUpdate();
|
|
1297
|
+
});
|
|
1298
|
+
$("btn-logout").addEventListener("click", async () => {
|
|
1299
|
+
$("menu").hidden = true;
|
|
1300
|
+
await logout();
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
// ---------- 启动 ----------
|
|
1305
|
+
|
|
1306
|
+
async function boot() {
|
|
1307
|
+
wire();
|
|
1308
|
+
autosize();
|
|
1309
|
+
if ("serviceWorker" in navigator) {
|
|
1310
|
+
navigator.serviceWorker.register("/sw.js").catch(() => {});
|
|
1311
|
+
}
|
|
1312
|
+
let session = null;
|
|
1313
|
+
try {
|
|
1314
|
+
session = await fetch("/v1/web/session", { credentials: "same-origin" }).then((r) => r.json());
|
|
1315
|
+
} catch {
|
|
1316
|
+
session = null;
|
|
1317
|
+
}
|
|
1318
|
+
if (session?.ok) {
|
|
1319
|
+
await start();
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
// `pi-hub web-login` 打印的链接带 #code=XXXX-XXXX:直接兑换成 cookie,不要求手输。
|
|
1323
|
+
const hash = new URLSearchParams(location.hash.replace(/^#/, ""));
|
|
1324
|
+
const code = hash.get("code");
|
|
1325
|
+
if (code) {
|
|
1326
|
+
history.replaceState(null, "", location.pathname + location.search);
|
|
1327
|
+
try {
|
|
1328
|
+
await redeemCode(code);
|
|
1329
|
+
await start();
|
|
1330
|
+
return;
|
|
1331
|
+
} catch (err) {
|
|
1332
|
+
showLogin(err.status === 410 ? "一次性码已过期或已用过,请在主机上重新生成" : `一次性码登录失败:${err.message}`);
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
showLogin();
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
boot();
|