pi-hub-server 0.4.2 → 0.9.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/web/app.js CHANGED
@@ -2,16 +2,53 @@
2
2
  // 鉴权:cookie 会话(GET 免 CSRF,非 GET 带 x-pi-csrf)。上传与流式都走同源 /v1。
3
3
  "use strict";
4
4
 
5
+ import { renderMarkdown } from "./markdown.js";
6
+ import { draftKeyOf, draftStorageKey, isPinned } from "./compose.js";
7
+ import {
8
+ formatDuration,
9
+ formatTokens,
10
+ groupCollapsedText,
11
+ guessHome,
12
+ historyToItems,
13
+ matchModelValue,
14
+ menuPlacement,
15
+ modelValueCandidates,
16
+ parseCollapsedGroups,
17
+ pickSessionModel,
18
+ sessionTitle,
19
+ thinkingLevelLabel,
20
+ toggleCollapsedGroup,
21
+ toolInputText,
22
+ toolStateText,
23
+ usageLines,
24
+ workspaceHeader,
25
+ } from "./model.js";
26
+
5
27
  const $ = (id) => document.getElementById(id);
6
28
 
7
29
  /**
8
30
  * 桌面断点:必须与 style.css 里 `.drawer` 常驻侧栏的 `@media (min-width: 900px)` 一致。
9
- * 宽屏时抽屉是布局的一部分(CSS 强制显示),所以 Esc 不该把它关掉。
31
+ * 宽屏时抽屉是布局的一部分(CSS 里没有折叠态时强制显示),Esc 不把它关掉;
32
+ * 折叠/展开只由顶栏 ☰ 与侧栏内按钮切换(折叠态记在 localStorage)。
10
33
  */
11
34
  const WIDE_QUERY = "(min-width: 900px)";
12
35
  const isWideScreen = () => window.matchMedia(WIDE_QUERY).matches;
13
36
 
14
- const STORE_KEYS = { session: "pihub.session", cwd: "pihub.cwd", commands: "pihub.commands" };
37
+ /**
38
+ * 桌面折叠态=图标栏宽度(对齐 DSH 的 `SIDEBAR_COLLAPSED=56`)。
39
+ * 必须与 style.css 里的 `--sidebar-rail` 一致;主区靠 `left: var(--sidebar)` 自动跟着重排。
40
+ */
41
+ const SIDEBAR_RAIL = 56;
42
+
43
+ const STORE_KEYS = {
44
+ session: "pihub.session",
45
+ cwd: "pihub.cwd",
46
+ commands: "pihub.commands",
47
+ /** 桌面侧栏是否收起:"1" 收起,其他/缺省展开(窄屏不看这个键,抽屉语义不变)。 */
48
+ sidebarCollapsed: "pihub.sidebarCollapsed",
49
+ /** 抽屉里已折叠的工作区分组(JSON 数组,按 cwd 记)。 */
50
+ collapsedGroups: "pihub.collapsedGroups",
51
+ };
15
52
  /** sessionStorage:上次是否已登录(只为决定首帧画哪屏)。 */
16
53
  const AUTHED_KEY = "pihub.authed";
17
54
  const COMMAND_TTL_MS = 5 * 60 * 1000;
@@ -35,6 +72,14 @@ const state = {
35
72
  usage: null,
36
73
  search: "",
37
74
  pinned: true,
75
+ /** 上一次 scroll 事件的 scrollTop:用来区分「用户主动上滑」和「内容变长」。 */
76
+ lastScrollTop: 0,
77
+ /** 输入框当前对应的草稿键(会话 id / `n:<cwd>`):切会话时换副本,发送成功后清掉。 */
78
+ draftKey: "",
79
+ /** 桌面侧栏折叠态(跨刷新保持);窄屏忽略。 */
80
+ sidebarCollapsed: false,
81
+ /** 抽屉里已折叠的工作区 cwd 列表(跨刷新保持)。 */
82
+ collapsedGroups: [],
38
83
  // SSE 游标:已应用的最大 seq。首连(since=0)时回放都是历史,discard 到 `live` 边界为止。
39
84
  lastSeq: 0,
40
85
  awaitLive: true,
@@ -53,6 +98,50 @@ function store(key, value) {
53
98
  return null;
54
99
  }
55
100
 
101
+ function unstore(key) {
102
+ try {
103
+ localStorage.removeItem(key);
104
+ } catch {
105
+ // 同上:删不掉就当没存过
106
+ }
107
+ }
108
+
109
+ // ---------- 输入框草稿(F7:按会话/窗口隔离) ----------
110
+ // 键由 compose.draftKeyOf 决定:会话=会话 id,还没建会话的新窗口=`n:<cwd>`。
111
+ // 隐私模式(localStorage 抛异常)下 store/unstore 静默失败 ⇒ 退化成「刷新即丢」,不是错误。
112
+
113
+ function saveDraft(key, text) {
114
+ if (!key) return;
115
+ if (text) store(draftStorageKey(key), text);
116
+ else unstore(draftStorageKey(key));
117
+ }
118
+
119
+ function loadDraft(key) {
120
+ return (key && store(draftStorageKey(key))) || "";
121
+ }
122
+
123
+ /**
124
+ * 换草稿副本:先把当前键的输入落盘,再从 localStorage 载入新键。
125
+ * 切会话 / 开新会话窗口都走这里,所以旧会话的字不会串到新会话里。
126
+ */
127
+ function switchDraft(nextKey) {
128
+ const input = $("prompt");
129
+ const previous = state.draftKey;
130
+ const text = input.value;
131
+ if (previous && previous !== nextKey) saveDraft(previous, text);
132
+ state.draftKey = nextKey;
133
+ let next = loadDraft(nextKey);
134
+ // 同一份新会话缓冲的“搬家”:还没选工作区(`n:`)时先打的字,选好 cwd 后要跟着进 `n:<cwd>`,
135
+ // 否则用户「先打字、再点仓库组的 +」时会整段字看着没了。会话 ↔ 窗口之间从不搬。
136
+ if (!next && text && previous === draftKeyOf(null, "") && nextKey.startsWith("n:")) {
137
+ next = text;
138
+ saveDraft(nextKey, text);
139
+ }
140
+ if (input.value !== next) input.value = next;
141
+ hideSlash();
142
+ autosize();
143
+ }
144
+
56
145
  class ApiError extends Error {
57
146
  constructor(status, code, message) {
58
147
  super(message || `HTTP ${status}`);
@@ -103,157 +192,7 @@ async function api(path, options = {}) {
103
192
  }
104
193
  }
105
194
 
106
- // ---------- markdown(自研轻渲染:先转义再拼标签,代码块整体转义) ----------
107
-
108
- const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
109
-
110
- function escapeHtml(value) {
111
- return String(value ?? "").replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
112
- }
113
-
114
- function safeHref(href) {
115
- const raw = href.replace(/&amp;/g, "&");
116
- if (/^https?:\/\//i.test(raw) || /^mailto:/i.test(raw) || raw.startsWith("/")) return true;
117
- return false;
118
- }
119
-
120
- /** 输入必须是已转义文本,输出只含我们自己生成的标签。 */
121
- function inlineMarkdown(escaped) {
122
- let out = escaped;
123
- out = out.replace(/`([^`\n]+)`/g, "<code>$1</code>");
124
- out = out.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>");
125
- out = out.replace(/(^|[\s(])\*([^*\s][^*\n]*)\*/g, "$1<em>$2</em>");
126
- out = out.replace(/~~([^~\n]+)~~/g, "<del>$1</del>");
127
- out = out.replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, (match, label, href) =>
128
- safeHref(href) ? `<a href="${href}" target="_blank" rel="noopener noreferrer">${label}</a>` : label,
129
- );
130
- return out;
131
- }
132
-
133
- function isTableSeparator(line) {
134
- return /^\s*\|?[\s:-]*-[\s|:-]*$/.test(line) && line.includes("-");
135
- }
136
-
137
- function renderMarkdown(source) {
138
- const lines = String(source ?? "").replace(/\r\n?/g, "\n").split("\n");
139
- const out = [];
140
- let para = [];
141
- const flush = () => {
142
- if (para.length) {
143
- out.push(`<p>${para.map((l) => inlineMarkdown(escapeHtml(l))).join("<br>")}</p>`);
144
- para = [];
145
- }
146
- };
147
-
148
- let i = 0;
149
- while (i < lines.length) {
150
- const line = lines[i];
151
-
152
- // 代码块:内容整体转义,语言标记只用于角标
153
- const fence = /^\s{0,3}(`{3,}|~{3,})\s*([\w+-]*)\s*$/.exec(line);
154
- if (fence) {
155
- flush();
156
- const marker = fence[1][0];
157
- const lang = fence[2] || "";
158
- const body = [];
159
- i += 1;
160
- while (i < lines.length) {
161
- const closing = new RegExp(`^\\s{0,3}${marker}{${fence[1].length},}\\s*$`);
162
- if (closing.test(lines[i])) {
163
- i += 1;
164
- break;
165
- }
166
- body.push(lines[i]);
167
- i += 1;
168
- }
169
- out.push(
170
- `<div class="code-card"><div class="code-head"><span>${escapeHtml(lang || "code")}</span>` +
171
- `<button type="button" class="copy" data-copy>复制</button></div>` +
172
- `<pre><code>${escapeHtml(body.join("\n"))}</code></pre></div>`,
173
- );
174
- continue;
175
- }
176
-
177
- if (/^\s*$/.test(line)) {
178
- flush();
179
- i += 1;
180
- continue;
181
- }
182
-
183
- const heading = /^\s{0,3}(#{1,6})\s+(.*)$/.exec(line);
184
- if (heading) {
185
- flush();
186
- const level = Math.min(heading[1].length, 4);
187
- out.push(`<h${level}>${inlineMarkdown(escapeHtml(heading[2]))}</h${level}>`);
188
- i += 1;
189
- continue;
190
- }
191
-
192
- if (/^\s{0,3}([-*_])(\s*\1){2,}\s*$/.test(line)) {
193
- flush();
194
- out.push("<hr />");
195
- i += 1;
196
- continue;
197
- }
198
-
199
- const quote = /^\s{0,3}>\s?(.*)$/.exec(line);
200
- if (quote) {
201
- flush();
202
- const body = [];
203
- while (i < lines.length) {
204
- const q = /^\s{0,3}>\s?(.*)$/.exec(lines[i]);
205
- if (!q) break;
206
- body.push(q[1]);
207
- i += 1;
208
- }
209
- out.push(`<blockquote>${inlineMarkdown(escapeHtml(body.join("\n")))}</blockquote>`);
210
- continue;
211
- }
212
-
213
- const bullet = /^\s{0,3}([-*+])\s+(.*)$/.exec(line);
214
- const numbered = /^\s{0,3}(\d{1,9})[.)]\s+(.*)$/.exec(line);
215
- if (bullet || numbered) {
216
- flush();
217
- const ordered = Boolean(numbered);
218
- const items = [];
219
- while (i < lines.length) {
220
- const b = ordered ? /^\s{0,3}(\d{1,9})[.)]\s+(.*)$/.exec(lines[i]) : /^\s{0,3}([-*+])\s+(.*)$/.exec(lines[i]);
221
- if (!b) break;
222
- items.push(`<li>${inlineMarkdown(escapeHtml(b[2]))}</li>`);
223
- i += 1;
224
- }
225
- out.push(ordered ? `<ol>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`);
226
- continue;
227
- }
228
-
229
- // 表格:表头 + 分隔行才认,否则按普通段落
230
- if (line.includes("|") && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
231
- flush();
232
- const cells = (row) =>
233
- row
234
- .replace(/^\s*\|/, "")
235
- .replace(/\|\s*$/, "")
236
- .split("|")
237
- .map((c) => inlineMarkdown(escapeHtml(c.trim())));
238
- const head = cells(line);
239
- i += 2;
240
- const rows = [];
241
- while (i < lines.length && lines[i].includes("|") && !/^\s*$/.test(lines[i])) {
242
- rows.push(`<tr>${cells(lines[i]).map((c) => `<td>${c}</td>`).join("")}</tr>`);
243
- i += 1;
244
- }
245
- out.push(
246
- `<table><thead><tr>${head.map((c) => `<th>${c}</th>`).join("")}</tr></thead><tbody>${rows.join("")}</tbody></table>`,
247
- );
248
- continue;
249
- }
250
-
251
- para.push(line);
252
- i += 1;
253
- }
254
- flush();
255
- return out.join("");
256
- }
195
+ // ---------- markdown(渲染器在 web/markdown.js,node 可直接单测) ----------
257
196
 
258
197
  // ---------- 会话列表 ----------
259
198
 
@@ -303,12 +242,77 @@ function renderDrawer() {
303
242
  list.append(empty);
304
243
  }
305
244
 
245
+ let groupIndex = 0;
246
+ // home 从 cwd 里认(对齐安卓 guessHome):网页拿不到服务端 home,认不出来就按原路径画
247
+ const home = guessHome(state.sessions.map((s) => s.cwd));
306
248
  for (const group of groupSessions(filtered)) {
307
- const title = document.createElement("div");
308
- title.className = "group-title";
309
- title.textContent = group.cwd;
310
- title.title = group.cwd;
311
- list.append(title);
249
+ // 分组头可折叠(R8-F3):状态按 cwd 存 localStorage,刷新后保持;「未分类」组同权
250
+ // (它的 cwd 就是 groupSessions 里那句「(未知工作区)」占位 key)。
251
+ const rowsId = `group-rows-${(groupIndex += 1)}`;
252
+ const { name: groupName, path: groupPath } = workspaceHeader(group.cwd, home);
253
+ const head = document.createElement("div");
254
+ head.className = "group-title";
255
+ const toggle = document.createElement("button");
256
+ toggle.type = "button";
257
+ toggle.className = "group-toggle";
258
+ toggle.dataset.cwd = group.cwd;
259
+ toggle.setAttribute("aria-controls", rowsId);
260
+ const cwd = document.createElement("span");
261
+ cwd.className = "cwd";
262
+ // 组头文案 = 名称 + `~` 缩写路径(对齐安卓 WorkspaceHeader);以前是整条绝对路径大写
263
+ cwd.textContent = groupName;
264
+ cwd.title = group.cwd;
265
+ const path = document.createElement("span");
266
+ path.className = "cwd-path";
267
+ path.textContent = groupPath;
268
+ path.title = group.cwd;
269
+ const count = document.createElement("span");
270
+ count.className = "count";
271
+ count.textContent = groupCollapsedText(group.rows.length);
272
+ toggle.append(cwd, path, count);
273
+ // 同一仓库直接开新会话:不用滚到抽屉底部那个表单
274
+ const add = document.createElement("button");
275
+ add.type = "button";
276
+ add.className = "group-new";
277
+ add.textContent = "+";
278
+ add.title = `在 ${group.cwd} 新建会话`;
279
+ add.setAttribute("aria-label", `在 ${group.cwd} 新建会话`);
280
+ add.addEventListener("click", (event) => {
281
+ event.stopPropagation();
282
+ openNewSession(group.cwd);
283
+ });
284
+ // 工作区组头 ⋮(对齐安卓工作区长按菜单):复用 openMenuAt(anchor) 定点定位
285
+ const more = document.createElement("button");
286
+ more.type = "button";
287
+ more.className = "group-more";
288
+ more.textContent = "⋮";
289
+ more.dataset.cwd = group.cwd;
290
+ more.dataset.count = String(group.rows.length);
291
+ more.title = `${groupName} 更多操作`;
292
+ more.setAttribute("aria-label", `${groupName} 更多操作`);
293
+ more.addEventListener("click", (event) => {
294
+ event.stopPropagation();
295
+ toggleGroupMenu(more);
296
+ });
297
+ head.append(toggle, add, more);
298
+ list.append(head);
299
+
300
+ const rows = document.createElement("div");
301
+ rows.className = "session-group";
302
+ rows.id = rowsId;
303
+ const applyCollapsed = (collapsed) => {
304
+ toggle.setAttribute("aria-expanded", collapsed ? "false" : "true");
305
+ toggle.title = collapsed ? `展开 ${group.cwd}(${groupCollapsedText(group.rows.length)})` : `折叠 ${group.cwd}`;
306
+ rows.hidden = collapsed;
307
+ };
308
+ applyCollapsed(state.collapsedGroups.includes(group.cwd));
309
+ toggle.addEventListener("click", () => {
310
+ state.collapsedGroups = toggleCollapsedGroup(state.collapsedGroups, group.cwd);
311
+ store(STORE_KEYS.collapsedGroups, JSON.stringify(state.collapsedGroups));
312
+ applyCollapsed(state.collapsedGroups.includes(group.cwd));
313
+ });
314
+ list.append(rows);
315
+
312
316
  for (const row of group.rows) {
313
317
  const item = document.createElement("div");
314
318
  item.className = "session-item" + (row.id === state.sessionId ? " active" : "");
@@ -323,7 +327,7 @@ function renderDrawer() {
323
327
  line.append(badge, document.createTextNode(` ${row.preview || ""}`));
324
328
  item.append(name, line);
325
329
  item.addEventListener("click", () => openSession(row.id));
326
- list.append(item);
330
+ rows.append(item);
327
331
  }
328
332
  }
329
333
 
@@ -366,6 +370,17 @@ function ensureAssistant() {
366
370
  return item;
367
371
  }
368
372
 
373
+ /**
374
+ * 程序化改 `details.open` 也会派发 toggle 事件(且是异步的)——不隔离的话
375
+ * 「流式中自动展开」会被当成用户手动展开,之后永远收不起来。
376
+ * 用 dataset.auto 标记一次,由 messages 上的 toggle 捕获监听器消掉。
377
+ */
378
+ function setDetailsOpen(el, open) {
379
+ if (el.open === open) return;
380
+ el.dataset.auto = "1";
381
+ el.open = open;
382
+ }
383
+
369
384
  function createToolCard(item, tool) {
370
385
  const card = document.createElement("details");
371
386
  card.className = "tool-card";
@@ -377,8 +392,6 @@ function createToolCard(item, tool) {
377
392
  summary.append(name, status);
378
393
  const body = document.createElement("div");
379
394
  body.className = "tool-body";
380
- const pre = document.createElement("pre");
381
- body.append(pre);
382
395
  card.append(summary, body);
383
396
  const existing = item.refs.toolEls.get(tool.id);
384
397
  if (existing) existing.remove();
@@ -387,23 +400,46 @@ function createToolCard(item, tool) {
387
400
  return card;
388
401
  }
389
402
 
390
- function toolStateText(tool) {
391
- if (tool.isError) return "失败";
392
- if (tool.state === "done") return tool.durationMs ? `完成 · ${Math.round(tool.durationMs)}ms` : "完成";
393
- if (tool.state === "running") return "运行中…";
394
- return "排队中";
403
+ /** 卡片正文分「参数 / 输出」两段;空段不画。 */
404
+ function toolSections(tool) {
405
+ const sections = [];
406
+ const input = toolInputText(tool);
407
+ if (input) sections.push({ title: "参数", text: input, isError: false });
408
+ if (tool.preview) sections.push({ title: tool.isError ? "错误输出" : "输出", text: tool.preview, isError: Boolean(tool.isError) });
409
+ return sections;
395
410
  }
396
411
 
397
- function toolBodyText(tool) {
398
- if (tool.preview) return tool.preview;
399
- if (tool.args !== undefined) {
400
- try {
401
- return JSON.stringify(tool.args, null, 2);
402
- } catch {
403
- return String(tool.args);
404
- }
412
+ function renderToolBody(body, tool) {
413
+ const sections = toolSections(tool);
414
+ // 只在内容真变了才重建:流式 tool_progress 每帧都来,重建会丢滚动位置
415
+ const signature = `${tool.isError ? "E" : "O"}|${sections.map((s) => `${s.title}\u0000${s.text}`).join("\u0001")}`;
416
+ if (body.dataset.sig === signature) return;
417
+ body.dataset.sig = signature;
418
+ body.textContent = "";
419
+ if (!sections.length) {
420
+ const empty = document.createElement("div");
421
+ empty.className = "tool-empty";
422
+ empty.textContent = tool.state === "done" ? "(这次调用没有文本输出)" : "等待输出…";
423
+ body.append(empty);
424
+ return;
425
+ }
426
+ for (const section of sections) {
427
+ const wrap = document.createElement("div");
428
+ wrap.className = "tool-section";
429
+ const title = document.createElement("h4");
430
+ title.textContent = section.title;
431
+ const pre = document.createElement("pre");
432
+ if (section.isError) pre.classList.add("is-error");
433
+ pre.textContent = section.text;
434
+ wrap.append(title, pre);
435
+ body.append(wrap);
405
436
  }
406
- return "";
437
+ }
438
+
439
+ function thinkingHint(item) {
440
+ if (item.streaming) return "思考中…";
441
+ const chars = [...(item.thinking ?? "")].length;
442
+ return chars ? `${chars} 字` : "";
407
443
  }
408
444
 
409
445
  function buildItemEl(item) {
@@ -422,7 +458,11 @@ function buildItemEl(item) {
422
458
  const thinking = document.createElement("details");
423
459
  thinking.className = "thinking-block";
424
460
  const summary = document.createElement("summary");
425
- summary.textContent = "思考过程";
461
+ const summaryLabel = document.createElement("span");
462
+ summaryLabel.textContent = "思考过程";
463
+ const thinkingHintEl = document.createElement("span");
464
+ thinkingHintEl.className = "thinking-hint";
465
+ summary.append(summaryLabel, thinkingHintEl);
426
466
  const thinkingBody = document.createElement("div");
427
467
  thinkingBody.className = "thinking-body";
428
468
  thinking.append(summary, thinkingBody);
@@ -434,20 +474,9 @@ function buildItemEl(item) {
434
474
  const meta = document.createElement("div");
435
475
  meta.className = "meta";
436
476
 
437
- const actions = document.createElement("div");
438
- actions.className = "msg-actions";
439
- actions.hidden = true;
440
- for (const [act, label] of [["copy", "复制"], ["fork", "分叉"], ["usage", "用量"]]) {
441
- const btn = document.createElement("button");
442
- btn.type = "button";
443
- btn.className = "mini";
444
- btn.dataset.act = act;
445
- btn.textContent = label;
446
- actions.append(btn);
447
- }
448
-
449
- wrap.append(thinking, bubble, tools, actions, meta);
450
- item.refs = { thinking, thinkingBody, bubble, tools, actions, meta, toolEls: new Map() };
477
+ // 不再有常显操作行(`.msg-actions`):复制/分叉/用量走气泡上的右键 / 长按上下文菜单
478
+ wrap.append(thinking, bubble, tools, meta);
479
+ item.refs = { thinking, thinkingBody, thinkingHint: thinkingHintEl, bubble, tools, meta, toolEls: new Map() };
451
480
  item.el = wrap;
452
481
  return wrap;
453
482
  }
@@ -459,6 +488,7 @@ function appendItemEl(item) {
459
488
  const el = buildItemEl(item);
460
489
  box.append(el);
461
490
  patchItem(item);
491
+ // 新消息只在贴底时跟随(F8);用户上滑后在读上文,位置必须原地不动
462
492
  if (state.pinned) scrollToBottom();
463
493
  }
464
494
 
@@ -469,14 +499,20 @@ function patchItem(item) {
469
499
  refs.bubble.innerHTML = renderMarkdown(item.text);
470
500
  return;
471
501
  }
472
- if (item.thinking) {
473
- refs.thinking.hidden = false;
474
- refs.thinkingBody.textContent = item.thinking;
502
+ // 思考块:没有思考正文就整块不画(以前会留一个空的虚线框,看着像空行)
503
+ const thinking = item.thinking ?? "";
504
+ refs.thinking.hidden = !thinking;
505
+ if (thinking) {
506
+ refs.thinkingBody.textContent = thinking;
507
+ refs.thinkingHint.textContent = thinkingHint(item);
475
508
  // 用户手动折叠/展开过就不再自动覆盖;否则流式中展开、结束后收起
476
- const touched = refs.thinking.dataset.touched === "1";
477
- refs.thinking.open = touched ? refs.thinking.open : item.streaming;
509
+ if (refs.thinking.dataset.touched !== "1") setDetailsOpen(refs.thinking, Boolean(item.streaming));
478
510
  }
479
- refs.bubble.innerHTML = renderMarkdown(item.text) + (item.streaming ? '<span class="typing"></span>' : "");
511
+ // 正文为空时不画气泡(否则「思考过程」与工具卡之间多出一个空框)
512
+ const html = renderMarkdown(item.text);
513
+ const visible = Boolean(item.text);
514
+ refs.bubble.hidden = !visible;
515
+ refs.bubble.innerHTML = visible ? html + (item.streaming ? '<span class="typing"></span>' : "") : "";
480
516
  for (const id of item.toolOrder) {
481
517
  const tool = item.tools.get(id);
482
518
  if (!tool) continue;
@@ -485,26 +521,15 @@ function patchItem(item) {
485
521
  const status = card.querySelector(".tool-state");
486
522
  status.textContent = toolStateText(tool);
487
523
  status.classList.toggle("err", Boolean(tool.isError));
488
- const pre = card.querySelector("pre");
489
- const body = toolBodyText(tool);
490
- if (pre.textContent !== body) pre.textContent = body;
491
- if (tool.state === "running") card.open = true;
524
+ renderToolBody(card.querySelector(".tool-body"), tool);
525
+ if (card.dataset.touched !== "1") setDetailsOpen(card, tool.state === "running");
492
526
  }
527
+ // token 数只在底部脚注出现一次(W1-b):消息 meta 只留 `model · 耗时`。
493
528
  const metaParts = [];
494
529
  if (item.model) metaParts.push(item.model);
495
- if (item.durationMs) metaParts.push(`${(item.durationMs / 1000).toFixed(1)}s`);
496
- if (item.usage?.totalTokens) metaParts.push(`${formatTokens(item.usage.totalTokens)} tokens`);
530
+ if (item.durationMs) metaParts.push(formatDuration(item.durationMs));
497
531
  if (item.stopReason && item.stopReason !== "stop") metaParts.push(item.stopReason);
498
532
  refs.meta.textContent = metaParts.join(" · ");
499
- // 生成中不露操作行(正文还在长,复制/分叉没有意义)
500
- if (refs.actions) refs.actions.hidden = item.streaming || !item.text;
501
- }
502
-
503
- function formatTokens(n) {
504
- const v = Number(n) || 0;
505
- if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
506
- if (v >= 1000) return `${(v / 1000).toFixed(1)}k`;
507
- return String(v);
508
533
  }
509
534
 
510
535
  function renderMessages() {
@@ -526,68 +551,291 @@ function renderMessages() {
526
551
  patchItem(item);
527
552
  }
528
553
  box.append(frag);
554
+ // 整屏重画只在开会话/载入历史时发生(F8 的「用户主动进入」),这里强制贴底;
555
+ // 流式追加绝不能走这条路(否则上滑阅读会被冲刷)
529
556
  scrollToBottom();
530
557
  }
531
558
 
532
559
  function scrollToBottom() {
533
560
  const box = $("messages");
534
561
  box.scrollTop = box.scrollHeight;
562
+ // 程序化滚底后 scroll 事件会异步回来复核一次,这里先把状态置上,避免在回包前被当成“已上滑”
535
563
  state.pinned = true;
564
+ state.lastScrollTop = box.scrollTop;
536
565
  $("btn-jump").hidden = true;
537
566
  }
538
567
 
539
- function historyToItems(messages) {
540
- const items = [];
541
- for (const m of messages ?? []) {
542
- if (m.role === "user") {
543
- items.push({ role: "user", text: m.text ?? "", ts: m.ts });
544
- continue;
568
+ // ---------- 用量 ----------
569
+
570
+ function renderUsage() {
571
+ const bar = $("usage-bar");
572
+ const lines = usageLines(state.stats, state.usage);
573
+ $("usage-full").textContent = lines.full;
574
+ $("usage-narrow").textContent = lines.narrow;
575
+ bar.hidden = !lines.full;
576
+ }
577
+
578
+ // ---------- 气泡上下文菜单 ----------
579
+ // 鼠标右键 / 触摸长按 ≥500ms 在**指针坐标**画一个 position:fixed 的小菜单(不是顶层页面、不是底栏 sheet);
580
+ // pointerdown 到菜单外 / 窗口 blur / Escape / 消息区滚动 即销毁(W1-a)。
581
+ const LONG_PRESS_MS = 500;
582
+ const LONG_PRESS_MOVE_PX = 10;
583
+ /** @type {{el: HTMLElement, hideTimer: number}|null} */
584
+ const ctxMenu = { el: null, forItem: null };
585
+
586
+ function ensureCtxMenu() {
587
+ if (ctxMenu.el) return ctxMenu.el;
588
+ const menu = document.createElement("div");
589
+ menu.id = "ctx-menu";
590
+ menu.className = "ctx-menu";
591
+ menu.setAttribute("role", "menu");
592
+ menu.hidden = true;
593
+ menu.addEventListener("pointerdown", (event) => event.stopPropagation());
594
+ menu.addEventListener("click", (event) => {
595
+ const btn = event.target.closest("[data-act]");
596
+ if (!btn || !ctxMenu.forItem) return;
597
+ runMsgAction(btn.dataset.act, ctxMenu.forItem);
598
+ closeCtxMenu();
599
+ });
600
+ document.body.append(menu);
601
+ ctxMenu.el = menu;
602
+ return menu;
603
+ }
604
+
605
+ function msgMenuItems(item) {
606
+ // 文案对齐安卓(`messageMenuActions`):复制全文 / 分叉会话 / 用量统计
607
+ const items = [{ act: "copy", label: "复制全文" }];
608
+ if (item.role === "assistant") items.push({ act: "fork", label: "分叉会话" });
609
+ if (item.usage) items.push({ act: "usage", label: "用量统计" });
610
+ return items;
611
+ }
612
+
613
+ /** 在视口内 clamp:菜单贴右边/底部时向左上翻转,永不溢出窗口。 */
614
+ function positionCtxMenu(menu, x, y) {
615
+ menu.style.left = "0px";
616
+ menu.style.top = "0px";
617
+ const { width, height } = menu.getBoundingClientRect();
618
+ const left = Math.max(4, Math.min(x, window.innerWidth - width - 4));
619
+ const top = Math.max(4, Math.min(y, window.innerHeight - height - 4));
620
+ menu.style.left = `${Math.round(left)}px`;
621
+ menu.style.top = `${Math.round(top)}px`;
622
+ }
623
+
624
+ function openCtxMenu(item, x, y) {
625
+ const menu = ensureCtxMenu();
626
+ menu.textContent = "";
627
+ for (const { act, label } of msgMenuItems(item)) {
628
+ const btn = document.createElement("button");
629
+ btn.type = "button";
630
+ btn.dataset.act = act;
631
+ btn.setAttribute("role", "menuitem");
632
+ btn.textContent = label;
633
+ menu.append(btn);
634
+ }
635
+ ctxMenu.forItem = item;
636
+ menu.hidden = false;
637
+ positionCtxMenu(menu, x, y);
638
+ }
639
+
640
+ function closeCtxMenu() {
641
+ if (!ctxMenu.el || ctxMenu.el.hidden) return;
642
+ ctxMenu.el.hidden = true;
643
+ ctxMenu.forItem = null;
644
+ }
645
+
646
+ async function runMsgAction(act, item) {
647
+ if (act === "copy") {
648
+ try {
649
+ await navigator.clipboard.writeText(item.text ?? "");
650
+ toast("已复制全文");
651
+ } catch {
652
+ toast("复制失败(浏览器不允许)");
545
653
  }
546
- if (m.role !== "assistant") continue;
547
- const toolMap = new Map();
548
- const order = [];
549
- for (const call of m.toolCalls ?? []) {
550
- if (!call?.id) continue;
551
- toolMap.set(call.id, { id: call.id, name: call.name ?? "tool", args: call.args, state: "done" });
552
- order.push(call.id);
654
+ return;
655
+ }
656
+ if (act === "fork") {
657
+ await forkSession({ item });
658
+ return;
659
+ }
660
+ if (act === "usage") {
661
+ const u = item.usage;
662
+ if (!u) {
663
+ toast("这条回答没有用量数据");
664
+ return;
553
665
  }
554
- items.push({
555
- role: "assistant",
556
- text: m.text ?? "",
557
- thinking: m.thinking ?? "",
558
- tools: toolMap,
559
- toolOrder: order,
560
- streaming: false,
561
- usage: m.usage ?? null,
562
- model: m.model ?? null,
563
- durationMs: m.durationMs ?? null,
564
- stopReason: m.stopReason ?? null,
565
- ts: m.ts,
566
- el: null,
567
- refs: null,
568
- });
666
+ const rate = item.durationMs && u.outputTokens
667
+ ? ` · ${(u.outputTokens / (item.durationMs / 1000)).toFixed(1)} tok/s`
668
+ : "";
669
+ toast(`入 ${formatTokens(u.inputTokens)} · 出 ${formatTokens(u.outputTokens)} · 共 ${formatTokens(u.totalTokens)}${rate}`);
569
670
  }
570
- return items;
571
671
  }
572
672
 
573
- // ---------- 用量 ----------
673
+ /** 消息元素 → 渲染项(菜单要拿 item 才能复制/分叉)。 */
674
+ function itemForEl(el) {
675
+ const root = el?.closest?.(".msg");
676
+ return root ? state.items.find((it) => it.el === root) ?? null : null;
677
+ }
574
678
 
575
- function renderUsage() {
576
- const bar = $("usage-bar");
577
- const ctx = state.stats?.contextUsage ?? null;
578
- const parts = [];
579
- if (ctx && Number.isFinite(ctx.percent)) {
580
- const pct = Math.round(ctx.percent);
581
- const used = formatTokens(ctx.tokens);
582
- const window = ctx.contextWindow ? ` / ${formatTokens(ctx.contextWindow)}` : "";
583
- parts.push(`上下文 ${pct}% · ${used}${window}`);
584
- } else if (state.usage?.totalTokens) {
585
- parts.push(`本机累计 ${formatTokens(state.usage.totalTokens)} tokens`);
679
+ function bindMsgContextMenu() {
680
+ const box = $("messages");
681
+ let press = null; // {timer, point}
682
+
683
+ box.addEventListener("contextmenu", (event) => {
684
+ const item = itemForEl(event.target);
685
+ if (!item) return;
686
+ event.preventDefault();
687
+ openCtxMenu(item, event.clientX, event.clientY);
688
+ });
689
+
690
+ const cancel = () => {
691
+ clearTimeout(press?.timer);
692
+ press = null;
693
+ };
694
+ box.addEventListener("pointerdown", (event) => {
695
+ // 鼠标左键/触摸/笔都认;鼠标右键交给 contextmenu(否则会先起长按计时)
696
+ if (event.pointerType === "mouse" && event.button !== 0) return;
697
+ const item = itemForEl(event.target);
698
+ if (!item) return;
699
+ cancel();
700
+ const point = { x: event.clientX, y: event.clientY };
701
+ const timer = setTimeout(() => {
702
+ press = null;
703
+ openCtxMenu(item, point.x, point.y);
704
+ }, LONG_PRESS_MS);
705
+ press = { timer, point };
706
+ });
707
+
708
+ box.addEventListener("pointermove", (event) => {
709
+ if (!press) return;
710
+ if (Math.hypot(event.clientX - press.point.x, event.clientY - press.point.y) > LONG_PRESS_MOVE_PX) cancel();
711
+ });
712
+ box.addEventListener("pointerup", cancel);
713
+ box.addEventListener("pointercancel", cancel);
714
+ // 菜单开着时在消息区滚动(滚轮/触摸滑动都会触发 scroll)就销毁
715
+ box.addEventListener("scroll", closeCtxMenu);
716
+ // 点菜单以外任何地方销毁(capture 阶段,免得被 stopPropagation 绕开)
717
+ document.addEventListener("pointerdown", (event) => {
718
+ if (ctxMenu.el && !ctxMenu.el.hidden && !ctxMenu.el.contains(event.target)) closeCtxMenu();
719
+ }, true);
720
+ window.addEventListener("blur", closeCtxMenu);
721
+ document.addEventListener("keydown", (event) => {
722
+ if (event.key === "Escape") closeCtxMenu();
723
+ });
724
+ }
725
+
726
+ /**
727
+ * 锚定弹出菜单(#menu,R8-F1):rail ⋯ / 顶栏 ⋯ / 任何「贴着按钮」的菜单都走 openMenuAt(anchor)。
728
+ * 以前 #menu 是 `.menu { position:absolute; top:48px; right:8px }`,挂在折叠态被 `hidden` 的
729
+ * #btn-menu 上 ⇒ 点图标栏 ⋯ 菜单出现在窗口右上角(用户截图)。现在落点现算:fixed + 视口
730
+ * clamp + 下方放不下就上翻 + 左窄栏从按钮右侧长出(menuPlacement 纯函数)。
731
+ */
732
+ const anchoredMenu = { el: null, anchor: null };
733
+
734
+ /** @param {HTMLElement} menu @param {HTMLElement} anchor */
735
+ function openMenuAt(menu, anchor) {
736
+ // 另一张锚定菜单(顶栏 ⋯ / 组头 ⋮)还开着就先收掉,免得两张菜单叠在一起
737
+ if (anchoredMenu.el && anchoredMenu.el !== menu) anchoredMenu.el.hidden = true;
738
+ menu.hidden = false;
739
+ menu.style.position = "fixed";
740
+ // 先挪到窗口外量尺寸:量完再定位,否则首帧会从旧位置闪一次
741
+ menu.style.left = "-9999px";
742
+ menu.style.top = "0px";
743
+ const size = menu.getBoundingClientRect();
744
+ const pos = menuPlacement(anchor.getBoundingClientRect(), size, {
745
+ width: window.innerWidth,
746
+ height: window.innerHeight,
747
+ });
748
+ menu.style.left = `${Math.round(pos.left)}px`;
749
+ menu.style.top = `${Math.round(pos.top)}px`;
750
+ menu.dataset.placement = pos.placement;
751
+ menu.dataset.anchor = anchor.id;
752
+ anchoredMenu.el = menu;
753
+ anchoredMenu.anchor = anchor;
754
+ }
755
+
756
+ /** @returns {boolean} 这次调用是否真关掉了菜单(Escape 用它决定要不要继续往下处理) */
757
+ function closeAnchoredMenu() {
758
+ const menu = anchoredMenu.el;
759
+ if (!menu || menu.hidden) return false;
760
+ menu.hidden = true;
761
+ delete menu.dataset.anchor;
762
+ anchoredMenu.el = null;
763
+ anchoredMenu.anchor = null;
764
+ return true;
765
+ }
766
+
767
+ /** 点同一个按钮=开关;点另一个锚点=就地改挂到新按钮旁。 */
768
+ function toggleMenuAt(anchor) {
769
+ const menu = $("menu");
770
+ if (anchoredMenu.anchor === anchor && !menu.hidden) closeAnchoredMenu();
771
+ else openMenuAt(menu, anchor);
772
+ }
773
+
774
+ /** 组头 ⋮ 菜单当前指向的 cwd(抽屉重画后锚点会换新,选择存这里不掉)。 */
775
+ let groupMenuCwd = null;
776
+
777
+ /**
778
+ * 工作区组头 ⋮:复用同一个 openMenuAt(anchor) 定位器(不另写一套)。
779
+ * 项集合先上安卓工作区长按菜单里的前两项(查看全部会话 / 折叠该组)。
780
+ */
781
+ function toggleGroupMenu(anchor) {
782
+ const menu = $("group-menu");
783
+ if (anchoredMenu.anchor === anchor && !menu.hidden) {
784
+ closeAnchoredMenu();
785
+ return;
786
+ }
787
+ groupMenuCwd = anchor.dataset.cwd ?? null;
788
+ const count = Number(anchor.dataset.count) || 0;
789
+ const collapsed = state.collapsedGroups.includes(groupMenuCwd);
790
+ $("btn-group-all").textContent = `查看全部会话(${count})`;
791
+ $("btn-group-toggle").textContent = collapsed ? "展开该组" : "折叠该组";
792
+ openMenuAt(menu, anchor);
793
+ }
794
+
795
+ /** 「查看全部会话」= 清掉搜索过滤并展开该组,把这一组会话全部列出来。 */
796
+ function showAllGroupSessions() {
797
+ const cwd = groupMenuCwd;
798
+ closeAnchoredMenu();
799
+ if (!cwd) return;
800
+ if (state.collapsedGroups.includes(cwd)) {
801
+ state.collapsedGroups = toggleCollapsedGroup(state.collapsedGroups, cwd);
802
+ store(STORE_KEYS.collapsedGroups, JSON.stringify(state.collapsedGroups));
803
+ }
804
+ if (state.search) {
805
+ state.search = "";
806
+ $("session-search").value = "";
807
+ }
808
+ renderDrawer();
809
+ }
810
+
811
+ function toggleGroupCollapsed() {
812
+ const cwd = groupMenuCwd;
813
+ closeAnchoredMenu();
814
+ if (!cwd) return;
815
+ state.collapsedGroups = toggleCollapsedGroup(state.collapsedGroups, cwd);
816
+ store(STORE_KEYS.collapsedGroups, JSON.stringify(state.collapsedGroups));
817
+ renderDrawer();
818
+ }
819
+
820
+ /** 销毁路径:外部点击 / 失焦 / 任何滚动(fixed 菜单不跟滚)/ resize(窗口变了就得重算)。 */
821
+ function bindAnchoredMenu() {
822
+ for (const menu of [$("menu"), $("group-menu")]) {
823
+ menu.addEventListener("pointerdown", (event) => event.stopPropagation());
586
824
  }
587
- const cost = state.stats?.cost ?? state.usage?.cost ?? null;
588
- $("usage-context").textContent = parts.join(" · ");
589
- $("usage-cost").textContent = typeof cost === "number" && cost > 0 ? `$${cost.toFixed(4)}` : "";
590
- bar.hidden = !(parts.length || $("usage-cost").textContent);
825
+ document.addEventListener(
826
+ "pointerdown",
827
+ (event) => {
828
+ if (!anchoredMenu.anchor) return;
829
+ // 锚点自己的点击交给 toggle* 入口,否则会「先关再开」
830
+ if (anchoredMenu.el.contains(event.target) || anchoredMenu.anchor.contains(event.target)) return;
831
+ closeAnchoredMenu();
832
+ },
833
+ true,
834
+ );
835
+ window.addEventListener("blur", () => closeAnchoredMenu());
836
+ // 捕获阶段收所有滚动容器(消息区 / 会话列表 / 窗口)的事件
837
+ window.addEventListener("scroll", () => closeAnchoredMenu(), true);
838
+ window.addEventListener("resize", () => closeAnchoredMenu());
591
839
  }
592
840
 
593
841
  async function refreshStats() {
@@ -716,7 +964,10 @@ function handleEvent(ev) {
716
964
  item.toolOrder.push(id);
717
965
  }
718
966
  if (ev.args !== undefined) tool.args = ev.args;
719
- if (ev.type === "tool_start") tool.state = "running";
967
+ if (ev.type === "tool_start") {
968
+ tool.state = "running";
969
+ tool.startedAt = Date.now();
970
+ }
720
971
  if (ev.type === "tool_call") tool.state = tool.state === "running" ? "running" : "queued";
721
972
  if (ev.type === "tool_progress") {
722
973
  tool.state = "running";
@@ -738,6 +989,7 @@ function handleEvent(ev) {
738
989
  if (ev.thinking !== undefined) item.thinking = ev.thinking;
739
990
  item.streaming = false;
740
991
  patchItem(item);
992
+ if (state.pinned) scrollToBottom();
741
993
  break;
742
994
  }
743
995
  case "turn_end": {
@@ -806,9 +1058,14 @@ function handleEvent(ev) {
806
1058
  }
807
1059
  }
808
1060
 
1061
+ /**
1062
+ * 执行态 UI(F9):发送键**始终**可见可点(agent 跑着也能发 = 服务端排队 follow-up),
1063
+ * 额外多出停止键。两键并存,不是以前那样 `hidden = busy` 互斥替换。
1064
+ * 一律只改 `hidden`,不碰 `state.stream`/正在流的消息。
1065
+ */
809
1066
  function setStreamingUi(busy) {
810
1067
  state.streaming = busy;
811
- $("btn-send").hidden = busy;
1068
+ $("btn-send").hidden = false;
812
1069
  $("btn-stop").hidden = !busy;
813
1070
  }
814
1071
 
@@ -980,6 +1237,9 @@ async function send() {
980
1237
  const input = $("prompt");
981
1238
  const text = input.value.trim();
982
1239
  if (!text && !state.images.length && !state.docs.length) return;
1240
+ // 发送成功后要清的草稿键:ensureSession 新建会话时 state.draftKey 会换成新会话 id,
1241
+ // 所以这里先把「写字时那个键」记下来,两边都清。
1242
+ const sentDraftKey = state.draftKey;
983
1243
  let finalText = text;
984
1244
  for (const doc of state.docs) {
985
1245
  finalText += `${finalText ? "\n\n" : ""}[附件] ${doc.path}`;
@@ -988,19 +1248,29 @@ async function send() {
988
1248
  try {
989
1249
  const id = await ensureSession();
990
1250
  input.value = "";
1251
+ saveDraft(sentDraftKey, "");
1252
+ saveDraft(state.draftKey, "");
991
1253
  hideSlash();
992
1254
  autosize();
993
1255
  state.images = [];
994
1256
  state.docs = [];
995
1257
  renderAttachments();
1258
+ // 用户自己发言 = 唯一无条件跟随的时机(F8):强制贴底并滚到底,焦点回输入框(F7)
996
1259
  state.pinned = true;
1260
+ scrollToBottom();
1261
+ input.focus();
997
1262
  const body = { text: finalText };
998
1263
  if (images.length) body.images = images;
1264
+ // F9:执行中发送必须显式声明排队语义(服务端 readStreamingBehavior 只认 steer/followUp),
1265
+ // 不传就会被 pi 以 409 prompt_rejected 拒掉(W-VERIFY 实测)。
1266
+ if (state.streaming) body.streamingBehavior = "followUp";
999
1267
  const data = await api(`/v1/sessions/${id}/prompt`, { method: "POST", body });
1268
+ // 执行中发送(F9):服务端自行排队 follow-up,UI 只提示一句,不改 streaming 也不清流
1000
1269
  if (data?.disposition === "queued") toast("已排队(正在生成)");
1001
1270
  setStreamingUi(true);
1002
1271
  } catch (err) {
1003
1272
  input.value = text;
1273
+ saveDraft(state.draftKey, text);
1004
1274
  toast(`发送失败:${err.message}`);
1005
1275
  }
1006
1276
  }
@@ -1017,31 +1287,59 @@ async function stop() {
1017
1287
 
1018
1288
  function applySession(session) {
1019
1289
  state.session = session;
1020
- const title = session?.name || session?.sessionId || state.sessionId || "pi hub";
1290
+ const title = sessionTitle(session, state.sessionId);
1021
1291
  $("session-title").textContent = title;
1292
+ // 完整值放 title 属性(标题只显示人读的那段,hover 才能看到全路径/全 id)
1293
+ $("session-title").title = session?.name || session?.cwd || session?.sessionId || state.sessionId || "";
1022
1294
  const parts = [];
1023
1295
  if (session?.cwd) parts.push(session.cwd);
1024
- if (session?.model) parts.push(session.model);
1296
+ // live 快照的 model 是 `{provider,id}` 对象:直接拼字符串会渲染成 `[object Object]`(实测)
1297
+ const modelLabel = modelValueCandidates(session?.model)[0];
1298
+ if (modelLabel) parts.push(modelLabel);
1025
1299
  if (session?.status) parts.push(session.status);
1026
1300
  $("session-sub").textContent = parts.join(" · ");
1027
- if (session?.model) selectIfPresent($("model-select"), modelValueOf(session.model));
1301
+ // 快照没有 model 时(`starting` 的新会话)再从历史消息里拿;都没有就显示「默认」,不停在「模型…」
1302
+ const model = pickSessionModel(session?.model, state.items);
1303
+ if (model) selectSessionModel($("model-select"), model);
1304
+ setModelPlaceholder($("model-select"), "默认");
1028
1305
  }
1029
1306
 
1030
- function modelValueOf(model) {
1031
- if (model && typeof model === "object") {
1032
- return model.provider ? `${model.provider}/${model.id}` : (model.id ?? "");
1033
- }
1034
- return String(model ?? "");
1307
+ /** 无模型时的占位文案:会话已打开就不再是「模型…」,而是这条会话在用的「默认」模型。 */
1308
+ function setModelPlaceholder(select, text) {
1309
+ const option = select.querySelector('option[value=""]');
1310
+ if (option && option.textContent !== text) option.textContent = text;
1035
1311
  }
1036
1312
 
1037
- function selectIfPresent(select, value) {
1038
- if (!value) return;
1039
- const option = [...select.options].find((o) => o.value === value);
1040
- if (option) select.value = value;
1313
+ /**
1314
+ * 会话模型落到 `#model-select`:
1315
+ * 1. 先按选项 value(`provider/id`)精确/按 id 部分匹配(历史行的 model 是裸 id);
1316
+ * 2. 匹配不上就补一条「当前模型(不在列表)」选项 —— 用户要看到这条会话到底用什么模型,
1317
+ * 而不是停在「模型…」占位(R5 实测)。
1318
+ * @param {HTMLSelectElement} select
1319
+ * @param {string|{provider?:string,id?:string}} model
1320
+ */
1321
+ function selectSessionModel(select, model) {
1322
+ select.querySelector('option[data-current="1"]')?.remove();
1323
+ const values = [...select.options].map((option) => option.value).filter((value) => value !== "");
1324
+ const matched = matchModelValue(values, model);
1325
+ if (matched !== null) {
1326
+ select.value = matched;
1327
+ return;
1328
+ }
1329
+ const label = typeof model === "object" ? [model.provider, model.id].filter(Boolean).join("/") : String(model);
1330
+ if (!label) return;
1331
+ const option = document.createElement("option");
1332
+ option.value = label;
1333
+ option.textContent = `${label}(不在列表)`;
1334
+ option.dataset.current = "1";
1335
+ select.append(option);
1336
+ select.value = label;
1041
1337
  }
1042
1338
 
1043
1339
  async function openSession(id) {
1044
1340
  state.sessionId = id;
1341
+ // 草稿换成这条会话的副本(F7):先把上一个键的输入落盘,再载入这里(新建的会话是空草稿)
1342
+ switchDraft(draftKeyOf(id, null));
1045
1343
  state.items = [];
1046
1344
  state.streaming = false;
1047
1345
  state.stats = null;
@@ -1053,7 +1351,11 @@ async function openSession(id) {
1053
1351
  renderUsage();
1054
1352
  setStreamingUi(false);
1055
1353
  $("session-title").textContent = id.slice(0, 8);
1354
+ $("session-title").title = id;
1056
1355
  $("session-sub").textContent = "";
1356
+ // 会话一打开就先把占位改成「默认」(F4):`starting` 时 /state 可能还没 model,
1357
+ // 等状态/历史到了再由 applySession / 历史回填成真模型。
1358
+ setModelPlaceholder($("model-select"), "默认");
1057
1359
  // 这里不再 renderMessages():history 一到就整屏重画,先画空态只会多一次闪烁。
1058
1360
  $("messages").textContent = "";
1059
1361
  closeDrawer();
@@ -1064,6 +1366,9 @@ async function openSession(id) {
1064
1366
  const hist = await api(`/v1/sessions/${id}/history`);
1065
1367
  state.items = historyToItems(hist?.messages ?? []);
1066
1368
  renderMessages();
1369
+ // 历史里最后一条 assistant 带 model 就选上(/state 拿不到时的补路,F4)
1370
+ const model = pickSessionModel(state.session?.model, state.items);
1371
+ if (model) selectSessionModel($("model-select"), model);
1067
1372
  } catch (err) {
1068
1373
  toast(`历史加载失败:${err.message}`);
1069
1374
  }
@@ -1077,6 +1382,9 @@ async function loadThinking(id) {
1077
1382
  // 必须先问 /state:`GET /v1/sessions/:id/thinking` 走 requireLive ⇒ 非 live 会话会被**spawn** 出来,
1078
1383
  // 只为读一个档位列表就起一个 pi 子进程(占 MAX_LIVE 槽、抢会话锁),绝不划算。所以保持串行。
1079
1384
  const info = await api(`/v1/sessions/${id}/state`).catch(() => null);
1385
+ // 非 live 会话不会收到 SSE `ready` 帧(那一帧只在 spawn 时发),模型/工作区展示
1386
+ // 只能靠这里补:不补就留在「模型…」占位(R5 实测)。已打开的会话幂等。
1387
+ if (info?.state) applySession(info.state);
1080
1388
  const live = info?.live === true;
1081
1389
  const data = live ? await api(`/v1/sessions/${id}/thinking`) : await api("/v1/thinking");
1082
1390
  state.levels = data?.levels ?? [];
@@ -1085,8 +1393,9 @@ async function loadThinking(id) {
1085
1393
  select.textContent = "";
1086
1394
  for (const level of state.levels) {
1087
1395
  const option = document.createElement("option");
1396
+ // value 保持原始 level(POST /thinking 认它);只把 label 本地化成 关/极简/低/中/高
1088
1397
  option.value = level;
1089
- option.textContent = level;
1398
+ option.textContent = thinkingLevelLabel(level);
1090
1399
  select.append(option);
1091
1400
  }
1092
1401
  if (state.level) select.value = state.level;
@@ -1251,12 +1560,13 @@ async function forkSession({ item = null, clone = false } = {}) {
1251
1560
  // 非 clone 时服务端回传被分叉的那条 user 文本:回填输入框方便改完重问
1252
1561
  if (!clone && data.text) {
1253
1562
  $("prompt").value = data.text;
1563
+ saveDraft(state.draftKey, data.text);
1254
1564
  autosize();
1255
1565
  $("prompt").focus();
1256
1566
  }
1257
1567
  toast("已分叉到新会话");
1258
1568
  } catch (err) {
1259
- toast(`分叉失败:${err.message}`);
1569
+ showError(`分叉失败:${err.message}`);
1260
1570
  }
1261
1571
  }
1262
1572
 
@@ -1278,7 +1588,7 @@ async function exportSession() {
1278
1588
  setTimeout(() => URL.revokeObjectURL(url), 30_000);
1279
1589
  toast(`已导出 ${name}`);
1280
1590
  } catch (err) {
1281
- toast(`导出失败:${err.message}`);
1591
+ showError(`导出失败:${err.message}`);
1282
1592
  }
1283
1593
  }
1284
1594
 
@@ -1303,13 +1613,90 @@ function toast(message) {
1303
1613
  }, 3200);
1304
1614
  }
1305
1615
 
1616
+ /**
1617
+ * 常驻错误横幅(P1-9):3.2s toast 一闪就没、错误的 `message` 根本没机会读。
1618
+ * 横幅不自动消失(保留手动关闭 ✕),位置在顶栏下方,不遮输入框。
1619
+ */
1620
+ function showError(message) {
1621
+ $("error-banner-text").textContent = message;
1622
+ $("error-banner").hidden = false;
1623
+ }
1624
+
1625
+ function hideError() {
1626
+ $("error-banner").hidden = true;
1627
+ }
1628
+
1306
1629
  /** 只让抽屉可见(数据已经在 state 里),不重新拉列表。 */
1307
1630
  function showDrawer() {
1308
1631
  $("drawer").hidden = false;
1309
1632
  $("scrim").hidden = false;
1310
1633
  }
1311
1634
 
1635
+ /**
1636
+ * 桌面侧栏折叠态落到 DOM:`body.sidebar-collapsed` 只在 `@media (min-width:900px)`
1637
+ * 里生效(窄屏抽屉的 hidden/scrim 语义一点不动);两个按钮的 aria-expanded 跟着走。
1638
+ */
1639
+ function applySidebarCollapsed() {
1640
+ // 折叠/展开会把锚点按钮自己藏起来(rail ⋯ ↔ 顶栏 ⋯),菜单得跟着消失
1641
+ closeAnchoredMenu();
1642
+ document.body.classList.toggle("sidebar-collapsed", state.sidebarCollapsed);
1643
+ const expanded = String(!state.sidebarCollapsed);
1644
+ $("btn-drawer")?.setAttribute("aria-expanded", expanded);
1645
+ $("btn-drawer-close")?.setAttribute("aria-expanded", expanded);
1646
+ $("btn-rail-expand")?.setAttribute("aria-expanded", expanded);
1647
+ applyTopbarChrome();
1648
+ }
1649
+
1650
+ /**
1651
+ * 同一动作全屏只允许一个入口(W1-c 补充):
1652
+ * - 桌面折叠态:图标栏负责 +/🔍/⋯/展开 ⇒ 顶栏只留标题 + 连接点(三个按钮 `hidden`)
1653
+ * - 桌面展开态 / <900px:图标栏不可见(CSS `display:none`,不在 tab 序列),顶栏保留 ☰/+/⋯
1654
+ * 用 `hidden` 属性而不是 CSS 遮盖,保证「看不见 = 不可点 = 不可 tab」。
1655
+ */
1656
+ function applyTopbarChrome() {
1657
+ const railOnly = isWideScreen() && state.sidebarCollapsed;
1658
+ for (const id of ["btn-drawer", "btn-new", "btn-menu"]) {
1659
+ const el = $(id);
1660
+ if (el) el.hidden = railOnly;
1661
+ }
1662
+ }
1663
+
1664
+ /**
1665
+ * 折叠/展开前后钉住「当前视口顶部那条消息」(W1-c):主区宽度变了会重排,
1666
+ * 不锚定的话滚动条会跳到别的位置。返回锚点元素 + 它距滚动容器顶的距离。
1667
+ */
1668
+ function captureScrollAnchor() {
1669
+ const box = $("messages");
1670
+ const top = box.getBoundingClientRect().top;
1671
+ const first = [...box.querySelectorAll(".msg")].find((el) => el.getBoundingClientRect().bottom > top + 1);
1672
+ return first ? { el: first, offset: first.getBoundingClientRect().top - top } : null;
1673
+ }
1674
+
1675
+ function restoreScrollAnchor(anchor) {
1676
+ if (!anchor) return;
1677
+ const box = $("messages");
1678
+ const drift = anchor.el.getBoundingClientRect().top - box.getBoundingClientRect().top - anchor.offset;
1679
+ if (Math.abs(drift) > 0.5) box.scrollTop += drift;
1680
+ }
1681
+
1682
+ function setSidebarCollapsed(collapsed) {
1683
+ if (collapsed === state.sidebarCollapsed) return;
1684
+ const anchor = state.pinned ? null : captureScrollAnchor();
1685
+ state.sidebarCollapsed = collapsed;
1686
+ store(STORE_KEYS.sidebarCollapsed, collapsed ? "1" : "0");
1687
+ applySidebarCollapsed();
1688
+ restoreScrollAnchor(anchor);
1689
+ }
1690
+
1691
+ /** 顶栏 ☰ / 侧栏收起按钮:宽屏切折叠态,窄屏还是原来的抽屉开关。 */
1692
+ function toggleSidebar() {
1693
+ if (isWideScreen()) setSidebarCollapsed(!state.sidebarCollapsed);
1694
+ else if ($("drawer").hidden) openDrawer();
1695
+ else closeDrawer();
1696
+ }
1697
+
1312
1698
  function openDrawer() {
1699
+ if (isWideScreen() && state.sidebarCollapsed) setSidebarCollapsed(false);
1313
1700
  showDrawer();
1314
1701
  loadSessions().catch(() => {});
1315
1702
  }
@@ -1319,6 +1706,33 @@ function closeDrawer() {
1319
1706
  $("scrim").hidden = true;
1320
1707
  }
1321
1708
 
1709
+ /**
1710
+ * 抽屉底部「新建会话」表单默认收起(常驻展开会把历史列表挤掉一大截)。
1711
+ * @param {boolean} open
1712
+ * @param {string} [cwd] 预填的工作区(顶栏 + 用当前会话 cwd,仓库分组 + 用该组 cwd)
1713
+ */
1714
+ function setNewSessionOpen(open, cwd) {
1715
+ const form = $("new-session");
1716
+ const toggle = $("btn-new-session-toggle");
1717
+ form.hidden = !open;
1718
+ toggle.setAttribute("aria-expanded", open ? "true" : "false");
1719
+ if (!open) return;
1720
+ if (cwd) $("new-cwd").value = cwd;
1721
+ else if (!$("new-cwd").value) $("new-cwd").value = store(STORE_KEYS.cwd) ?? state.session?.cwd ?? "";
1722
+ $("new-cwd").focus();
1723
+ }
1724
+
1725
+ /** 顶栏 / 分组 +:展开表单(窄屏先把抽屉拉出来,宽屏折叠态先展开图标栏)。 */
1726
+ function openNewSession(cwd) {
1727
+ if (isWideScreen()) {
1728
+ if (state.sidebarCollapsed) setSidebarCollapsed(false);
1729
+ } else showDrawer();
1730
+ loadSessions().catch(() => {});
1731
+ setNewSessionOpen(true, cwd);
1732
+ // 新会话窗口有自己的草稿副本(F7):按表单里实际生效的 cwd 取键(`n:<cwd>`,空 cwd 也有一份)
1733
+ switchDraft(draftKeyOf(null, $("new-cwd").value.trim()));
1734
+ }
1735
+
1322
1736
  function showLogin(message) {
1323
1737
  $("boot")?.remove();
1324
1738
  $("app").hidden = true;
@@ -1334,6 +1748,9 @@ function showApp() {
1334
1748
  $("boot")?.remove();
1335
1749
  $("login").hidden = true;
1336
1750
  $("app").hidden = false;
1751
+ // 折叠态跨刷新保持:先回放上次的选择,再让 CSS 根据 body class 收缩布局。
1752
+ state.sidebarCollapsed = store(STORE_KEYS.sidebarCollapsed) === "1";
1753
+ applySidebarCollapsed();
1337
1754
  }
1338
1755
 
1339
1756
  async function start() {
@@ -1452,16 +1869,32 @@ async function checkUpdate() {
1452
1869
 
1453
1870
  function wire() {
1454
1871
  $("login-form").addEventListener("submit", login);
1455
- $("btn-drawer").addEventListener("click", openDrawer);
1456
- $("btn-drawer-close").addEventListener("click", closeDrawer);
1872
+ $("btn-drawer").addEventListener("click", toggleSidebar);
1873
+ $("btn-drawer-close").addEventListener("click", () => (isWideScreen() ? setSidebarCollapsed(true) : closeDrawer()));
1874
+ $("btn-new").addEventListener("click", () => openNewSession(state.session?.cwd ?? null));
1875
+ // 折叠态图标栏(56px):与侧栏内同名入口等价,没入口就不存在
1876
+ $("btn-rail-new").addEventListener("click", () => openNewSession(state.session?.cwd ?? null));
1877
+ $("btn-rail-search").addEventListener("click", () => {
1878
+ setSidebarCollapsed(false);
1879
+ $("session-search").focus();
1880
+ });
1881
+ // 图标栏 ⋯ 与顶栏 ⋯ 走同一个定位器:菜单从被点的按钮旁长出(R8-F1)
1882
+ $("btn-rail-more").addEventListener("click", () => toggleMenuAt($("btn-rail-more")));
1883
+ $("btn-rail-expand").addEventListener("click", () => setSidebarCollapsed(false));
1884
+ bindMsgContextMenu();
1885
+ bindAnchoredMenu();
1886
+ // 组头 ⋮ 菜单(与顶栏 ⋯ 同一个 openMenuAt 定位器)
1887
+ $("btn-group-all").addEventListener("click", showAllGroupSessions);
1888
+ $("btn-group-toggle").addEventListener("click", toggleGroupCollapsed);
1889
+ $("error-banner-close").addEventListener("click", hideError);
1890
+ // 跨断点拖窗:顶栏入口要不要让位给图标栏跟着宽度变
1891
+ window.addEventListener("resize", applyTopbarChrome);
1892
+ $("btn-new-session-toggle").addEventListener("click", () => setNewSessionOpen($("new-session").hidden));
1457
1893
  $("scrim").addEventListener("click", closeDrawer);
1458
1894
  // 键盘:Esc 关「更多」菜单 / 窄屏抽屉;Ctrl(⌘)+K 直接跳到会话搜索
1459
1895
  document.addEventListener("keydown", (event) => {
1460
1896
  if (event.key === "Escape") {
1461
- if (!$("menu").hidden) {
1462
- $("menu").hidden = true;
1463
- return;
1464
- }
1897
+ if (closeAnchoredMenu()) return;
1465
1898
  // 宽屏下抽屉是常驻侧栏,不接受 Esc 关闭
1466
1899
  if (!isWideScreen() && !$("drawer").hidden) closeDrawer();
1467
1900
  return;
@@ -1472,6 +1905,12 @@ function wire() {
1472
1905
  const search = $("session-search");
1473
1906
  search.focus();
1474
1907
  search.select();
1908
+ return;
1909
+ }
1910
+ // Ctrl/⌘+B:折叠/展开侧栏(与参考端 DSH 的 sidebar.left.toggle 同一个键位习惯)
1911
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "b") {
1912
+ event.preventDefault();
1913
+ toggleSidebar();
1475
1914
  }
1476
1915
  });
1477
1916
  $("session-search").addEventListener("input", (event) => {
@@ -1491,6 +1930,7 @@ function wire() {
1491
1930
  if (model) body.model = model;
1492
1931
  const data = await api("/v1/sessions", { method: "POST", body });
1493
1932
  store(STORE_KEYS.cwd, check.path);
1933
+ setNewSessionOpen(false);
1494
1934
  await openSession(data.session.id);
1495
1935
  } catch (err) {
1496
1936
  error.textContent = `新建失败:${err.message}`;
@@ -1500,6 +1940,8 @@ function wire() {
1500
1940
  $("prompt").addEventListener("input", () => {
1501
1941
  autosize();
1502
1942
  updateSlash();
1943
+ // 边打边存:切会话/刷新都不丢(F7);隐私模式下 saveDraft 静默失败
1944
+ saveDraft(state.draftKey, $("prompt").value);
1503
1945
  });
1504
1946
  $("prompt").addEventListener("blur", hideSlash);
1505
1947
  $("prompt").addEventListener("keydown", (event) => {
@@ -1558,44 +2000,18 @@ function wire() {
1558
2000
  });
1559
2001
  $("messages").addEventListener("scroll", () => {
1560
2002
  const box = $("messages");
1561
- const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 60;
1562
- state.pinned = atBottom;
1563
- $("btn-jump").hidden = atBottom;
2003
+ // 贴底判定走 compose.isPinned(阈值 32,可 node 单测)。
2004
+ // F8 修复(W-VERIFY):流式 append 会让 scrollHeight 变长而 scrollTop 不动,
2005
+ // 此刻 gap>32 不等于「用户上滑」——只有 scrollTop 真的变小才失跟,否则保持原状态。
2006
+ const top = box.scrollTop;
2007
+ const prev = state.lastScrollTop;
2008
+ if (isPinned(box)) state.pinned = true;
2009
+ else if (top < prev - 2) state.pinned = false;
2010
+ state.lastScrollTop = top;
2011
+ $("btn-jump").hidden = state.pinned;
1564
2012
  });
1565
2013
  $("btn-jump").addEventListener("click", scrollToBottom);
1566
2014
  $("messages").addEventListener("click", async (event) => {
1567
- // 消息操作行(复制/分叉/用量)
1568
- const actBtn = event.target.closest("[data-act]");
1569
- if (actBtn && actBtn.closest(".msg-actions")) {
1570
- const item = state.items.find((it) => it.el === actBtn.closest(".msg"));
1571
- if (!item) return;
1572
- const act = actBtn.dataset.act;
1573
- if (act === "copy") {
1574
- try {
1575
- await navigator.clipboard.writeText(item.text ?? "");
1576
- toast("已复制全文");
1577
- } catch {
1578
- toast("复制失败(浏览器不允许)");
1579
- }
1580
- return;
1581
- }
1582
- if (act === "fork") {
1583
- await forkSession({ item });
1584
- return;
1585
- }
1586
- if (act === "usage") {
1587
- const u = item.usage;
1588
- if (!u) {
1589
- toast("这条回答没有用量数据");
1590
- return;
1591
- }
1592
- const rate = item.durationMs && u.outputTokens
1593
- ? ` · ${(u.outputTokens / (item.durationMs / 1000)).toFixed(1)} tok/s`
1594
- : "";
1595
- toast(`入 ${formatTokens(u.inputTokens)} · 出 ${formatTokens(u.outputTokens)} · 共 ${formatTokens(u.totalTokens)}${rate}`);
1596
- }
1597
- return;
1598
- }
1599
2015
  const copy = event.target.closest("[data-copy]");
1600
2016
  if (!copy) return;
1601
2017
  const code = copy.closest(".code-card")?.querySelector("code");
@@ -1610,20 +2026,25 @@ function wire() {
1610
2026
  toast("复制失败(浏览器不允许)");
1611
2027
  }
1612
2028
  });
1613
- // toggle 不冒泡,但捕获阶段仍会经过祖先:记下用户手动开关过思考块
2029
+ // toggle 不冒泡,但捕获阶段仍会经过祖先:记下用户手动开关过思考块 / 工具卡。
2030
+ // `dataset.auto` 是 setDetailsOpen() 打的标记(程序化改动不算用户意图)。
1614
2031
  $("messages").addEventListener(
1615
2032
  "toggle",
1616
2033
  (event) => {
1617
2034
  const block = event.target;
1618
- if (block?.classList?.contains("thinking-block")) block.dataset.touched = "1";
2035
+ const isFold = block?.classList?.contains("thinking-block") || block?.classList?.contains("tool-card");
2036
+ if (!isFold) return;
2037
+ if (block.dataset.auto === "1") {
2038
+ delete block.dataset.auto;
2039
+ return;
2040
+ }
2041
+ block.dataset.touched = "1";
1619
2042
  },
1620
2043
  true,
1621
2044
  );
1622
- $("btn-menu").addEventListener("click", () => {
1623
- $("menu").hidden = !$("menu").hidden;
1624
- });
2045
+ $("btn-menu").addEventListener("click", () => toggleMenuAt($("btn-menu")));
1625
2046
  $("btn-rename").addEventListener("click", async () => {
1626
- $("menu").hidden = true;
2047
+ closeAnchoredMenu();
1627
2048
  if (!state.sessionId) return;
1628
2049
  const name = window.prompt("会话名称", state.session?.name ?? "");
1629
2050
  if (!name) return;
@@ -1631,33 +2052,33 @@ function wire() {
1631
2052
  await api(`/v1/sessions/${state.sessionId}/name`, { method: "POST", body: { name } });
1632
2053
  $("session-title").textContent = name;
1633
2054
  } catch (err) {
1634
- toast(`重命名失败:${err.message}`);
2055
+ showError(`重命名失败:${err.message}`);
1635
2056
  }
1636
2057
  });
1637
2058
  $("btn-compact").addEventListener("click", async () => {
1638
- $("menu").hidden = true;
2059
+ closeAnchoredMenu();
1639
2060
  if (!state.sessionId) return;
1640
2061
  try {
1641
2062
  await api(`/v1/sessions/${state.sessionId}/compact`, { method: "POST", body: {} });
1642
2063
  toast("已请求压缩");
1643
2064
  } catch (err) {
1644
- toast(`压缩失败:${err.message}`);
2065
+ showError(`压缩失败:${err.message}`);
1645
2066
  }
1646
2067
  });
1647
2068
  $("btn-update").addEventListener("click", async () => {
1648
- $("menu").hidden = true;
2069
+ closeAnchoredMenu();
1649
2070
  await checkUpdate();
1650
2071
  });
1651
2072
  $("btn-fork-clone").addEventListener("click", async () => {
1652
- $("menu").hidden = true;
2073
+ closeAnchoredMenu();
1653
2074
  await forkSession({ clone: true });
1654
2075
  });
1655
2076
  $("btn-export").addEventListener("click", async () => {
1656
- $("menu").hidden = true;
2077
+ closeAnchoredMenu();
1657
2078
  await exportSession();
1658
2079
  });
1659
2080
  $("btn-logout").addEventListener("click", async () => {
1660
- $("menu").hidden = true;
2081
+ closeAnchoredMenu();
1661
2082
  await logout();
1662
2083
  });
1663
2084
  }
@@ -1665,8 +2086,12 @@ function wire() {
1665
2086
  // ---------- 启动 ----------
1666
2087
 
1667
2088
  async function boot() {
2089
+ // 抽屉分组折叠态跨刷新保持(F3):坏数据由 parseCollapsedGroups 吃掉
2090
+ state.collapsedGroups = parseCollapsedGroups(store(STORE_KEYS.collapsedGroups));
1668
2091
  wire();
1669
2092
  autosize();
2093
+ // 首屏草稿(F7):还没开会话时用「上次工作区」的新会话键;记住的会话在 openSession 里换副本
2094
+ switchDraft(draftKeyOf(null, store(STORE_KEYS.cwd) ?? ""));
1670
2095
  // 首帧定屏:两屏在 HTML 里都带 hidden,若等 /v1/web/session 往返结束才显示,
1671
2096
  // 首次访问会先看到一片纯背景色(这就是「第一次进来闪一下」)。
1672
2097
  // 这里同步按上次登录态先画一屏骨架,拿到真实结果再纠正。
@@ -1686,7 +2111,7 @@ async function boot() {
1686
2111
  return;
1687
2112
  }
1688
2113
  markAuthed(false);
1689
- // `pi-hub web-login` 打印的链接带 #code=XXXX-XXXX:直接兑换成 cookie,不要求手输。
2114
+ // `pi-hub web` 打印的链接带 #code=XXXX-XXXX:直接兑换成 cookie,不要求手输。
1690
2115
  const hash = new URLSearchParams(location.hash.replace(/^#/, ""));
1691
2116
  const code = hash.get("code");
1692
2117
  if (code) {