@yanzc/claude-pro 0.12.0 → 0.14.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/src/web/app.js CHANGED
@@ -250,7 +250,16 @@
250
250
  if (item.k === "summary") return `<div class="it it-summary"><details><summary>✻ 对话已压缩(摘要)</summary><div class="md">${md(item.text)}</div></details></div>`;
251
251
  if (item.k === "output") {
252
252
  const lines = trimBlank(item.lines);
253
- return lines.length ? `<div class="it it-output"><pre>${ansiLines(lines)}</pre></div>` : "";
253
+ if (!lines.length) return "";
254
+ // the "✻ Done at …" line under an answer (see App.doneText): a line of its own, the rest as the terminal had it
255
+ let html = "", run = [];
256
+ const flush = () => { const r = trimBlank(run); if (r.length) html += `<pre>${ansiLines(r)}</pre>`; run = []; };
257
+ for (const line of lines) {
258
+ const text = plain(line).trim();
259
+ if (/^✻ Done at \d{1,2}:\d{2}\b/.test(text)) { flush(); html += turnMeta(text); } else run.push(line);
260
+ }
261
+ flush();
262
+ return html ? `<div class="it it-output">${html}</div>` : "";
254
263
  }
255
264
  if (item.k === "tool") {
256
265
  const running = item.status === "running";
@@ -267,6 +276,21 @@
267
276
  return "";
268
277
  }
269
278
 
279
+ // "✻ Done at 17:37 · worked 5m 40s · $0.05 (total $0.10) · ctx 119.1k/1M · opus-5-5 max" as the page shows it
280
+ function turnMeta(text) {
281
+ const [head, ...rest] = text.split(" · ");
282
+ const at = head.replace(/^✻ Done at /, "");
283
+ const parts = rest.map((p) => { // (HTML: every piece of the line escaped)
284
+ let m;
285
+ if ((m = /^worked (.+)$/.exec(p))) return `用时 ${esc(m[1])}`;
286
+ if ((m = /^(\$[\d.,]+) \(total (\$[\d.,]+)\)$/.exec(p))) return `${esc(m[1])}<span class="tm-dim">(累计 ${esc(m[2])})</span>`;
287
+ if ((m = /^ctx (.+)$/.exec(p))) return `上下文 ${esc(m[1])}`;
288
+ return esc(p);
289
+ });
290
+ const check = '<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12.5 4.5 4.5L19 7.5"/></svg>';
291
+ return `<div class="turn-meta" title="${esc(text)}"><span class="tm-done"><span class="tm-check">${check}</span>${esc(at)} 完成</span>${parts.map((p) => `<span>${p}</span>`).join("")}</div>`;
292
+ }
293
+
270
294
  // ---------------------------------------------------------------- images for a message (as pasting one in the terminal)
271
295
 
272
296
  const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
@@ -644,6 +668,12 @@
644
668
  stop: '<svg viewBox="0 0 24 24" width="14" height="14"><rect x="5" y="5" width="14" height="14" rx="2" fill="currentColor"/></svg>',
645
669
  add: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>',
646
670
  caret: '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>',
671
+ chevron: '<svg class="chev" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>',
672
+ terminal: '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 7 5 5-5 5M12 17h7"/></svg>',
673
+ agent: '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/><circle cx="12" cy="12" r="2.5"/></svg>',
674
+ todoOpen: '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="12" cy="12" r="8"/></svg>',
675
+ todoNow: '<svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor"/></svg>',
676
+ todoDone: '<svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><circle cx="12" cy="12" r="9" fill="currentColor"/><path d="m8 12.3 2.8 2.8L16.2 9.6" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
647
677
  more: '<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><circle cx="5" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="19" cy="12" r="1.8"/></svg>',
648
678
  };
649
679
 
@@ -667,7 +697,7 @@
667
697
  }
668
698
 
669
699
  const ws = {
670
- sessions: [], live: [], projectOpen: {}, q: "", loaded: false,
700
+ sessions: [], live: [], projectOpen: {}, workspaces: [], q: "", loaded: false,
671
701
  closed: new Set(JSON.parse(localStorage.getItem("cpWsClosed") || "[]")),
672
702
  expanded: new Set(),
673
703
  tips: new Map(),
@@ -686,6 +716,7 @@
686
716
  const s = await api("/api/sessions");
687
717
  ws.sessions = s.sessions;
688
718
  ws.projectOpen = s.projectOpen || {};
719
+ ws.workspaces = Array.isArray(s.workspaces) ? s.workspaces : [];
689
720
  ws.live = s.live || (await api("/api/live")).sessions;
690
721
  ws.loaded = true;
691
722
  if (!sidebarMenuOpen()) drawWorkspace();
@@ -722,6 +753,13 @@
722
753
  g.last = Math.max(g.last, it.mtime || 0);
723
754
  if (working(it)) g.live = true;
724
755
  }
756
+ // the folders added to the 工作区 (添加工作区): listed before a conversation runs there
757
+ for (const w of ws.workspaces) {
758
+ const key = projectKey(w.cwd);
759
+ if (groups.has(key)) { groups.get(key).added = true; continue; }
760
+ if (q && !w.cwd.toLowerCase().includes(q)) continue;
761
+ groups.set(key, { key, cwd: w.cwd, items: [], last: w.added || 0, live: false, added: true });
762
+ }
725
763
  const list = [...groups.values()].sort((a, b) => b.live - a.live || b.last - a.last || a.key.localeCompare(b.key));
726
764
  const here = location.hash;
727
765
  ws.tips.clear();
@@ -736,10 +774,34 @@
736
774
  const [cls] = it.peer ? liveState(it.peer.status) : [""];
737
775
  const active = here === it.href || (it.alt && here === it.alt);
738
776
  return `<div class="ws-row${it.id ? " has-menu" : ""}" data-tip="${id}"><a class="ws-item${active ? " active" : ""}" href="${esc(it.href)}">${working(it) ? `<span class="ws-dot ${cls}"></span>` : ""}<span class="ws-title">${esc(it.title)}</span>${working(it) ? "" : `<span class="ws-ago">${esc(shortAgo(it.mtime))}</span>`}</a>${it.id ? `<button type="button" class="ws-menu" data-session-menu aria-label="对话操作:${esc(it.title)}" aria-expanded="false">${ICON.more}</button>` : ""}</div>`;
739
- }).join("") + (!closed && g.items.length > limit ? `<button type="button" class="ws-more" data-expand="${esc(g.key)}">展开其余 ${g.items.length - limit} 个</button>` : "");
777
+ }).join("") + (!closed && g.items.length > limit ? `<button type="button" class="ws-more" data-expand="${esc(g.key)}">展开其余 ${g.items.length - limit} 个</button>` : "")
778
+ + (!closed && !g.items.length ? '<div class="ws-hint">还没有会话,点右边的 + 新建</div>' : "");
740
779
  const running = g.items.filter(working).length;
741
780
  return `<div class="ws-group"><div class="ws-folder-row"><button type="button" class="ws-folder" data-folder="${esc(g.key)}" title="${esc(shortPath(g.cwd))}">${closed ? ICON.folder : ICON.folderOpen}<span>${esc(baseName(g.cwd))}</span>${running ? `<span class="ws-count">${running}</span>` : ""}</button><button type="button" class="ws-pmenu" data-pmenu="${esc(g.key)}" data-cwd="${esc(g.cwd)}" title="更多" aria-label="项目菜单" aria-expanded="false">${ICON.more}</button><button type="button" class="ws-add" data-add="${esc(g.cwd)}" title="在 ${esc(baseName(g.cwd))} 里新建会话" aria-label="新建会话">${ICON.add}</button></div>${rows}</div>`;
742
- }).join("") : `<div class="ws-empty">${q ? "没有符合的会话" : "还没有会话"}</div>`;
781
+ }).join("") : `<div class="ws-empty">${q ? "没有符合的会话" : "还没有会话:点上方的文件夹图标添加工作区"}</div>`;
782
+ }
783
+
784
+ // 添加工作区: a folder chosen on the computer claude-pro runs on (the system's folder dialog here, the directory
785
+ // browser from elsewhere), listed in the sidebar and opened there
786
+ async function addWorkspaceDir() {
787
+ const add = async (cwd) => {
788
+ if (!cwd) return;
789
+ try {
790
+ const r = await api("/api/workspaces", { method: "POST", body: { cwd } });
791
+ if (ws.closed.delete(projectKey(r.cwd))) localStorage.setItem("cpWsClosed", JSON.stringify([...ws.closed]));
792
+ // the folder of the next new conversation (the new-conversation page, when shown, starts again with it)
793
+ localStorage.setItem("cpNewDir", r.cwd);
794
+ await loadWorkspace({ afterPending: true });
795
+ if (location.hash === "#/new" || location.hash === "") route();
796
+ toast(`已添加工作区 ${baseName(r.cwd)}`);
797
+ } catch (e) { fail(e); }
798
+ };
799
+ if (!hasNativeFolderPicker) return browseProjectDirectories(null, add);
800
+ const b = $("#wsAddDir");
801
+ b.disabled = true;
802
+ try { await add((await api("/api/projects/pick", { method: "POST", body: {} })).cwd); }
803
+ catch (e) { if (e.status === 409) fail(e); else browseProjectDirectories(null, add); }
804
+ finally { b.disabled = false; }
743
805
  }
744
806
 
745
807
  function markActive() {
@@ -840,9 +902,15 @@
840
902
  if (ws.projectOpen.explorer) items.push({ label: "在资源管理器中打开", value: "explorer" });
841
903
  if (ws.projectOpen.vscode) items.push({ label: "在 VS Code 中打开", value: "vscode" });
842
904
  items.push({ label: ids.length ? `归档全部会话(${ids.length} 个)` : "没有可以归档的会话", description: ids.length ? "从工作区收起,内容保留,可以在「全部会话 → 已归档」里找回" : "运行中的会话不能归档", value: "all" });
905
+ const pinned = ws.workspaces.find((w) => projectKey(w.cwd) === key);
906
+ if (pinned) items.push({ label: "从工作区移除", description: "只是不再固定显示,目录和会话都不动", value: "unpin" });
843
907
  popMenu(pm, [{ key: "p", title: "", items }], async (_, value) => {
844
908
  try {
845
- if (value === "all") {
909
+ if (value === "unpin") {
910
+ await api("/api/workspaces/remove", { method: "POST", body: { cwd: pinned.cwd } });
911
+ await loadWorkspace({ afterPending: true });
912
+ toast(`已从工作区移除 ${baseName(pinned.cwd)}`);
913
+ } else if (value === "all") {
846
914
  if (ids.length && confirm(`归档这个项目的 ${ids.length} 个会话?`)) await archive(ids);
847
915
  } else {
848
916
  await api("/api/projects/open", { method: "POST", body: { cwd: pm.dataset.cwd, target: value } });
@@ -893,6 +961,7 @@
893
961
  });
894
962
  $("#wsSearch").addEventListener("input", (e) => { ws.q = e.target.value.trim(); drawWorkspace(); });
895
963
  $("#wsRefresh").addEventListener("click", () => loadWorkspace());
964
+ $("#wsAddDir").addEventListener("click", () => addWorkspaceDir().catch(fail));
896
965
  }
897
966
 
898
967
  // ---------------------------------------------------------------- the message box (new conversation and live)
@@ -992,7 +1061,7 @@
992
1061
  if (wasOpen) return;
993
1062
  const pop = document.createElement("div");
994
1063
  pop.className = "pop";
995
- pop.innerHTML = sections.map((s) => `<div class="pop-head">${esc(s.title)}</div>${s.items.map((it, i) => `<button type="button" data-s="${esc(s.key)}" data-i="${i}" class="${it.current ? "current" : ""}${it.danger ? " danger" : ""}"><span>${esc(it.label)}</span>${it.description ? `<small>${esc(it.description)}</small>` : ""}</button>`).join("")}`).join("");
1064
+ pop.innerHTML = sections.map((s) => `<div class="pop-head">${esc(s.title)}</div>${s.items.map((it, i) => `<button type="button" data-s="${esc(s.key)}" data-i="${i}" class="${it.current ? "current" : ""}${it.danger ? " danger" : ""}"><span>${esc(it.label)}${it.isDefault ? ' <span class="pill accent pop-default">默认</span>' : ""}</span>${it.description ? `<small>${esc(it.description)}</small>` : ""}</button>`).join("")}`).join("");
996
1065
  document.body.appendChild(pop);
997
1066
  const r = anchor.getBoundingClientRect();
998
1067
  pop.style.left = `${Math.max(8, Math.min(window.innerWidth - pop.offsetWidth - 8, r.right - pop.offsetWidth))}px`;
@@ -1026,6 +1095,9 @@
1026
1095
  });
1027
1096
  }
1028
1097
 
1098
+ // Clicking the tagged model follows the project default rather than creating a model override.
1099
+ const modelMenuItems = (models = []) => models.filter((m) => m.value !== "default").map((m) => ({ ...m, value: m.isDefault ? "default" : m.value }));
1100
+
1029
1101
  // ---------------------------------------------------------------- 新会话
1030
1102
 
1031
1103
  let hasNativeFolderPicker = false;
@@ -1061,7 +1133,7 @@
1061
1133
  }
1062
1134
 
1063
1135
  async function newView() {
1064
- const el = page(`<div class="chat-page"><div class="welcome"><div class="welcome-logo">c</div><h1>你好,今天要做什么?</h1><p class="muted">选一个项目目录,告诉它要做什么:你在这里看着它工作、随时给它发消息。</p></div><div class="chat-composer" id="ncomp"></div></div>`, "chat");
1136
+ const el = page(`<div class="chat-page"><div class="welcome"><img class="welcome-logo" src="/favicon.svg" alt="" width="56" height="56"><h1>你好,今天要做什么?</h1><p class="muted">选一个项目目录,告诉它要做什么:你在这里看着它工作、随时给它发消息。</p></div><div class="chat-composer" id="ncomp"></div></div>`, "chat");
1065
1137
  let projects = [];
1066
1138
  try { projects = (await api("/api/projects")).projects; } catch { /* the folder chooser still works */ }
1067
1139
  if (!el.isConnected) return;
@@ -1103,8 +1175,8 @@
1103
1175
  const info = await options(kind);
1104
1176
  if (!el.isConnected || dir !== currentDir) return;
1105
1177
  const isModel = kind === "models";
1106
- const current = isModel ? info.modelChoice : info.effortChoice;
1107
- const items = info[kind].map((item) => ({ ...item, label: item.value === "default" ? "项目默认" : item.label, current: item.value === current }));
1178
+ const items = isModel ? modelMenuItems(info.models) : (info.efforts || []).map((item) => ({ ...item, label: item.value === "default" ? "项目默认" : item.label, current: item.value === info.effortChoice }));
1179
+ if (!items.length) return toast(isModel ? "没有可选的模型" : "这个模型不能调推理强度");
1108
1180
  popMenu(anchor, [{ key: kind, title: isModel ? "模型" : "思考强度", items }], (_, value) => {
1109
1181
  if (isModel) { if (model !== value) effort = undefined; model = value; }
1110
1182
  else effort = value;
@@ -1165,7 +1237,7 @@
1165
1237
  const el = page(`<div class="chat-page">
1166
1238
  <header class="chat-head"><div class="chat-titles"><h2 id="ltitle">连接中…</h2><div class="chat-sub" id="lsub"></div></div><span id="lconn" class="pill warn" hidden></span><button type="button" class="icon-btn" id="lmenu" title="更多">${ICON.more}</button></header>
1167
1239
  <div class="chat-scroll" id="lscroll"><div class="chat-log" id="log"></div></div>
1168
- <div class="chat-foot"><div class="chat-extra"><div class="todos" id="ltodos"></div><div class="queue" id="lqueue"></div><div id="ldialog"></div></div>
1240
+ <div class="chat-foot"><div class="chat-extra"><div class="bgwork" id="lbg"></div><div class="todos" id="ltodos"></div><div class="queue" id="lqueue"></div><div id="ldialog"></div></div>
1169
1241
  <div class="status-line" id="lstatus"></div><div class="chat-composer" id="lcomp"></div><div class="chat-stats" id="lstats"></div></div>
1170
1242
  </div>`, "chat");
1171
1243
  const log = $("#log", el);
@@ -1196,7 +1268,8 @@
1196
1268
  const anchor = e.currentTarget;
1197
1269
  let o;
1198
1270
  try { o = await post("options"); } catch (err) { return fail(err); }
1199
- const items = (o[list] || []).map((m) => ({ label: m.label || m.value, description: m.description || "", value: m.value, current: m.current }));
1271
+ if (!el.isConnected) return;
1272
+ const items = key === "model" ? modelMenuItems(o.models) : (o[list] || []);
1200
1273
  if (!items.length) return toast(key === "effort" ? "这个模型不能调推理强度" : "没有可选的模型");
1201
1274
  popMenu(anchor, [{ key, title, items }], (k, value) => post("send", { text: `/${k} ${value}` }).catch(fail));
1202
1275
  };
@@ -1268,8 +1341,29 @@
1268
1341
  html = `<span class="work">${frames[Math.floor(Date.now() / 120) % frames.length]} ${esc(s.verb || "Working")}…</span> <span class="muted">(${parts.join(" · ")})</span>`;
1269
1342
  }
1270
1343
  $("#lstatus", el).innerHTML = html;
1344
+ for (const t of $$("#lbg [data-since]", el)) t.textContent = fmtDuration(Math.max(0, Date.now() - Number(t.dataset.since)));
1271
1345
  c.setBusy(busy);
1272
1346
  }
1347
+ // what runs in the background for the session (its background agents, its run_in_background commands)
1348
+ function renderBackground(list) {
1349
+ const box = $("#lbg", el);
1350
+ const open = $("details", box)?.open ?? true;
1351
+ box.innerHTML = list.length ? `<details class="side-card"${open ? " open" : ""}><summary><span class="pulse"></span>后台运行<span class="card-count">${list.length}</span>${ICON.chevron}</summary><div class="card-list">${list.map((b) => {
1352
+ const agent = b.kind === "agent";
1353
+ const tip = b.command && b.command !== b.label ? b.command : b.label;
1354
+ const since = Number(b.since) > 0 ? Number(b.since) : 0;
1355
+ return `<div class="bg-row${agent ? " agent" : ""}" title="${esc(tip)}"><span class="bg-icon" title="${agent ? "后台 agent" : "后台命令"}">${agent ? ICON.agent : ICON.terminal}</span><span class="bg-label">${esc(b.label)}</span><span class="bg-id">${esc(b.id)}</span>${since ? `<span class="bg-time" data-since="${since}">${fmtDuration(Math.max(0, Date.now() - since))}</span>` : ""}</div>`;
1356
+ }).join("")}</div></details>` : "";
1357
+ }
1358
+ function renderTodos(todos) {
1359
+ const box = $("#ltodos", el);
1360
+ const open = $("details", box)?.open ?? true;
1361
+ const done = todos.filter((t) => t.status === "completed").length;
1362
+ box.innerHTML = todos.length ? `<details class="side-card"${open ? " open" : ""}><summary>待办<span class="card-count">${done}/${todos.length}</span><span class="todo-bar"><i style="width:${Math.round((done / todos.length) * 100)}%"></i></span>${ICON.chevron}</summary><div class="card-list">${todos.map((t) => {
1363
+ const state = t.status === "completed" ? "done" : t.status === "in_progress" ? "now" : "";
1364
+ return `<div class="todo-row ${state}"><span class="todo-icon">${state === "done" ? ICON.todoDone : state === "now" ? ICON.todoNow : ICON.todoOpen}</span><span>${esc(t.content)}</span></div>`;
1365
+ }).join("")}</div></details>` : "";
1366
+ }
1273
1367
  function setStatus(next) {
1274
1368
  status = next || {};
1275
1369
  statusAt = Date.now();
@@ -1281,11 +1375,11 @@
1281
1375
  const stats = [];
1282
1376
  if (status.context?.window) stats.push(`上下文 ${fmtTokens(status.context.used || 0)} / ${fmtTokens(status.context.window)}(${Math.round(((status.context.used || 0) / status.context.window) * 100)}%)`);
1283
1377
  if (Number.isFinite(status.cost)) stats.push(`花费 ${fmtUsd(status.cost)}`);
1284
- if (status.tasks) stats.push(`${status.tasks} 个后台 agent`);
1378
+ if (status.tasks && !Array.isArray(status.background)) stats.push(`${status.tasks} 个后台 agent`); // (a session of an older version)
1285
1379
  $("#lstats", el).textContent = stats.join(" · ");
1286
- const todos = Array.isArray(status.todos) ? status.todos : [];
1287
- $("#ltodos", el).innerHTML = todos.length ? `<details open><summary class="muted">待办 ${todos.filter((t) => t.status === "completed").length}/${todos.length}</summary>${todos.map((t) => `<div class="${t.status === "completed" ? "done" : t.status === "in_progress" ? "now" : ""}">${t.status === "completed" ? "☒" : t.status === "in_progress" ? "◼" : "☐"} ${esc(t.content)}</div>`).join("")}</details>` : "";
1288
- $("#lqueue", el).innerHTML = (status.queue || []).map((q) => `<div>⎿ 排队中:${esc(String(q).replace(/\s+/g, " ").slice(0, 200))}</div>`).join("");
1380
+ renderBackground(Array.isArray(status.background) ? status.background : []);
1381
+ renderTodos(Array.isArray(status.todos) ? status.todos : []);
1382
+ $("#lqueue", el).innerHTML = (status.queue || []).map((q) => `<div class="queue-row"><span class="queue-tag">排队中</span><span>${esc(String(q).replace(/\s+/g, " ").slice(0, 200))}</span></div>`).join("");
1289
1383
  renderDialog(status.dialog);
1290
1384
  renderStatus();
1291
1385
  }
@@ -1360,16 +1454,31 @@
1360
1454
  // ---------------------------------------------------------------- 远程访问
1361
1455
 
1362
1456
  async function remotePage() {
1363
- const el = page('<h1>远程访问</h1><p class="sub">在手机或别的电脑上,通过 https://&lt;你的通讯号&gt;.7bit.fun 打开这台电脑的控制台,要输入密码</p><div id="body"><div class="empty">正在加载…</div></div>');
1457
+ const el = page('<h1>远程访问</h1><p class="sub">在手机或别的电脑上,通过你自己的域名(https://&lt;前缀&gt;.7bit.fun)打开这台电脑的控制台,要输入密码</p><div id="body"><div class="empty">正在加载…</div></div>');
1364
1458
  let v;
1365
1459
  try { v = await api("/api/remote"); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
1366
- drawRemote(el, v);
1367
- const timer = setInterval(async () => { try { const next = await api("/api/remote"); if (JSON.stringify(next.tunnel) !== JSON.stringify(v.tunnel)) { v = next; drawRemote(el, v); } } catch { /* next time */ } }, 3000);
1460
+ // the address's prefix (the account's 通讯号 at the gateway), asked once
1461
+ const h = v.gateway ? await api("/api/remote/handle").catch((e) => ({ error: e.message })) : null;
1462
+ if (!el.isConnected) return;
1463
+ drawRemote(el, v, h);
1464
+ const timer = setInterval(async () => { try { const next = await api("/api/remote"); if (JSON.stringify(next.tunnel) !== JSON.stringify(v.tunnel)) { v = next; drawRemote(el, v, h); } } catch { /* next time */ } }, 3000);
1368
1465
  cleanup = () => clearInterval(timer);
1369
1466
  }
1370
1467
 
1371
- function drawRemote(el, v) {
1468
+ const HANDLE_RULE = /^[a-z][a-z0-9-]{1,18}[a-z0-9]$/;
1469
+ const HANDLE_HINT = "3–20 个小写字母、数字或 -,字母开头、不以 - 结尾";
1470
+
1471
+ function drawRemote(el, v, h) {
1472
+ // without 7bit.fun there is no address: only the way to connect it
1473
+ if (!v.gateway) {
1474
+ $("#body", el).innerHTML = `<div class="panel panel-pad"><div style="font-weight:650;margin-bottom:6px">远程访问需要 7bit.fun 网关</div><p class="muted" style="margin:0 0 14px;font-size:13px">访问地址 https://&lt;前缀&gt;.7bit.fun 由网关提供:连接 7bit.fun 后,就能在这里选一个自己的域名前缀并开启。</p><button class="button" id="rConnectGw">去连接 7bit.fun</button></div>`;
1475
+ $("#rConnectGw", el).addEventListener("click", () => { sessionStorage.setItem("cpOpenAdd", "1"); location.hash = "#/providers"; });
1476
+ return;
1477
+ }
1372
1478
  const t = v.tunnel || {};
1479
+ const domain = h?.domain || "7bit.fun";
1480
+ const prefixField = (id) => `<label class="field" style="margin:0">域名前缀<small>${HANDLE_HINT};要唯一,它也是你在网关的通讯号(联系人用它找到你)</small>
1481
+ <span class="prefix-row"><span class="mono muted">https://</span><input id="${id}" class="mono" maxlength="20" autocomplete="off" spellcheck="false" placeholder="例如 yanzc" value="${h && !h.auto ? esc(h.handle) : ""}"><span class="mono muted">.${esc(domain)}</span></span></label>`;
1373
1482
  const state = !v.enabled ? ["off", "已关闭"] : t.status === "online" ? ["ok", "已开启"] : t.status === "error" ? ["off", "没有接上"] : ["warn", "正在连接"];
1374
1483
  const device = (ua) => { const s = String(ua || ""); return /iPhone|iPad/.test(s) ? "iPhone / iPad" : /Android/.test(s) ? "Android" : /Windows/.test(s) ? "Windows" : /Mac OS/.test(s) ? "Mac" : s.slice(0, 40) || "未知设备"; };
1375
1484
  $("#body", el).innerHTML = `
@@ -1377,25 +1486,67 @@
1377
1486
  <div><div class="muted" style="font-size:12.5px">状态</div><div style="font-size:18px;font-weight:650;margin-top:2px"><span class="pill ${state[0]}">${state[1]}</span>
1378
1487
  ${t.status === "online" && t.host ? ` <a href="https://${esc(t.host)}" target="_blank" rel="noopener" class="mono" style="font-size:15px">https://${esc(t.host)}</a>` : ""}</div>
1379
1488
  ${t.error ? `<div style="color:var(--danger);font-size:13px;margin-top:4px">${esc(t.error)}</div>` : ""}
1380
- ${!v.gateway ? '<div class="muted" style="font-size:13px;margin-top:4px">远程访问通过 7bit.fun 网关:先在「模型与供应商」里连接 7bit.fun。</div>' : ""}</div>
1381
- <div class="actions">${v.enabled ? '<button class="button danger" id="rOff">关闭远程访问</button>' : `<button class="button" id="rOn" ${v.hasPassword && v.gateway ? "" : "disabled"}>开启远程访问</button>`}</div></div>
1382
- <p class="muted" style="font-size:12.5px;margin:12px 0 0">地址用的是你在网关的通讯号(在网关网页「通讯录」里改)。开启后这台电脑的控制台服务常驻后台;电脑休眠或关机时打不开,claude-pro 的任何会话启动时会重新接上。</p></div>
1489
+ ${h?.error ? `<div style="color:var(--danger);font-size:13px;margin-top:4px">读不到域名前缀:${esc(h.error)}</div>` : ""}</div>
1490
+ <div class="actions">${v.enabled ? `<button class="button secondary" id="rRename">修改前缀</button><button class="button danger" id="rOff">关闭远程访问</button>` : ""}</div></div>
1491
+ ${v.enabled ? "" : `<div class="remote-setup">${prefixField("rHandle")}<div class="actions"><button class="button" id="rOn" ${v.hasPassword ? "" : "disabled"}>开启远程访问</button>${v.hasPassword ? "" : '<span class="muted" style="font-size:12.5px">先在下面设一个密码</span>'}<span class="modal-error" id="rErr"></span></div></div>`}
1492
+ <p class="muted" style="font-size:12.5px;margin:12px 0 0">开启后这台电脑的控制台服务常驻后台;电脑休眠或关机时打不开,claude-pro 的任何会话启动时会重新接上。</p></div>
1383
1493
  <div class="section-head"><div><h2>密码</h2><p>${v.hasPassword ? "已设置。改密码会让所有已登录的设备退出。" : `还没有设置:开启前先设一个(至少 ${v.minPassword} 位)。`}</p></div></div>
1384
1494
  <form class="panel panel-pad actions" id="rPwForm"><input type="password" id="rPw1" placeholder="新密码" autocomplete="new-password" style="flex:1;min-width:180px"><input type="password" id="rPw2" placeholder="再输一次" autocomplete="new-password" style="flex:1;min-width:180px"><button class="button" type="submit">${v.hasPassword ? "修改密码" : "设置密码"}</button></form>
1385
1495
  <div class="section-head"><div><h2>已登录的设备</h2><p>${v.sessions.length} 台</p></div>${v.sessions.length ? '<button class="button danger small" id="rLogoutAll">全部退出</button>' : ""}</div>
1386
1496
  <div class="panel">${v.sessions.length ? `<table class="list"><tbody>${v.sessions.map((s) => `<tr><td>${esc(device(s.ua))}</td><td class="mono">${esc(s.ip || "")}</td><td>最近 ${esc(ago(s.lastSeen))}</td><td class="num muted">${s.remember ? "记住 30 天" : "1 天"}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">没有</div>'}</div>
1387
1497
  <div class="section-head"><h2>最近的登录</h2></div>
1388
1498
  <div class="panel">${v.logins.length ? `<table class="list"><tbody>${v.logins.map((l) => `<tr><td>${l.ok ? '<span class="pill ok">成功</span>' : '<span class="pill off">密码错误</span>'}</td><td>${esc(device(l.ua))}</td><td class="mono">${esc(l.ip || "")}</td><td class="num">${esc(fmtTime(l.at))}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">还没有人登录过</div>'}</div>`;
1389
- const post = async (body, done) => { try { drawRemote(el, await api("/api/remote", { method: "POST", body })); if (done) toast(done); } catch (e) { fail(e); } };
1390
- $("#rOn", el)?.addEventListener("click", () => post({ enabled: true }, "远程访问已开启,正在连接网关…"));
1391
- $("#rOff", el)?.addEventListener("click", () => { if (confirm("关闭远程访问?外网就打不开这台电脑的控制台了。")) post({ enabled: false }, "远程访问已关闭"); });
1392
- $("#rLogoutAll", el)?.addEventListener("click", () => { if (confirm("让所有已登录的设备退出?")) post({ logoutAll: true }, "都已退出"); });
1499
+ const post = async (body, done) => {
1500
+ const next = await api("/api/remote", { method: "POST", body });
1501
+ if (body.handle && h) Object.assign(h, { handle: body.handle, auto: false, error: null });
1502
+ drawRemote(el, next, h);
1503
+ if (done) toast(done);
1504
+ };
1505
+ // the prefix typed, checked here as the gateway will: none needed when the user chose one before
1506
+ const typedHandle = (input, err) => {
1507
+ const value = input.value.trim().toLowerCase();
1508
+ if (!value && h && !h.auto) return h.handle;
1509
+ if (!value) { err("先填一个域名前缀"); input.focus(); return null; }
1510
+ if (!HANDLE_RULE.test(value)) { err(`域名前缀要是 ${HANDLE_HINT}`); input.focus(); return null; }
1511
+ return value;
1512
+ };
1513
+ $("#rOn", el)?.addEventListener("click", async (e) => {
1514
+ const b = e.currentTarget, errBox = $("#rErr", el), err = (m) => { errBox.textContent = m; };
1515
+ err("");
1516
+ const handle = typedHandle($("#rHandle", el), err);
1517
+ if (!handle) return;
1518
+ b.disabled = true;
1519
+ try { await post({ ...(handle !== h?.handle ? { handle } : {}), enabled: true }, `远程访问已开启:https://${handle}.${domain},正在连接网关…`); }
1520
+ catch (ex) { err(ex.message); b.disabled = false; }
1521
+ });
1522
+ $("#rHandle", el)?.addEventListener("keydown", (e) => { if (e.key === "Enter") $("#rOn", el)?.click(); });
1523
+ $("#rRename", el)?.addEventListener("click", () => {
1524
+ const m = modal({
1525
+ title: "修改域名前缀", sub: `现在是 https://${h?.handle || "…"}.${domain};改后旧地址就打不开了`,
1526
+ body: prefixField("rNewHandle"),
1527
+ foot: '<span class="modal-error"></span><button class="button secondary" data-close>取消</button><button class="button" id="rSaveHandle">保存</button>',
1528
+ });
1529
+ const input = $("#rNewHandle", m.el);
1530
+ input.focus(); input.select();
1531
+ const save = async () => {
1532
+ const err = (msg) => { $(".modal-error", m.el).textContent = msg; };
1533
+ err("");
1534
+ const handle = typedHandle(input, err);
1535
+ if (!handle) return;
1536
+ if (handle === h?.handle) return m.close();
1537
+ try { await post({ handle }, `已改为 https://${handle}.${domain},正在重新连接…`); m.close(); } catch (ex) { err(ex.message); }
1538
+ };
1539
+ $("#rSaveHandle", m.el).addEventListener("click", save);
1540
+ input.addEventListener("keydown", (e) => { if (e.key === "Enter") save(); });
1541
+ });
1542
+ $("#rOff", el)?.addEventListener("click", () => { if (confirm("关闭远程访问?外网就打不开这台电脑的控制台了。")) post({ enabled: false }, "远程访问已关闭").catch(fail); });
1543
+ $("#rLogoutAll", el)?.addEventListener("click", () => { if (confirm("让所有已登录的设备退出?")) post({ logoutAll: true }, "都已退出").catch(fail); });
1393
1544
  $("#rPwForm", el).addEventListener("submit", (e) => {
1394
1545
  e.preventDefault();
1395
1546
  const a = $("#rPw1", el).value, b = $("#rPw2", el).value;
1396
1547
  if (a.length < v.minPassword) return toast(`密码至少 ${v.minPassword} 位`, "error");
1397
1548
  if (a !== b) return toast("两次输入不一样", "error");
1398
- post({ password: a }, "密码已保存,所有已登录的设备都已退出");
1549
+ post({ password: a }, "密码已保存,所有已登录的设备都已退出").catch(fail);
1399
1550
  });
1400
1551
  }
1401
1552
 
@@ -1408,83 +1559,266 @@
1408
1559
  drawProviders(el, p);
1409
1560
  }
1410
1561
 
1562
+ let modelTab = null; // the provider whose tab 模型列表 shows (kept across redraws; a provider just connected gets it)
1411
1563
  function drawProviders(el, p) {
1412
- const card = (x) => `<div class="panel prov${x.connected ? " connected" : ""}"><div class="prov-top"><strong>${esc(x.name)}</strong>${x.connected ? '<span class="pill ok">已连接</span>' : ""}</div>
1413
- <div class="meta">${esc(x.protocol === "openai" ? "OpenAI 协议" : "Anthropic 协议")} · ${esc(x.baseUrl)}</div>
1414
- ${x.connected ? `<div class="meta">Key ${esc(x.key || "(无需)")} · ${x.models.length} 个模型${x.model ? ` · 选的是 ${esc(x.model)}` : ""}</div>` : ""}
1415
- <div class="actions">${x.connected ? `<button class="button secondary small" data-connect="${esc(x.id)}">更换 Key / 模型</button><button class="button danger small" data-remove="${esc(x.id)}">断开</button>` : `<button class="button small" data-connect="${esc(x.id)}">连接</button>`}${x.keyPage ? `<a class="button secondary small" href="${esc(x.keyPage)}" target="_blank" rel="noopener">获取 Key</a>` : ""}</div></div>`;
1416
- const connected = [...p.presets, ...p.custom].filter((x) => x.connected);
1417
1564
  $("#body", el).innerHTML = `<div id="pbody">
1418
- <div class="section-head"><div><h2>默认模型</h2><p>新会话用的模型和推理强度。会话里的 /model、/effort 只改那一个会话(并记住给下次用)</p></div></div>
1419
- <div class="panel panel-pad" id="defaults"><div class="muted">正在读取可用模型…</div></div>
1420
- <div class="section-head"><div><h2>7bit.fun 网关</h2><p>Claude、GPT 等模型,余额、远程控制、跨电脑和通讯录都通过它</p></div></div>
1421
- <div class="panel prov${p.gateway.connected ? " connected" : ""}" style="max-width:640px"><div class="prov-top"><strong>7bit.fun</strong>${p.gateway.connected ? '<span class="pill ok">已连接</span>' : ""}</div>
1422
- <div class="meta">${esc(p.gateway.url)}${p.gateway.connected ? ` · Key ${esc(p.gateway.key)}${p.gateway.account?.email ? ` · ${esc(p.gateway.account.email)}` : ""}` : ""}</div>
1423
- <form class="actions" id="gwForm"><input type="password" id="gwKey" placeholder="${p.gateway.connected ? "粘贴新 Key 来更换" : "粘贴 7bit.fun 的 API Key"}" style="flex:1;min-width:240px" autocomplete="off"><button class="button small" type="submit">${p.gateway.connected ? "更换" : "连接"}</button>${p.gateway.connected ? '<button class="button danger small" type="button" id="gwOut">断开</button>' : ""}<a class="button secondary small" href="${esc(p.gateway.keyPage)}" target="_blank" rel="noopener">获取 Key</a></form></div>
1424
- <div class="section-head"><div><h2>模型供应商</h2><p>${connected.length} 个已连接。Key 保存在 ~/.claude-pro/providers.json,页面上只显示开头和结尾</p></div><button class="button secondary small" id="addCustom">添加自定义供应商</button></div>
1425
- <div class="prov-grid">${[...p.presets.filter((x) => x.connected), ...p.custom, ...p.presets.filter((x) => !x.connected)].map(card).join("")}</div></div>`;
1426
- loadDefaults(el, p);
1427
- $("#gwForm", el).addEventListener("submit", async (e) => {
1428
- e.preventDefault();
1429
- const apiKey = $("#gwKey", el).value.trim();
1430
- if (!apiKey) return toast("请先粘贴 Key", "error");
1431
- try { drawProviders(el, await api("/api/gateway", { method: "POST", body: { apiKey } })); toast("已连接 7bit.fun"); } catch (err) { fail(err); }
1565
+ <div class="section-head"><div><h2>默认设置</h2><p>新会话用的模型和思考强度,选了就保存。会话里的 /model、/effort 只改那一个会话(并记住给下次用);已经开着的会话要 /model default 或重启才换</p></div></div>
1566
+ <div class="panel" id="defaults"><div class="panel-pad muted">正在读取…</div></div>
1567
+ <div class="section-head"><div><h2>模型列表</h2><p>勾选的模型出现在会话的模型菜单里,也是「默认模型」的选项(都不勾就列出全部)。列表只在点「刷新模型列表」时更新</p></div><div class="actions head-actions"><input type="search" id="modelFilter" placeholder="搜索模型…" style="width:180px"><button class="button secondary small" id="refreshModels" title="重新向 7bit.fun 和各供应商拉取模型列表">刷新模型列表</button><button class="button small" id="addProvider" title="连接 7bit.fun、DeepSeek、Kimi、OpenRouter 等供应商,或你自己的兼容接口">添加供应商</button></div></div>
1568
+ <div id="modelLists"><div class="panel panel-pad muted">正在读取…</div></div></div>`;
1569
+ loadModelLists(el, p);
1570
+ // 添加供应商: any built-in provider or 7bit.fun (one connected already: another account of it), or one of the
1571
+ // user's own
1572
+ $("#addProvider", el).addEventListener("click", (e) => {
1573
+ const others = (base) => p.custom.filter((c) => c.preset === base && c.connected).length;
1574
+ const again = "已连接 · 再添加一个账号";
1575
+ popMenu(e.currentTarget, [
1576
+ { key: "preset", title: "选择供应商", items: [
1577
+ { label: "7bit.fun", description: p.gateway.connected ? again : `${p.gateway.url} · Claude、GPT 等模型`, value: "7bit" },
1578
+ ...p.presets.map((x) => ({ label: x.providerName || x.name, description: x.connected ? again : x.baseUrl, value: x.id })),
1579
+ ] },
1580
+ { key: "custom", title: "", items: [{ label: "自定义供应商…", description: "任何兼容 Anthropic 或 OpenAI 的接口", value: "" }] },
1581
+ ], (key, value) => {
1582
+ if (key === "custom") return connectDialog(el, null);
1583
+ if (value === "7bit") {
1584
+ if (!p.gateway.connected) return gatewayDialog(el, p);
1585
+ return connectDialog(el, null, { instanceOf: "7bit", template: { name: "7bit.fun", baseUrl: p.gateway.url }, count: 1 + others("7bit") });
1586
+ }
1587
+ const x = p.presets.find((y) => y.id === value);
1588
+ if (!x) return;
1589
+ if (!x.connected) return connectDialog(el, x);
1590
+ connectDialog(el, null, { instanceOf: x.id, template: { name: x.providerName || x.name, baseUrl: x.baseUrl, keyless: x.keyless }, count: 1 + others(x.id) });
1591
+ }, { dropdown: true });
1432
1592
  });
1433
- $("#gwOut", el)?.addEventListener("click", async () => {
1434
- if (!confirm("断开 7bit.fun?这台电脑的会话会下线,网关上的模型也不能用了。")) return;
1435
- try { drawProviders(el, await api("/api/gateway", { method: "DELETE" })); toast("已断开"); } catch (err) { fail(err); }
1593
+ // (from the first-run notice: the menu opens by itself)
1594
+ if (sessionStorage.getItem("cpOpenAdd")) { sessionStorage.removeItem("cpOpenAdd"); setTimeout(() => { if (el.isConnected) $("#addProvider", el)?.click(); }, 60); }
1595
+ $("#refreshModels", el).addEventListener("click", async (e) => {
1596
+ const b = e.currentTarget;
1597
+ b.disabled = true;
1598
+ b.textContent = "正在刷新…";
1599
+ try {
1600
+ const r = await api("/api/models/refresh", { method: "POST", body: {} });
1601
+ const parts = [...(r.gateway ? [{ name: "7bit.fun", ...r.gateway }] : []), ...r.providers];
1602
+ const ok = parts.filter((x) => !x.error).map((x) => `${x.name} ${x.count} 个`);
1603
+ const bad = parts.filter((x) => x.error).map((x) => `${x.name}(${x.error})`);
1604
+ if (!parts.length) toast("还没有连接任何供应商", "error");
1605
+ else toast([ok.length ? `已刷新:${ok.join(",")}` : "", bad.length ? `失败:${bad.join(",")}` : ""].filter(Boolean).join(";"), bad.length && !ok.length ? "error" : "ok");
1606
+ if (el.isConnected) drawProviders(el, r.view);
1607
+ } catch (err) { fail(err); b.disabled = false; b.textContent = "刷新模型列表"; }
1436
1608
  });
1437
- $("#addCustom", el).addEventListener("click", () => connectDialog(el, null));
1438
- $("#pbody", el).addEventListener("click", async (e) => {
1439
- const c = e.target.closest("[data-connect]"), r = e.target.closest("[data-remove]");
1440
- if (c) connectDialog(el, [...p.presets, ...p.custom].find((x) => x.id === c.dataset.connect));
1441
- if (r && confirm(`断开 ${r.dataset.remove}?保存的 Key 会删除。`)) {
1442
- try { drawProviders(el, await api(`/api/providers/${encodeURIComponent(r.dataset.remove)}`, { method: "DELETE" })); toast("已断开"); } catch (err) { fail(err); }
1609
+ }
1610
+
1611
+ // 模型列表: the kept lists, a tab per provider (nothing is asked of the providers here: see 刷新模型列表); each
1612
+ // tab says how its provider is connected, with 更换 Key / 模型 and 断开.
1613
+ async function loadModelLists(el, p) {
1614
+ const box = $("#modelLists", el);
1615
+ let r;
1616
+ try { r = await api("/api/models/kept"); } catch (e) {
1617
+ box.innerHTML = `<div class="panel panel-pad muted">读取失败:${esc(e.message)}</div>`;
1618
+ $("#defaults", el).innerHTML = `<div class="panel-pad muted">读取失败:${esc(e.message)}</div>`;
1619
+ return;
1620
+ }
1621
+ if (!el.isConnected) return;
1622
+ const current = r.remembered?.model || r.current;
1623
+ const picked = new Set(r.picked || []);
1624
+ const price = (m) => (m.price ? `$${m.price.input} / $${m.price.output}` : "—");
1625
+ const pickedNote = () => (picked.size ? `菜单显示勾选的 ${picked.size} 个` : "菜单显示全部");
1626
+ const providerOf = (id) => [...(p?.presets || []), ...(p?.custom || [])].find((x) => x.id === id);
1627
+ if (!r.groups.some((g) => g.id === modelTab)) modelTab = r.groups[0]?.id || null;
1628
+ const head = (g) => {
1629
+ const x = providerOf(g.id);
1630
+ const when = `${g.models.length} 个模型${g.at ? ` · ${esc(ago(g.at))}更新` : ""}`;
1631
+ if (g.id === "7bit" && p?.gateway) {
1632
+ // (the balance comes after: GET /api/gateway/account)
1633
+ return `<div class="mg-head"><div class="meta">${esc(p.gateway.url)} · Key ${esc(p.gateway.key)}<span id="gwAccount">${p.gateway.account?.email ? ` · ${esc(p.gateway.account.email)}` : ""}</span> · 余额 <strong id="gwBalance">…</strong> · ${when}</div>
1634
+ <div class="actions"><button class="button secondary small" data-gateway="change">更换 Key</button><button class="button danger small" data-gateway="remove">断开</button><a class="button secondary small" href="${esc(p.gateway.keyPage)}" target="_blank" rel="noopener">获取 Key</a></div></div>`;
1443
1635
  }
1636
+ if (!x) return `<div class="mg-head"><div class="meta">${when}</div></div>`;
1637
+ return `<div class="mg-head"><div class="meta">${esc(x.protocol === "openai" ? "OpenAI 协议" : "Anthropic 协议")} · ${esc(x.baseUrl)} · Key ${esc(x.key || "(无需)")} · ${when}</div>
1638
+ <div class="actions"><button class="button secondary small" data-connect="${esc(x.id)}">更换 Key / 模型</button><button class="button danger small" data-remove="${esc(x.id)}">断开</button>${x.keyPage ? `<a class="button secondary small" href="${esc(x.keyPage)}" target="_blank" rel="noopener">获取 Key</a>` : ""}</div></div>`;
1639
+ };
1640
+ box.innerHTML = r.groups.length ? `<div class="mtabs" role="tablist">${r.groups.map((g) => `<button type="button" role="tab" data-tab="${esc(g.id)}" aria-selected="${g.id === modelTab}" class="${g.id === modelTab ? "active" : ""}">${esc(g.name)}<span class="count">${g.models.length}</span></button>`).join("")}</div>` + r.groups.map((g) => `<div class="panel model-group" role="tabpanel" data-group="${esc(g.id)}"${g.id === modelTab ? "" : " hidden"}>
1641
+ ${head(g)}<div class="empty no-match" hidden>这个供应商里没有匹配的模型</div>
1642
+ ${g.models.length ? `<table class="list"><thead><tr><th class="pick" title="勾选的模型出现在会话的模型菜单里">菜单</th><th>模型</th><th class="num">上下文</th><th class="num">最大输出</th><th>推理强度</th><th class="num" title="每百万 token 的美元价:输入 / 输出">价格(输入/输出)</th></tr></thead><tbody>
1643
+ ${g.models.map((m) => `<tr class="click" data-model="${esc(m.ref)}" data-text="${esc([m.ref, m.name, m.vendor].filter(Boolean).join(" ").toLowerCase())}"><td class="pick"><input type="checkbox" data-pick="${esc(m.ref)}" aria-label="在会话的模型菜单里显示 ${esc(m.ref)}"${picked.has(m.ref) ? " checked" : ""}></td><td class="title-cell"><strong class="mono">${esc(m.ref)}${m.ref === current ? ' <span class="pill ok def-pill">默认</span>' : ""}</strong>${m.name || m.vendor ? `<div class="path">${esc([m.name, m.vendor].filter(Boolean).join(" · "))}</div>` : ""}</td><td class="num">${m.window ? fmtTokens(m.window) : "—"}</td><td class="num">${m.maxOutput ? fmtTokens(m.maxOutput) : "—"}</td><td>${m.efforts.length ? esc(m.efforts.join(" · ")) : '<span class="faint">—</span>'}</td><td class="num">${price(m)}</td></tr>`).join("")}
1644
+ </tbody></table>` : '<div class="empty">还没有拉取过模型列表:点「刷新模型列表」</div>'}</div>`).join("") : '<div class="panel panel-pad muted">还没有连接供应商:点「添加供应商」</div>';
1645
+ if (r.groups.length) box.insertAdjacentHTML("afterbegin", `<div class="pick-bar"><span id="pickedNote">${pickedNote()}</span><button type="button" class="button secondary small" id="clearPicked"${picked.size ? "" : " hidden"}>清除勾选</button></div>`);
1646
+ // 默认设置: the default model, among the models ticked below (all when none is), and the default effort; each
1647
+ // saved when chosen (settings.json), and what a session's /model or /effort remembered of it forgotten
1648
+ let defModel = r.remembered?.model || r.current;
1649
+ let defEffort = p?.remembered?.effort || p?.effort || "auto";
1650
+ let remembered = { model: r.remembered?.model || null, effort: p?.remembered?.effort || null };
1651
+ const allModels = r.groups.flatMap((g) => g.models.map((m) => ({ ref: m.ref, group: g.name, name: m.name })));
1652
+ const paintDefaults = () => {
1653
+ const dbox = $("#defaults", el);
1654
+ if (!dbox) return;
1655
+ const choices = picked.size ? allModels.filter((m) => picked.has(m.ref)) : allModels;
1656
+ const groups = [...new Set(choices.map((m) => m.group))];
1657
+ const listed = choices.some((m) => m.ref === defModel);
1658
+ const efforts = ["auto", "low", "medium", "high", "xhigh", "max"];
1659
+ dbox.innerHTML = `<div class="def-row"><div class="def-label"><strong>默认模型</strong><small>选项是下面「模型列表」里勾选的模型${picked.size ? `(${picked.size} 个)` : "(没勾选:列出全部)"}</small></div>
1660
+ <div><select id="defModel">${listed || !defModel ? "" : `<option value="${esc(defModel)}" selected>${esc(defModel)}(当前)</option>`}${groups.map((gname) => `<optgroup label="${esc(gname)}">${choices.filter((m) => m.group === gname).map((m) => `<option value="${esc(m.ref)}"${m.ref === defModel ? " selected" : ""}>${esc(m.ref)}${m.name ? ` · ${esc(m.name)}` : ""}</option>`).join("")}</optgroup>`).join("")}</select>
1661
+ ${remembered.model ? `<div class="def-note">现在生效的是会话里 /model 记住的选择;在这里选一次就以这里为准</div>` : ""}</div></div>
1662
+ <div class="def-row"><div class="def-label"><strong>思考强度</strong><small>auto 用模型自己的默认;不支持的模型会取最接近的一档</small></div>
1663
+ <div><select id="defEffort">${efforts.map((x) => `<option${x === defEffort ? " selected" : ""}>${x}</option>`).join("")}${efforts.includes(defEffort) ? "" : `<option selected>${esc(defEffort)}</option>`}</select>
1664
+ ${remembered.effort ? `<div class="def-note">现在生效的是会话里 /effort 记住的选择;在这里选一次就以这里为准</div>` : ""}</div></div>`;
1665
+ $("#defModel", dbox).onchange = async (e) => {
1666
+ const value = e.target.value;
1667
+ try {
1668
+ await api("/api/settings", { method: "POST", body: { scope: "user", key: "model", value } });
1669
+ if (remembered.model) await api("/api/remembered", { method: "POST", body: { model: null } });
1670
+ defModel = value;
1671
+ remembered.model = null;
1672
+ for (const pill of $$(".def-pill", box)) pill.remove();
1673
+ $(`tr[data-model="${CSS.escape(value)}"] .title-cell strong`, box)?.insertAdjacentHTML("beforeend", ' <span class="pill ok def-pill">默认</span>');
1674
+ toast(`默认模型已改为 ${value}`);
1675
+ } catch (err) { fail(err); }
1676
+ paintDefaults();
1677
+ };
1678
+ $("#defEffort", dbox).onchange = async (e) => {
1679
+ const value = e.target.value;
1680
+ try {
1681
+ await api("/api/settings", { method: "POST", body: { scope: "user", key: "effort", value } });
1682
+ if (remembered.effort) await api("/api/remembered", { method: "POST", body: { effort: null } });
1683
+ defEffort = value;
1684
+ remembered.effort = null;
1685
+ toast(`默认思考强度已改为 ${value}`);
1686
+ } catch (err) { fail(err); }
1687
+ paintDefaults();
1688
+ };
1689
+ };
1690
+ paintDefaults();
1691
+ let saving = Promise.resolve();
1692
+ const savePicked = () => {
1693
+ const models = [...picked];
1694
+ $("#pickedNote", box).textContent = pickedNote();
1695
+ $("#clearPicked", box).hidden = !picked.size;
1696
+ paintDefaults(); // (its choices are the ticked models)
1697
+ saving = saving.then(() => api("/api/models/picked", { method: "POST", body: { models } })).catch((e) => fail(e));
1698
+ };
1699
+ box.onchange = (e) => {
1700
+ const cb = e.target.closest("input[data-pick]");
1701
+ if (!cb) return;
1702
+ if (cb.checked) picked.add(cb.dataset.pick); else picked.delete(cb.dataset.pick);
1703
+ savePicked();
1704
+ };
1705
+ $("#clearPicked", box)?.addEventListener("click", () => {
1706
+ picked.clear();
1707
+ for (const cb of $$("input[data-pick]", box)) cb.checked = false;
1708
+ savePicked();
1709
+ toast("已清除勾选:会话的模型菜单显示全部模型");
1444
1710
  });
1711
+ if ($("#gwBalance", box)) {
1712
+ api("/api/gateway/account").then((a) => {
1713
+ const b = $("#gwBalance", box);
1714
+ if (!b) return;
1715
+ b.textContent = a.balance != null ? fmtUsd(a.balance) : "—";
1716
+ if (a.error) b.title = `查询失败:${a.error}`;
1717
+ if (a.email && !$("#gwAccount", box).textContent) $("#gwAccount", box).textContent = ` · ${a.email}`;
1718
+ }).catch(() => { const b = $("#gwBalance", box); if (b) b.textContent = "—"; });
1719
+ }
1720
+ const filter = $("#modelFilter", el);
1721
+ // searching: every tab says how many of its models match; the tab shown lists them
1722
+ const apply = () => {
1723
+ const q = filter.value.trim().toLowerCase();
1724
+ for (const g of $$(".model-group", box)) {
1725
+ const rows = $$("tr[data-model]", g);
1726
+ let shown = 0;
1727
+ for (const tr of rows) { const hit = !q || tr.dataset.text.includes(q); tr.hidden = !hit; shown += hit; }
1728
+ $(".no-match", g).hidden = !q || !rows.length || shown > 0;
1729
+ const tab = $(`[data-tab="${CSS.escape(g.dataset.group)}"] .count`, box);
1730
+ if (tab) tab.textContent = q ? `${shown}/${rows.length}` : rows.length;
1731
+ }
1732
+ };
1733
+ const show = (id) => {
1734
+ modelTab = id;
1735
+ for (const t of $$("[data-tab]", box)) { const on = t.dataset.tab === id; t.classList.toggle("active", on); t.setAttribute("aria-selected", String(on)); }
1736
+ for (const g of $$(".model-group", box)) g.hidden = g.dataset.group !== id;
1737
+ };
1738
+ filter.oninput = apply;
1739
+ apply();
1740
+ box.onclick = async (e) => {
1741
+ const tab = e.target.closest("[data-tab]");
1742
+ if (tab) return show(tab.dataset.tab);
1743
+ const gw = e.target.closest("[data-gateway]");
1744
+ if (gw?.dataset.gateway === "change") return gatewayDialog(el, p);
1745
+ if (gw?.dataset.gateway === "remove") {
1746
+ if (!confirm("断开 7bit.fun?保存的 Key 会删除:它的模型不能用了,这台电脑的会话也会下线(远程访问、跨电脑互发任务靠它)。")) return;
1747
+ try { drawProviders(el, await api("/api/gateway", { method: "DELETE" })); toast("已断开 7bit.fun"); } catch (err) { fail(err); }
1748
+ return;
1749
+ }
1750
+ const c = e.target.closest("[data-connect]"), rm = e.target.closest("[data-remove]");
1751
+ if (c) return connectDialog(el, providerOf(c.dataset.connect));
1752
+ if (rm) {
1753
+ const x = providerOf(rm.dataset.remove);
1754
+ if (!confirm(`断开 ${x?.name || rm.dataset.remove}?保存的 Key 会删除,它的模型也从列表里去掉。`)) return;
1755
+ try { drawProviders(el, await api(`/api/providers/${encodeURIComponent(rm.dataset.remove)}`, { method: "DELETE" })); toast("已断开"); } catch (err) { fail(err); }
1756
+ return;
1757
+ }
1758
+ if (e.target.closest(".pick")) return; // (the checkbox itself)
1759
+ // a click on the row ticks (or unticks) the model
1760
+ const cb = e.target.closest("tr[data-model]")?.querySelector("input[data-pick]");
1761
+ if (!cb) return;
1762
+ cb.checked = !cb.checked;
1763
+ cb.dispatchEvent(new Event("change", { bubbles: true }));
1764
+ };
1445
1765
  }
1446
1766
 
1447
- async function loadDefaults(el, p) {
1448
- const box = $("#defaults", el);
1449
- let m;
1450
- try { m = await api("/api/models"); } catch (e) { box.innerHTML = `<div class="muted">读取失败:${esc(e.message)}</div>`; return; }
1451
- const current = m.remembered?.model || m.current;
1452
- const efforts = ["auto", "low", "medium", "high", "xhigh", "max"];
1453
- const currentEffort = p.remembered?.effort || p.effort;
1454
- box.innerHTML = `<div class="actions" style="align-items:flex-end">
1455
- <label class="field" style="flex:2;min-width:260px;margin:0">模型<input list="modelList" id="defModel" value="${esc(current)}" placeholder="provider/model,或 opus、sonnet"><datalist id="modelList">${m.models.map((x) => `<option value="${esc(x.ref)}">${esc(x.provider)}${x.window ? ` · ${fmtTokens(x.window)} 上下文` : ""}</option>`).join("")}</datalist></label>
1456
- <label class="field" style="min-width:140px;margin:0">推理强度<select id="defEffort">${efforts.map((x) => `<option${x === currentEffort ? " selected" : ""}>${x}</option>`).join("")}${efforts.includes(currentEffort) ? "" : `<option selected>${esc(currentEffort)}</option>`}</select></label>
1457
- <button class="button" id="saveDefaults">保存为默认</button></div>
1458
- <p class="muted" style="font-size:12.5px;margin:10px 0 0">${m.remembered?.model || m.remembered?.effort ? `现在生效的是会话里 /model、/effort 记住的选择(${esc([m.remembered.model, m.remembered.effort].filter(Boolean).join(" · "))})。保存后会写入设置的 model / effort,并清掉记住的选择。` : "保存到 ~/.claude-pro/settings.json 的 model / effort。"}已经开着的会话要 /model default 或重启才换。</p>`;
1459
- $("#saveDefaults", box).addEventListener("click", async () => {
1460
- const model = $("#defModel", box).value.trim();
1461
- const effort = $("#defEffort", box).value;
1462
- try {
1463
- if (model) await api("/api/settings", { method: "POST", body: { scope: "user", key: "model", value: model } });
1464
- await api("/api/settings", { method: "POST", body: { scope: "user", key: "effort", value: effort } });
1465
- await api("/api/remembered", { method: "POST", body: { model: null, effort: null } });
1466
- toast("已保存默认模型");
1467
- providers();
1468
- } catch (e) { fail(e); }
1767
+ // Connect 7bit.fun, or change its key: the gateway checks the key (its account), and its model list comes with it.
1768
+ function gatewayDialog(el, p) {
1769
+ const again = p.gateway.connected;
1770
+ const m = modal({
1771
+ title: again ? `${p.gateway.name || "7bit.fun"}:名称与 Key` : "连接 7bit.fun", sub: p.gateway.url,
1772
+ body: `<label class="field">名称<small>显示在 tab 里</small><input id="gName" maxlength="40" value="${esc(p.gateway.name || "7bit.fun")}"></label>
1773
+ <label class="field">API Key<small>${again ? "留空则继续用已保存的 Key;" : ""}在网关网页「API 密钥」里创建</small><input type="password" id="gKey" autocomplete="off" placeholder="${again ? "留空:用已保存的" : "粘贴 7bit.fun 的 API Key"}"></label>
1774
+ <a class="button secondary small" href="${esc(p.gateway.keyPage)}" target="_blank" rel="noopener">获取 Key</a>`,
1775
+ foot: `<span class="modal-error"></span><button class="button secondary" data-close>取消</button><button class="button" id="gConnect">${again ? "保存" : "连接"}</button>`,
1469
1776
  });
1777
+ const input = $("#gKey", m.el);
1778
+ (again ? $("#gName", m.el) : input).focus();
1779
+ const go = async () => {
1780
+ const apiKey = input.value.trim();
1781
+ const name = $("#gName", m.el).value.trim();
1782
+ const err = $(".modal-error", m.el);
1783
+ if (!apiKey && !again) { err.textContent = "请先粘贴 Key"; return; }
1784
+ const b = $("#gConnect", m.el);
1785
+ b.disabled = true;
1786
+ b.textContent = "正在验证…";
1787
+ err.textContent = "";
1788
+ try {
1789
+ const view = await api("/api/gateway", { method: "POST", body: { ...(apiKey ? { apiKey } : {}), name } });
1790
+ m.close();
1791
+ toast(again ? "已保存" : `已连接 ${name || "7bit.fun"}`);
1792
+ modelTab = "7bit";
1793
+ drawProviders(el, view);
1794
+ } catch (ex) { err.textContent = ex.message; b.disabled = false; b.textContent = again ? "保存" : "连接"; }
1795
+ };
1796
+ $("#gConnect", m.el).addEventListener("click", go);
1797
+ for (const i of [input, $("#gName", m.el)]) i.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); });
1470
1798
  }
1471
1799
 
1472
- // Connect a provider (a built-in one, or with x = null one of the user's own): key → models → test → saved.
1473
- function connectDialog(el, x) {
1474
- const custom = !x;
1800
+ // Connect a provider: a built-in one (x; connected already: its key, model or name changed), another account of one
1801
+ // or of 7bit.fun (instanceOf, with its template and how many are connected), or with neither one of the user's own.
1802
+ // 名称 → key → models → test → saved.
1803
+ function connectDialog(el, x, { instanceOf = null, template = null, count = 0 } = {}) {
1804
+ const custom = !x && !instanceOf;
1805
+ const base = x || template;
1806
+ const defaultName = x ? x.name : instanceOf ? `${template.name} ${count + 1}` : "";
1475
1807
  const m = modal({
1476
- title: custom ? "添加自定义供应商" : `连接 ${x.name}`, sub: custom ? "任何兼容 Anthropic Messages 或 OpenAI Chat Completions 的接口" : `${x.baseUrl}`,
1477
- body: `${custom ? `<label class="field">名字<small>模型名会是 名字/模型,比如 myrelay/gpt-5</small><input id="cName" placeholder="myrelay"></label>
1478
- <label class="field">协议<select id="cProto"><option value="openai">OpenAI 兼容(/chat/completions)</option><option value="anthropic">Anthropic 兼容(/v1/messages)</option></select></label>
1808
+ title: custom ? "添加自定义供应商" : x ? (x.connected ? `${x.name}:名称、Key 与模型` : `连接 ${x.name}`) : `再添加一个 ${template.name} 账号`,
1809
+ sub: custom ? "任何兼容 Anthropic Messages 或 OpenAI Chat Completions 的接口" : `${base.baseUrl}`,
1810
+ body: `<label class="field">名称<small>${custom ? "显示在 tab 和模型菜单里;英文名同时是模型前缀,比如 myrelay/gpt-5" : "显示在 tab 和模型菜单里"}</small><input id="cName" maxlength="40" value="${esc(defaultName)}" placeholder="${custom ? "myrelay" : esc(base.name)}"></label>
1811
+ ${custom ? `<label class="field">协议<select id="cProto"><option value="openai">OpenAI 兼容(/chat/completions)</option><option value="anthropic">Anthropic 兼容(/v1/messages)</option></select></label>
1479
1812
  <label class="field">地址<input id="cUrl" placeholder="https://api.example.com/v1"></label>` : ""}
1480
- <label class="field">API Key${x?.connected ? "<small>留空则继续用已保存的 Key</small>" : x?.keyless ? "<small>这个供应商不需要 Key</small>" : ""}<input type="password" id="cKey" autocomplete="off" placeholder="${x?.connected ? "留空:用已保存的" : "粘贴 Key"}"></label>
1813
+ <label class="field">API Key${x?.connected ? "<small>留空则继续用已保存的 Key</small>" : base?.keyless ? "<small>这个供应商不需要 Key</small>" : ""}<input type="password" id="cKey" autocomplete="off" placeholder="${x?.connected ? "留空:用已保存的" : "粘贴 Key"}"></label>
1481
1814
  <div class="actions"><button class="button secondary" id="cCheck">检查 Key 并列出模型</button></div>
1482
1815
  <div id="cModels" style="margin-top:14px"></div>`,
1483
1816
  foot: '<span class="modal-error"></span><button class="button secondary" data-close>取消</button><button class="button" id="cConnect" disabled>测试并连接</button>',
1484
1817
  });
1485
1818
  let checked = null;
1486
1819
  const err = (t) => { $(".modal-error", m.el).textContent = t || ""; };
1487
- const target = () => (custom ? { custom: { name: $("#cName", m.el).value, protocol: $("#cProto", m.el).value, baseUrl: $("#cUrl", m.el).value } } : { id: x.id });
1820
+ const target = () => (custom ? { custom: { name: $("#cName", m.el).value, protocol: $("#cProto", m.el).value, baseUrl: $("#cUrl", m.el).value } } : instanceOf ? { instanceOf } : { id: x.id });
1821
+ (x?.connected ? $("#cName", m.el) : custom ? $("#cName", m.el) : $("#cKey", m.el)).focus();
1488
1822
  $("#cCheck", m.el).addEventListener("click", async (e) => {
1489
1823
  err("");
1490
1824
  e.target.disabled = true;
@@ -1509,9 +1843,10 @@
1509
1843
  e.target.disabled = true;
1510
1844
  e.target.textContent = `正在测试 ${model}…`;
1511
1845
  try {
1512
- const p = await api("/api/providers/connect", { method: "POST", body: { ...target(), apiKey: $("#cKey", m.el).value, model, models: list.length ? list : [{ id: model }], authHeader: checked?.authHeader, useNow: $("#cUse", m.el)?.checked } });
1846
+ const p = await api("/api/providers/connect", { method: "POST", body: { ...target(), name: $("#cName", m.el).value, apiKey: $("#cKey", m.el).value, model, models: list.length ? list : [{ id: model }], authHeader: checked?.authHeader, useNow: $("#cUse", m.el)?.checked } });
1513
1847
  m.close();
1514
1848
  toast(`已连接,模型 ${model} 测试通过`);
1849
+ modelTab = p.connected || modelTab; // (its tab is the one shown)
1515
1850
  drawProviders(el, p);
1516
1851
  } catch (ex) { err(ex.message); e.target.disabled = false; e.target.textContent = "测试并连接"; }
1517
1852
  });
@@ -1636,35 +1971,99 @@
1636
1971
 
1637
1972
  async function extensions() {
1638
1973
  const project = sessionStorage.getItem("extProject") || "";
1639
- const el = page(`<h1>扩展</h1><p class="sub">技能、子 agent、自定义命令、MCP 服务器和 hooks。新会话会加载改动</p>
1974
+ const el = page(`<h1>扩展</h1><p class="sub">内置工具、技能、子 agent、MCP 和 hooks。新会话会加载改动</p>
1640
1975
  <div class="toolbar"><span class="muted" style="font-size:13px">项目:</span>${await projectsSelect("proj", project)}</div><div id="body"><div class="empty">正在加载…</div></div>`);
1641
1976
  $("#proj", el).addEventListener("change", (e) => { sessionStorage.setItem("extProject", e.target.value); extensions(); });
1642
1977
  let x;
1643
1978
  try { x = await api(`/api/extensions${project ? `?project=${encodeURIComponent(project)}` : ""}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
1644
1979
  const scopePill = (s) => `<span class="pill${s === "built-in" ? "" : s === "user" ? " accent" : " ok"}">${{ "built-in": "内置", user: "用户", project: "项目" }[s] || esc(s)}</span>`;
1645
- const list = (items, kind) => items.length ? items.map((i) => `<div class="file-row"><span class="name">${esc(kind === "command" ? `/${i.name}` : i.name)}</span>${scopePill(i.scope)}<span class="desc" title="${esc(i.description)}">${esc(i.description)}</span>${i.path ? `<button class="button secondary small" data-edit="${esc(i.path)}">编辑</button>` : ""}</div>`).join("") : '<div class="file-row"><span class="desc">还没有</span></div>';
1646
- const newBtn = (kind, label) => `<button class="button secondary small" data-new="${kind}">新建${label}</button>`;
1980
+ const list = (items, kind) => items.length ? items.map((i) => `<div class="file-row"><span class="name">${esc(i.name)}</span>${scopePill(i.scope)}<span class="desc" title="${esc(i.description)}">${esc(i.description)}</span>${i.path ? `<button class="button secondary small" data-edit="${esc(i.path)}">编辑</button>` : ""}</div>`).join("") : '<div class="file-row"><span class="desc">还没有</span></div>';
1981
+ // 新建: a new conversation with the request written for the model (it knows the formats and asks what is missing)
1982
+ const aiBtn = (kind) => `<button class="button secondary small" data-ai="${kind}" title="打开新会话,写好要求交给模型去做">${ICON.agent}让 AI 新建</button>`;
1983
+ // 内置工具: what every request gives the model, in a line each (the whole description on hover)
1984
+ const tools = x.tools || [];
1985
+ const toolRows = tools.map((t) => {
1986
+ const first = (t.description.split(/\n/).find((l) => l.trim()) || "").replace(/^[-\s]+/, "").split(/(?<=\.)\s/)[0];
1987
+ return `<div class="file-row"><span class="name">${esc(t.name)}</span><span class="desc" title="${esc(t.description.slice(0, 1200))}">${esc(TOOL_ZH[t.name] || first)}</span></div>`;
1988
+ }).join("");
1647
1989
  $("#body", el).innerHTML = `
1648
- <div class="section-head"><div><h2>技能</h2><p>skills/&lt;名字&gt;/SKILL.md:模型按描述决定何时加载</p></div>${newBtn("skill", "技能")}</div><div class="panel">${list(x.skills, "skill")}</div>
1649
- <div class="section-head"><div><h2>子 agent</h2><p>agents/*.md:Task 工具可以把任务交给它们</p></div>${newBtn("agent", "子 agent")}</div><div class="panel">${list(x.agents, "agent")}</div>
1650
- <div class="section-head"><div><h2>自定义命令</h2><p>commands/*.md:在会话里输入 /名字</p></div>${newBtn("command", "命令")}</div><div class="panel">${list(x.commands, "command")}</div>
1651
- <div class="section-head"><div><h2>MCP 服务器</h2><p>环境变量和请求头的值不会显示(保持 ••• 就是不改)</p></div><button class="button secondary small" id="addMcp">添加 MCP 服务器</button></div>
1652
- <div class="panel">${x.mcp.length ? x.mcp.map((s, i) => `<div class="file-row"><span class="name">${esc(s.name)}</span><span class="pill">${esc(s.scope)}</span><span class="desc mono">${esc(s.spec?.url || [s.spec?.command, ...(s.spec?.args || [])].filter(Boolean).join(" "))}</span>${s.scope === "user" || s.scope === ".mcp.json" ? `<button class="button secondary small" data-mcp="${i}">编辑</button>` : `<button class="button secondary small" data-edit="${esc(s.file)}">编辑文件</button>`}</div>`).join("") : '<div class="file-row"><span class="desc">没有配置 MCP 服务器</span></div>'}</div>
1990
+ <div class="section-head"><div><h2>内置工具<span class="card-count" style="margin-left:8px;vertical-align:2px">${tools.length + (x.selfRestart ? 1 : 0)}</span></h2><p>每次请求都会发给模型、由模型决定何时调用的工具,写在程序里(不是 MCP)。鼠标停在说明上可以看到发给模型的原文</p></div></div>
1991
+ <div class="panel">${toolRows || '<div class="file-row"><span class="desc">读不到工具清单</span></div>'}${x.selfRestart ? `<div class="file-row"><span class="name">Restart</span><span class="desc">${esc(TOOL_ZH.Restart)}</span></div>` : ""}
1992
+ <div class="file-row"><span class="desc">另外:配置了 MCP 服务器时,它们的工具会以 mcp__服务器名__工具名 加进这个清单;子 agent 用的是它定义里 tools 列出的那些。</span></div></div>
1993
+ <div class="section-head"><div><h2>技能</h2><p>skills/&lt;名字&gt;/SKILL.md:模型按描述决定何时用 Skill 工具加载</p></div>${aiBtn("skill")}</div><div class="panel">${list(x.skills, "skill")}</div>
1994
+ <div class="section-head"><div><h2>子 agent</h2><p>agents/*.md:Task 工具可以把任务交给它们</p></div>${aiBtn("agent")}</div><div class="panel">${list(x.agents, "agent")}</div>
1995
+ <div class="section-head"><div><h2>MCP</h2><p>别的工具要装 MCP 才有的常用能力,这里已经内置,不用安装;也可以接入外部 MCP 服务器,它们的工具会加进上面的清单</p></div>${aiBtn("mcp")}</div>
1996
+ <div class="panel">${BUILTIN_MCP.filter((b) => tools.some((t) => t.name === b.tool)).map((b) => `<div class="file-row"><span class="name" style="font-family:inherit;font-weight:600">${esc(b.name)}</span><span class="pill">内置</span><span class="desc" title="${esc(b.tools)}">${esc(b.desc)}${b.like ? `<span class="faint"> · 相当于 ${esc(b.like)}</span>` : ""}</span></div>`).join("")}
1997
+ <div class="file-row mcp-sub"><span class="desc"><strong>外部 MCP 服务器</strong> · 环境变量和请求头的值不会显示</span></div>
1998
+ ${x.mcp.length ? x.mcp.map((s, i) => `<div class="file-row"><span class="name">${esc(s.name)}</span><span class="pill">${esc(s.scope)}</span><span class="desc mono">${esc(s.spec?.url || [s.spec?.command, ...(s.spec?.args || [])].filter(Boolean).join(" "))}</span>${s.scope === "user" || s.scope === ".mcp.json" ? `<button class="button secondary small" data-mcp="${i}">编辑</button>` : `<button class="button secondary small" data-edit="${esc(s.file)}">编辑文件</button>`}</div>`).join("") : '<div class="file-row"><span class="desc">还没有添加外部 MCP 服务器</span></div>'}</div>
1653
1999
  <div class="section-head"><div><h2>Hooks</h2><p>在工具调用前后、提交消息时等运行的命令,写在设置文件的 hooks 里</p></div></div>
1654
2000
  <div class="panel">${x.hooks.length ? x.hooks.map((h) => `<div class="file-row"><span class="name">${esc(h.event)}</span><span class="pill">${esc(h.scope)}</span><span class="desc mono">${esc(JSON.stringify(h.entries))}</span><button class="button secondary small" data-edit="${esc(h.file)}">编辑文件</button></div>`).join("") : `<div class="file-row"><span class="desc">没有 hooks。要添加,编辑设置文件的 "hooks" 字段</span><button class="button secondary small" data-edit="${esc(x.settingsFiles.user)}">编辑用户设置文件</button></div>`}</div>`;
1655
2001
  $("#body", el).addEventListener("click", async (e) => {
1656
- const ed = e.target.closest("[data-edit]"), nw = e.target.closest("[data-new]"), mc = e.target.closest("[data-mcp]");
2002
+ const ed = e.target.closest("[data-edit]"), ai = e.target.closest("[data-ai]"), mc = e.target.closest("[data-mcp]");
1657
2003
  if (ed) openEditor(ed.dataset.edit, { title: "编辑", deletable: !/\.json$/i.test(ed.dataset.edit), onSaved: extensions });
1658
- if (nw) {
1659
- const kind = nw.dataset.new;
1660
- const name = prompt(`新${{ skill: "技能", agent: "子 agent", command: "命令" }[kind]}的名字(字母、数字、_ . -)`);
1661
- if (!name) return;
1662
- const scope = project && confirm(`放在项目 ${project} 里吗?\n确定:项目级(.claude-pro/) 取消:用户级(所有项目)`) ? "project" : "user";
1663
- try { const r = await api("/api/extensions", { method: "POST", body: { kind, scope, name, project } }); openEditor(r.path, { title: "编辑", onSaved: extensions }); } catch (err) { fail(err); }
1664
- }
2004
+ if (ai) askModelToCreate(ai.dataset.ai, { project, settingsFile: x.settingsFiles?.user || "" });
1665
2005
  if (mc) mcpDialog(x, x.mcp[Number(mc.dataset.mcp)], project);
1666
2006
  });
1667
- $("#addMcp", el).addEventListener("click", () => mcpDialog(x, null, project));
2007
+ }
2008
+
2009
+ // The built-in tools in a few Chinese words (扩展's 内置工具; what the model reads is their English description)
2010
+ const TOOL_ZH = {
2011
+ Task: "把复杂的多步任务交给子 agent,可以在后台运行",
2012
+ Skill: "加载一个技能(下面「技能」里写好的做事说明)",
2013
+ TaskOutput: "查看后台 agent 的状态和结果",
2014
+ TaskStop: "停止一个后台 agent",
2015
+ Bash: "运行终端命令(git、npm、构建、测试等),可以放到后台",
2016
+ BashOutput: "读取后台命令的输出",
2017
+ KillShell: "结束一个后台命令",
2018
+ REPL: "在常驻的 Python / Node.js 进程里运行代码,变量和数据保留到下次",
2019
+ Processes: "列出本机进程(端口、命令行),或结束进程",
2020
+ Glob: "按文件名模式找文件",
2021
+ Grep: "按内容搜索文件(ripgrep)",
2022
+ Read: "读取文件,也能看图片和 notebook",
2023
+ Edit: "在文件里精确替换一段文字",
2024
+ MultiEdit: "一次在同一个文件里做多处替换",
2025
+ Write: "写入文件(新建或整个覆盖)",
2026
+ NotebookEdit: "编辑 Jupyter notebook 的单元格",
2027
+ WebFetch: "抓取网页,按要求提取内容",
2028
+ WebSearch: "联网搜索",
2029
+ Browser: "操作真实的浏览器:打开网页、点击、输入、截图",
2030
+ TodoWrite: "维护当前任务的待办清单(就是对话下方的「待办」)",
2031
+ AskUserQuestion: "向你提问、让你在几个选项里选",
2032
+ Effort: "遇到难题时调高自己本次的思考强度",
2033
+ ListPeers: "列出其他 claude-pro 会话(本机、你的其他电脑、联系人)",
2034
+ MessagePeer: "给其他会话发任务或问题,答复自动发回",
2035
+ Restart: "改了 claude-pro 自身代码后重启加载(只有源码版有)",
2036
+ };
2037
+
2038
+ // What other agents get from MCP servers and claude-pro has built in (扩展's MCP section): shown while its tool is
2039
+ // there (Browser can be turned off).
2040
+ const BUILTIN_MCP = [
2041
+ { tool: "Browser", tools: "Browser", name: "浏览器", desc: "打开网页、点击、输入、截图,可以用你已登录的浏览器", like: "Playwright / Chrome DevTools MCP" },
2042
+ { tool: "WebSearch", tools: "WebSearch", name: "联网搜索", desc: "搜索并汇总结果,附来源", like: "Brave / Tavily 等搜索 MCP" },
2043
+ { tool: "WebFetch", tools: "WebFetch", name: "抓取网页", desc: "读取网页正文,按要求提取内容", like: "Fetch MCP" },
2044
+ { tool: "Read", tools: "Read · Write · Edit · MultiEdit · Glob · Grep", name: "文件系统", desc: "读写、修改、搜索本机文件", like: "Filesystem MCP" },
2045
+ { tool: "REPL", tools: "REPL", name: "代码执行", desc: "常驻的 Python / Node.js 进程,处理数据、跑脚本", like: "代码执行类 MCP" },
2046
+ { tool: "Processes", tools: "Processes", name: "进程管理", desc: "查看进程和占用的端口,结束进程", like: "系统 / 进程类 MCP" },
2047
+ { tool: "MessagePeer", tools: "ListPeers · MessagePeer", name: "多会话协作", desc: "和本机、你的其他电脑、联系人的 claude-pro 会话互发任务", like: "" },
2048
+ ];
2049
+
2050
+ // 让 AI 新建: the new conversation's box with the request (where the file goes, its format), the project's directory
2051
+ // chosen when the page shows one; what the thing should do is left for the user to write at the end.
2052
+ function askModelToCreate(kind, { project, settingsFile }) {
2053
+ const sep = settingsFile.includes("\\") ? "\\" : "/";
2054
+ const userDir = settingsFile ? settingsFile.slice(0, settingsFile.lastIndexOf(sep)) : "~/.claude-pro";
2055
+ const dir = project ? `${project}${sep}.claude-pro` : userDir;
2056
+ const where = project ? `项目 ${project}` : "用户级(所有项目都能用)";
2057
+ const text = {
2058
+ skill: `帮我新建一个技能,放在${where}:${dir}${sep}skills${sep}<名字>${sep}SKILL.md。frontmatter 写 name 和 description(description 说清楚什么时候该用它),正文写步骤和说明。信息不够就先问我。\n\n这个技能用来:`,
2059
+ agent: `帮我新建一个子 agent,放在${where}:${dir}${sep}agents${sep}<名字>.md。frontmatter 写 name、description(什么时候把任务交给它)和 tools,正文是它的系统提示词。信息不够就先问我。\n\n这个子 agent 负责:`,
2060
+ mcp: `帮我添加一个 MCP 服务器,写进${project ? `项目的 ${project}${sep}.mcp.json` : ` ${settingsFile || "用户设置文件"} 的 "mcpServers"`}(写法和 Claude Code 的 mcpServers 一样:stdio 用 command/args/env,远程用 type: "http" 和 url/headers)。需要安装或填密钥就告诉我,先别把密钥写进会提交的文件。\n\n要接入的服务:`,
2061
+ }[kind];
2062
+ if (!text) return;
2063
+ if (draftText("new").trim() && !confirm("新会话输入框里还有没发送的内容,用这段要求替换它吗?")) return;
2064
+ saveDraft("new", text, []);
2065
+ if (project) localStorage.setItem("cpNewDir", project);
2066
+ location.hash = "#/new";
1668
2067
  }
1669
2068
 
1670
2069
  function mcpDialog(x, server, project) {
@@ -1692,8 +2091,9 @@
1692
2091
 
1693
2092
  async function usage() {
1694
2093
  const days = Number(sessionStorage.getItem("usageDays")) || 30;
2094
+ const period = days === 1 ? "今天" : `近 ${days} 天`;
1695
2095
  const el = page(`<h1>用量</h1><p class="sub">按天、模型、项目统计(来自每次请求的运行记录;有价格的模型才算得出花费)</p>
1696
- <div class="toolbar">${[7, 30, 90].map((d) => `<button class="button ${d === days ? "" : "secondary"} small" data-days="${d}">近 ${d} 天</button>`).join("")}<span style="flex:1"></span><label class="muted" style="font-size:13px">图表:<select id="metric"><option value="cost">花费</option><option value="tokens">tokens</option><option value="requests">请求数</option></select></label></div><div id="body"><div class="empty">正在统计…</div></div>`);
2096
+ <div class="toolbar">${[1, 7, 30, 90].map((d) => `<button class="button ${d === days ? "" : "secondary"} small" data-days="${d}">${d === 1 ? "今天" : `近 ${d} 天`}</button>`).join("")}<span style="flex:1"></span><label class="muted" style="font-size:13px">图表:<select id="metric"><option value="cost">花费</option><option value="tokens">tokens</option><option value="requests">请求数</option></select></label></div><div id="body"><div class="empty">正在统计…</div></div>`);
1697
2097
  $$("[data-days]", el).forEach((b) => b.addEventListener("click", () => { sessionStorage.setItem("usageDays", b.dataset.days); usage(); }));
1698
2098
  let u;
1699
2099
  try { u = await api(`/api/usage?days=${days}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
@@ -1702,30 +2102,33 @@
1702
2102
  ${rows.map((r) => `<tr><td class="mono" style="word-break:break-all">${esc(shortPath(r.key))}</td><td class="num">${r.requests}</td><td class="num">${fmtTokens(r.input)}</td><td class="num">${fmtTokens(r.output)}</td><td class="num">${fmtTokens(r.cacheRead)}</td><td class="num">${fmtTokens(r.cacheWrite)}</td><td class="num">${r.cost ? fmtUsd(r.cost) : "—"}${r.unpriced ? ` <span class="faint" title="${r.unpriced} 次请求的模型没有价格">*</span>` : ""}</td></tr>`).join("")}
1703
2103
  </tbody></table>` : '<div class="empty">没有记录</div>';
1704
2104
  $("#body", el).innerHTML = `<div class="cards">
1705
- <div class="panel stat"><div class="label">花费(近 ${days} 天,按价格估算)</div><div class="value">${fmtUsd(total.cost)}</div></div>
2105
+ <div class="panel stat"><div class="label">花费(${period},按价格估算)</div><div class="value">${fmtUsd(total.cost)}</div></div>
1706
2106
  <div class="panel stat"><div class="label">请求</div><div class="value">${total.requests}</div></div>
1707
2107
  <div class="panel stat"><div class="label">tokens(含缓存)</div><div class="value">${fmtTokens(total.tokens)}</div></div>
1708
2108
  <div class="panel stat"><div class="label">所有会话累计花费</div><div class="value">${fmtUsd(u.totalSessionCost)}</div><div class="hint">会话自己记录的花费,不限时间</div></div></div>
1709
- <div class="section-head"><h2>每天</h2></div><div class="panel panel-pad"><svg class="chart" id="chart"></svg></div>
2109
+ <div class="section-head"><h2>${days === 1 ? "每小时" : "每天"}</h2></div><div class="panel panel-pad"><svg class="chart" id="chart"></svg></div>
1710
2110
  <div class="section-head"><h2>按模型</h2></div><div class="panel">${table(u.models, "模型")}</div>
1711
2111
  <div class="section-head"><h2>按项目</h2></div><div class="panel">${table(u.projects, "项目")}</div>
1712
- <div class="section-head"><h2>花费最多的会话</h2></div><div class="panel">${u.sessions.length ? `<table class="list"><tbody>${u.sessions.map((s) => `<tr class="click" data-open="${esc(s.dir)}/${esc(s.id)}"><td class="title-cell"><strong>${esc(s.title)}</strong><div class="path">${esc(shortPath(s.cwd || s.dir))}</div></td><td>${ago(s.mtime)}</td><td class="num">${fmtUsd(s.cost)}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">没有记录</div>'}</div>`;
2112
+ <div class="section-head"><h2>花费最多的会话(${period})</h2></div><div class="panel">${u.sessions.length ? `<table class="list"><tbody>${u.sessions.map((s) => `<tr${s.dir ? ` class="click" data-open="${esc(s.dir)}/${esc(s.id)}"` : ""}><td class="title-cell"><strong>${esc(s.title || "(已删除的会话)")}</strong><div class="path">${esc(s.cwd || s.dir ? shortPath(s.cwd || s.dir) : s.id)}</div></td><td>${s.mtime ? ago(s.mtime) : ""}</td><td class="num">${s.requests} 次</td><td class="num">${s.cost ? fmtUsd(s.cost) : "—"}${s.unpriced ? ` <span class="faint" title="${s.unpriced} 次请求的模型没有价格">*</span>` : ""}</td></tr>`).join("")}</tbody></table>` : '<div class="empty">没有记录</div>'}</div>`;
1713
2113
  const drawChart = () => {
1714
2114
  const metric = $("#metric", el).value;
1715
2115
  const val = (d) => (metric === "cost" ? d.cost : metric === "tokens" ? d.input + d.output + d.cacheRead + d.cacheWrite : d.requests);
1716
2116
  const svg = $("#chart", el);
2117
+ const series = days === 1 && u.hours ? u.hours : u.days; // (today: by hour)
1717
2118
  const w = svg.clientWidth || 900, h = 220, pad = { l: 56, r: 10, t: 10, b: 26 };
1718
- const max = Math.max(...u.days.map(val), metric === "cost" ? 0.01 : 1);
1719
- const bw = (w - pad.l - pad.r) / u.days.length;
2119
+ const max = Math.max(...series.map(val), metric === "cost" ? 0.01 : 1);
2120
+ const bw = (w - pad.l - pad.r) / series.length;
1720
2121
  const fmt = (v) => (metric === "cost" ? fmtUsd(v) : fmtTokens(v));
1721
2122
  let s = "";
1722
2123
  for (let i = 0; i <= 4; i++) { const y = pad.t + ((h - pad.t - pad.b) * i) / 4; s += `<line x1="${pad.l}" x2="${w - pad.r}" y1="${y}" y2="${y}"/><text x="${pad.l - 6}" y="${y + 3}" text-anchor="end">${esc(fmt(max * (1 - i / 4)))}</text>`; }
1723
- u.days.forEach((d, i) => {
2124
+ const label = (d) => (series === u.days ? d.key.slice(5) : d.key.slice(0, 2));
2125
+ const every = Math.max(1, Math.ceil(series.length / (w < 520 ? 6 : 12)));
2126
+ series.forEach((d, i) => {
1724
2127
  const v = val(d);
1725
2128
  const bh = ((h - pad.t - pad.b) * v) / max;
1726
2129
  const x = pad.l + i * bw;
1727
2130
  s += `<rect class="bar" x="${x + bw * 0.15}" y="${h - pad.b - bh}" width="${Math.max(1, bw * 0.7)}" height="${Math.max(0, bh)}"><title>${esc(d.key)}:${esc(fmt(v))} · ${d.requests} 次请求</title></rect>`;
1728
- if (u.days.length <= 31 ? i % Math.ceil(u.days.length / 10) === 0 : i % 10 === 0) s += `<text x="${x + bw / 2}" y="${h - 8}" text-anchor="middle">${esc(d.key.slice(5))}</text>`;
2131
+ if (i % every === 0) s += `<text x="${x + bw / 2}" y="${h - 8}" text-anchor="middle">${esc(label(d))}</text>`;
1729
2132
  });
1730
2133
  svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
1731
2134
  svg.innerHTML = s;
@@ -1836,15 +2239,57 @@
1836
2239
  setDrawer(false);
1837
2240
  syncVisualHeight();
1838
2241
  $("#logoutBtn").addEventListener("click", async () => { await api("/api/logout", { method: "POST" }).catch(() => {}); location.reload(); });
2242
+ // The console took up new code (an update, an edit): this page is the old one, and the API may differ from it.
2243
+ let pageCode = null, toldReload = false;
2244
+ function noteServerCode(p) {
2245
+ if (!p?.code) return;
2246
+ pageCode ??= p.code;
2247
+ if (p.code === pageCode || toldReload) return;
2248
+ toldReload = true;
2249
+ const el = document.createElement("div");
2250
+ el.className = "reload-note"; // (not .toast: toast() reuses and removes that one)
2251
+ el.innerHTML = `控制台已更新到 v${esc(p.version)}:<button type="button" class="button small" data-reload>刷新页面</button>`;
2252
+ el.querySelector("[data-reload]").addEventListener("click", () => location.reload());
2253
+ document.body.appendChild(el);
2254
+ }
2255
+ let pingTick = 0;
1839
2256
  api("/api/ping").then((p) => {
2257
+ noteServerCode(p);
1840
2258
  $("#brandVersion").textContent = `v${p.version}`;
2259
+ if (p.machine) $("#sideMe").title = `设置与更多 · ${p.machine}`;
1841
2260
  hasNativeFolderPicker = p.nativeFolderPicker === true;
1842
2261
  $("#remoteLinks").classList.toggle("hidden", !p.remote); // opened through 远程访问: switch computer, log out
2262
+ if (p.repo) { $("#repoLink").href = p.repo; $("#repoLink").classList.remove("hidden"); $("#repoSep").classList.remove("hidden"); }
1843
2263
  route();
1844
2264
  loadWorkspace();
1845
2265
  scheduleUpdateCheck();
2266
+ noticeNoProvider();
1846
2267
  }).catch(() => {});
2268
+ // A first start (nothing connected, not even 7bit.fun): said at once, with the way to the page that adds one. Once a
2269
+ // browser session, and not on that page.
2270
+ function noticeNoProvider() {
2271
+ if (sessionStorage.getItem("cpNoProviderShown")) return;
2272
+ api("/api/providers").then((v) => {
2273
+ if (v.gateway?.connected || [...(v.presets || []), ...(v.custom || [])].some((x) => x.connected)) return;
2274
+ if (location.hash.startsWith("#/providers") || sessionStorage.getItem("cpNoProviderShown")) return;
2275
+ sessionStorage.setItem("cpNoProviderShown", "1");
2276
+ const m = modal({
2277
+ title: "先添加一个模型供应商",
2278
+ body: `<p style="margin:0 0 10px">claude-pro 需要连上至少一个模型供应商才能工作:7bit.fun、DeepSeek、Kimi、OpenAI、OpenRouter……也可以是任何兼容 Anthropic 或 OpenAI 接口的服务。</p><p class="muted" style="margin:0;font-size:13px">添加之后,在「模型与供应商」里还能勾选会话里要用的模型、设置默认模型。</p>`,
2279
+ foot: '<button class="button secondary" data-close>稍后</button><button class="button" id="goAddProvider">添加供应商</button>',
2280
+ });
2281
+ $("#goAddProvider", m.el).addEventListener("click", () => {
2282
+ m.close();
2283
+ sessionStorage.setItem("cpOpenAdd", "1");
2284
+ if (location.hash === "#/providers") route(); else location.hash = "#/providers";
2285
+ });
2286
+ $("#goAddProvider", m.el).focus();
2287
+ }).catch(() => {});
2288
+ }
1847
2289
  // the sidebar follows the sessions (and keeps the server from stopping while the page is open)
1848
- setInterval(() => { if (document.visibilityState === "visible") loadWorkspace(); else api("/api/ping").catch(() => {}); }, 5000);
1849
- api("/api/overview").then((o) => { const who = o.gateway?.account?.name || o.gateway?.account?.email || o.host; $("#sideUser").textContent = who; $("#sideAvatar").textContent = String(who || "?").slice(0, 1).toUpperCase(); }).catch(() => {});
2290
+ setInterval(() => {
2291
+ const visible = document.visibilityState === "visible";
2292
+ if (visible) loadWorkspace();
2293
+ if (!visible || ++pingTick % 6 === 0) api("/api/ping").then(noteServerCode).catch(() => {}); // (every 30 s while looked at)
2294
+ }, 5000);
1850
2295
  })();