@yanzc/claude-pro 0.12.0 → 0.13.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
  }
@@ -1408,83 +1502,266 @@
1408
1502
  drawProviders(el, p);
1409
1503
  }
1410
1504
 
1505
+ let modelTab = null; // the provider whose tab 模型列表 shows (kept across redraws; a provider just connected gets it)
1411
1506
  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
1507
  $("#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); }
1508
+ <div class="section-head"><div><h2>默认设置</h2><p>新会话用的模型和思考强度,选了就保存。会话里的 /model、/effort 只改那一个会话(并记住给下次用);已经开着的会话要 /model default 或重启才换</p></div></div>
1509
+ <div class="panel" id="defaults"><div class="panel-pad muted">正在读取…</div></div>
1510
+ <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>
1511
+ <div id="modelLists"><div class="panel panel-pad muted">正在读取…</div></div></div>`;
1512
+ loadModelLists(el, p);
1513
+ // 添加供应商: any built-in provider or 7bit.fun (one connected already: another account of it), or one of the
1514
+ // user's own
1515
+ $("#addProvider", el).addEventListener("click", (e) => {
1516
+ const others = (base) => p.custom.filter((c) => c.preset === base && c.connected).length;
1517
+ const again = "已连接 · 再添加一个账号";
1518
+ popMenu(e.currentTarget, [
1519
+ { key: "preset", title: "选择供应商", items: [
1520
+ { label: "7bit.fun", description: p.gateway.connected ? again : `${p.gateway.url} · Claude、GPT 等模型`, value: "7bit" },
1521
+ ...p.presets.map((x) => ({ label: x.providerName || x.name, description: x.connected ? again : x.baseUrl, value: x.id })),
1522
+ ] },
1523
+ { key: "custom", title: "", items: [{ label: "自定义供应商…", description: "任何兼容 Anthropic 或 OpenAI 的接口", value: "" }] },
1524
+ ], (key, value) => {
1525
+ if (key === "custom") return connectDialog(el, null);
1526
+ if (value === "7bit") {
1527
+ if (!p.gateway.connected) return gatewayDialog(el, p);
1528
+ return connectDialog(el, null, { instanceOf: "7bit", template: { name: "7bit.fun", baseUrl: p.gateway.url }, count: 1 + others("7bit") });
1529
+ }
1530
+ const x = p.presets.find((y) => y.id === value);
1531
+ if (!x) return;
1532
+ if (!x.connected) return connectDialog(el, x);
1533
+ connectDialog(el, null, { instanceOf: x.id, template: { name: x.providerName || x.name, baseUrl: x.baseUrl, keyless: x.keyless }, count: 1 + others(x.id) });
1534
+ }, { dropdown: true });
1432
1535
  });
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); }
1536
+ // (from the first-run notice: the menu opens by itself)
1537
+ if (sessionStorage.getItem("cpOpenAdd")) { sessionStorage.removeItem("cpOpenAdd"); setTimeout(() => { if (el.isConnected) $("#addProvider", el)?.click(); }, 60); }
1538
+ $("#refreshModels", el).addEventListener("click", async (e) => {
1539
+ const b = e.currentTarget;
1540
+ b.disabled = true;
1541
+ b.textContent = "正在刷新…";
1542
+ try {
1543
+ const r = await api("/api/models/refresh", { method: "POST", body: {} });
1544
+ const parts = [...(r.gateway ? [{ name: "7bit.fun", ...r.gateway }] : []), ...r.providers];
1545
+ const ok = parts.filter((x) => !x.error).map((x) => `${x.name} ${x.count} 个`);
1546
+ const bad = parts.filter((x) => x.error).map((x) => `${x.name}(${x.error})`);
1547
+ if (!parts.length) toast("还没有连接任何供应商", "error");
1548
+ else toast([ok.length ? `已刷新:${ok.join(",")}` : "", bad.length ? `失败:${bad.join(",")}` : ""].filter(Boolean).join(";"), bad.length && !ok.length ? "error" : "ok");
1549
+ if (el.isConnected) drawProviders(el, r.view);
1550
+ } catch (err) { fail(err); b.disabled = false; b.textContent = "刷新模型列表"; }
1436
1551
  });
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); }
1552
+ }
1553
+
1554
+ // 模型列表: the kept lists, a tab per provider (nothing is asked of the providers here: see 刷新模型列表); each
1555
+ // tab says how its provider is connected, with 更换 Key / 模型 and 断开.
1556
+ async function loadModelLists(el, p) {
1557
+ const box = $("#modelLists", el);
1558
+ let r;
1559
+ try { r = await api("/api/models/kept"); } catch (e) {
1560
+ box.innerHTML = `<div class="panel panel-pad muted">读取失败:${esc(e.message)}</div>`;
1561
+ $("#defaults", el).innerHTML = `<div class="panel-pad muted">读取失败:${esc(e.message)}</div>`;
1562
+ return;
1563
+ }
1564
+ if (!el.isConnected) return;
1565
+ const current = r.remembered?.model || r.current;
1566
+ const picked = new Set(r.picked || []);
1567
+ const price = (m) => (m.price ? `$${m.price.input} / $${m.price.output}` : "—");
1568
+ const pickedNote = () => (picked.size ? `菜单显示勾选的 ${picked.size} 个` : "菜单显示全部");
1569
+ const providerOf = (id) => [...(p?.presets || []), ...(p?.custom || [])].find((x) => x.id === id);
1570
+ if (!r.groups.some((g) => g.id === modelTab)) modelTab = r.groups[0]?.id || null;
1571
+ const head = (g) => {
1572
+ const x = providerOf(g.id);
1573
+ const when = `${g.models.length} 个模型${g.at ? ` · ${esc(ago(g.at))}更新` : ""}`;
1574
+ if (g.id === "7bit" && p?.gateway) {
1575
+ // (the balance comes after: GET /api/gateway/account)
1576
+ 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>
1577
+ <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
1578
  }
1579
+ if (!x) return `<div class="mg-head"><div class="meta">${when}</div></div>`;
1580
+ return `<div class="mg-head"><div class="meta">${esc(x.protocol === "openai" ? "OpenAI 协议" : "Anthropic 协议")} · ${esc(x.baseUrl)} · Key ${esc(x.key || "(无需)")} · ${when}</div>
1581
+ <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>`;
1582
+ };
1583
+ 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"}>
1584
+ ${head(g)}<div class="empty no-match" hidden>这个供应商里没有匹配的模型</div>
1585
+ ${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>
1586
+ ${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("")}
1587
+ </tbody></table>` : '<div class="empty">还没有拉取过模型列表:点「刷新模型列表」</div>'}</div>`).join("") : '<div class="panel panel-pad muted">还没有连接供应商:点「添加供应商」</div>';
1588
+ 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>`);
1589
+ // 默认设置: the default model, among the models ticked below (all when none is), and the default effort; each
1590
+ // saved when chosen (settings.json), and what a session's /model or /effort remembered of it forgotten
1591
+ let defModel = r.remembered?.model || r.current;
1592
+ let defEffort = p?.remembered?.effort || p?.effort || "auto";
1593
+ let remembered = { model: r.remembered?.model || null, effort: p?.remembered?.effort || null };
1594
+ const allModels = r.groups.flatMap((g) => g.models.map((m) => ({ ref: m.ref, group: g.name, name: m.name })));
1595
+ const paintDefaults = () => {
1596
+ const dbox = $("#defaults", el);
1597
+ if (!dbox) return;
1598
+ const choices = picked.size ? allModels.filter((m) => picked.has(m.ref)) : allModels;
1599
+ const groups = [...new Set(choices.map((m) => m.group))];
1600
+ const listed = choices.some((m) => m.ref === defModel);
1601
+ const efforts = ["auto", "low", "medium", "high", "xhigh", "max"];
1602
+ dbox.innerHTML = `<div class="def-row"><div class="def-label"><strong>默认模型</strong><small>选项是下面「模型列表」里勾选的模型${picked.size ? `(${picked.size} 个)` : "(没勾选:列出全部)"}</small></div>
1603
+ <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>
1604
+ ${remembered.model ? `<div class="def-note">现在生效的是会话里 /model 记住的选择;在这里选一次就以这里为准</div>` : ""}</div></div>
1605
+ <div class="def-row"><div class="def-label"><strong>思考强度</strong><small>auto 用模型自己的默认;不支持的模型会取最接近的一档</small></div>
1606
+ <div><select id="defEffort">${efforts.map((x) => `<option${x === defEffort ? " selected" : ""}>${x}</option>`).join("")}${efforts.includes(defEffort) ? "" : `<option selected>${esc(defEffort)}</option>`}</select>
1607
+ ${remembered.effort ? `<div class="def-note">现在生效的是会话里 /effort 记住的选择;在这里选一次就以这里为准</div>` : ""}</div></div>`;
1608
+ $("#defModel", dbox).onchange = async (e) => {
1609
+ const value = e.target.value;
1610
+ try {
1611
+ await api("/api/settings", { method: "POST", body: { scope: "user", key: "model", value } });
1612
+ if (remembered.model) await api("/api/remembered", { method: "POST", body: { model: null } });
1613
+ defModel = value;
1614
+ remembered.model = null;
1615
+ for (const pill of $$(".def-pill", box)) pill.remove();
1616
+ $(`tr[data-model="${CSS.escape(value)}"] .title-cell strong`, box)?.insertAdjacentHTML("beforeend", ' <span class="pill ok def-pill">默认</span>');
1617
+ toast(`默认模型已改为 ${value}`);
1618
+ } catch (err) { fail(err); }
1619
+ paintDefaults();
1620
+ };
1621
+ $("#defEffort", dbox).onchange = async (e) => {
1622
+ const value = e.target.value;
1623
+ try {
1624
+ await api("/api/settings", { method: "POST", body: { scope: "user", key: "effort", value } });
1625
+ if (remembered.effort) await api("/api/remembered", { method: "POST", body: { effort: null } });
1626
+ defEffort = value;
1627
+ remembered.effort = null;
1628
+ toast(`默认思考强度已改为 ${value}`);
1629
+ } catch (err) { fail(err); }
1630
+ paintDefaults();
1631
+ };
1632
+ };
1633
+ paintDefaults();
1634
+ let saving = Promise.resolve();
1635
+ const savePicked = () => {
1636
+ const models = [...picked];
1637
+ $("#pickedNote", box).textContent = pickedNote();
1638
+ $("#clearPicked", box).hidden = !picked.size;
1639
+ paintDefaults(); // (its choices are the ticked models)
1640
+ saving = saving.then(() => api("/api/models/picked", { method: "POST", body: { models } })).catch((e) => fail(e));
1641
+ };
1642
+ box.onchange = (e) => {
1643
+ const cb = e.target.closest("input[data-pick]");
1644
+ if (!cb) return;
1645
+ if (cb.checked) picked.add(cb.dataset.pick); else picked.delete(cb.dataset.pick);
1646
+ savePicked();
1647
+ };
1648
+ $("#clearPicked", box)?.addEventListener("click", () => {
1649
+ picked.clear();
1650
+ for (const cb of $$("input[data-pick]", box)) cb.checked = false;
1651
+ savePicked();
1652
+ toast("已清除勾选:会话的模型菜单显示全部模型");
1444
1653
  });
1654
+ if ($("#gwBalance", box)) {
1655
+ api("/api/gateway/account").then((a) => {
1656
+ const b = $("#gwBalance", box);
1657
+ if (!b) return;
1658
+ b.textContent = a.balance != null ? fmtUsd(a.balance) : "—";
1659
+ if (a.error) b.title = `查询失败:${a.error}`;
1660
+ if (a.email && !$("#gwAccount", box).textContent) $("#gwAccount", box).textContent = ` · ${a.email}`;
1661
+ }).catch(() => { const b = $("#gwBalance", box); if (b) b.textContent = "—"; });
1662
+ }
1663
+ const filter = $("#modelFilter", el);
1664
+ // searching: every tab says how many of its models match; the tab shown lists them
1665
+ const apply = () => {
1666
+ const q = filter.value.trim().toLowerCase();
1667
+ for (const g of $$(".model-group", box)) {
1668
+ const rows = $$("tr[data-model]", g);
1669
+ let shown = 0;
1670
+ for (const tr of rows) { const hit = !q || tr.dataset.text.includes(q); tr.hidden = !hit; shown += hit; }
1671
+ $(".no-match", g).hidden = !q || !rows.length || shown > 0;
1672
+ const tab = $(`[data-tab="${CSS.escape(g.dataset.group)}"] .count`, box);
1673
+ if (tab) tab.textContent = q ? `${shown}/${rows.length}` : rows.length;
1674
+ }
1675
+ };
1676
+ const show = (id) => {
1677
+ modelTab = id;
1678
+ for (const t of $$("[data-tab]", box)) { const on = t.dataset.tab === id; t.classList.toggle("active", on); t.setAttribute("aria-selected", String(on)); }
1679
+ for (const g of $$(".model-group", box)) g.hidden = g.dataset.group !== id;
1680
+ };
1681
+ filter.oninput = apply;
1682
+ apply();
1683
+ box.onclick = async (e) => {
1684
+ const tab = e.target.closest("[data-tab]");
1685
+ if (tab) return show(tab.dataset.tab);
1686
+ const gw = e.target.closest("[data-gateway]");
1687
+ if (gw?.dataset.gateway === "change") return gatewayDialog(el, p);
1688
+ if (gw?.dataset.gateway === "remove") {
1689
+ if (!confirm("断开 7bit.fun?保存的 Key 会删除:它的模型不能用了,这台电脑的会话也会下线(远程访问、跨电脑互发任务靠它)。")) return;
1690
+ try { drawProviders(el, await api("/api/gateway", { method: "DELETE" })); toast("已断开 7bit.fun"); } catch (err) { fail(err); }
1691
+ return;
1692
+ }
1693
+ const c = e.target.closest("[data-connect]"), rm = e.target.closest("[data-remove]");
1694
+ if (c) return connectDialog(el, providerOf(c.dataset.connect));
1695
+ if (rm) {
1696
+ const x = providerOf(rm.dataset.remove);
1697
+ if (!confirm(`断开 ${x?.name || rm.dataset.remove}?保存的 Key 会删除,它的模型也从列表里去掉。`)) return;
1698
+ try { drawProviders(el, await api(`/api/providers/${encodeURIComponent(rm.dataset.remove)}`, { method: "DELETE" })); toast("已断开"); } catch (err) { fail(err); }
1699
+ return;
1700
+ }
1701
+ if (e.target.closest(".pick")) return; // (the checkbox itself)
1702
+ // a click on the row ticks (or unticks) the model
1703
+ const cb = e.target.closest("tr[data-model]")?.querySelector("input[data-pick]");
1704
+ if (!cb) return;
1705
+ cb.checked = !cb.checked;
1706
+ cb.dispatchEvent(new Event("change", { bubbles: true }));
1707
+ };
1445
1708
  }
1446
1709
 
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); }
1710
+ // Connect 7bit.fun, or change its key: the gateway checks the key (its account), and its model list comes with it.
1711
+ function gatewayDialog(el, p) {
1712
+ const again = p.gateway.connected;
1713
+ const m = modal({
1714
+ title: again ? `${p.gateway.name || "7bit.fun"}:名称与 Key` : "连接 7bit.fun", sub: p.gateway.url,
1715
+ body: `<label class="field">名称<small>显示在 tab 里</small><input id="gName" maxlength="40" value="${esc(p.gateway.name || "7bit.fun")}"></label>
1716
+ <label class="field">API Key<small>${again ? "留空则继续用已保存的 Key;" : ""}在网关网页「API 密钥」里创建</small><input type="password" id="gKey" autocomplete="off" placeholder="${again ? "留空:用已保存的" : "粘贴 7bit.fun 的 API Key"}"></label>
1717
+ <a class="button secondary small" href="${esc(p.gateway.keyPage)}" target="_blank" rel="noopener">获取 Key</a>`,
1718
+ foot: `<span class="modal-error"></span><button class="button secondary" data-close>取消</button><button class="button" id="gConnect">${again ? "保存" : "连接"}</button>`,
1469
1719
  });
1720
+ const input = $("#gKey", m.el);
1721
+ (again ? $("#gName", m.el) : input).focus();
1722
+ const go = async () => {
1723
+ const apiKey = input.value.trim();
1724
+ const name = $("#gName", m.el).value.trim();
1725
+ const err = $(".modal-error", m.el);
1726
+ if (!apiKey && !again) { err.textContent = "请先粘贴 Key"; return; }
1727
+ const b = $("#gConnect", m.el);
1728
+ b.disabled = true;
1729
+ b.textContent = "正在验证…";
1730
+ err.textContent = "";
1731
+ try {
1732
+ const view = await api("/api/gateway", { method: "POST", body: { ...(apiKey ? { apiKey } : {}), name } });
1733
+ m.close();
1734
+ toast(again ? "已保存" : `已连接 ${name || "7bit.fun"}`);
1735
+ modelTab = "7bit";
1736
+ drawProviders(el, view);
1737
+ } catch (ex) { err.textContent = ex.message; b.disabled = false; b.textContent = again ? "保存" : "连接"; }
1738
+ };
1739
+ $("#gConnect", m.el).addEventListener("click", go);
1740
+ for (const i of [input, $("#gName", m.el)]) i.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); });
1470
1741
  }
1471
1742
 
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;
1743
+ // Connect a provider: a built-in one (x; connected already: its key, model or name changed), another account of one
1744
+ // or of 7bit.fun (instanceOf, with its template and how many are connected), or with neither one of the user's own.
1745
+ // 名称 → key → models → test → saved.
1746
+ function connectDialog(el, x, { instanceOf = null, template = null, count = 0 } = {}) {
1747
+ const custom = !x && !instanceOf;
1748
+ const base = x || template;
1749
+ const defaultName = x ? x.name : instanceOf ? `${template.name} ${count + 1}` : "";
1475
1750
  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>
1751
+ title: custom ? "添加自定义供应商" : x ? (x.connected ? `${x.name}:名称、Key 与模型` : `连接 ${x.name}`) : `再添加一个 ${template.name} 账号`,
1752
+ sub: custom ? "任何兼容 Anthropic Messages 或 OpenAI Chat Completions 的接口" : `${base.baseUrl}`,
1753
+ 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>
1754
+ ${custom ? `<label class="field">协议<select id="cProto"><option value="openai">OpenAI 兼容(/chat/completions)</option><option value="anthropic">Anthropic 兼容(/v1/messages)</option></select></label>
1479
1755
  <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>
1756
+ <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
1757
  <div class="actions"><button class="button secondary" id="cCheck">检查 Key 并列出模型</button></div>
1482
1758
  <div id="cModels" style="margin-top:14px"></div>`,
1483
1759
  foot: '<span class="modal-error"></span><button class="button secondary" data-close>取消</button><button class="button" id="cConnect" disabled>测试并连接</button>',
1484
1760
  });
1485
1761
  let checked = null;
1486
1762
  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 });
1763
+ const target = () => (custom ? { custom: { name: $("#cName", m.el).value, protocol: $("#cProto", m.el).value, baseUrl: $("#cUrl", m.el).value } } : instanceOf ? { instanceOf } : { id: x.id });
1764
+ (x?.connected ? $("#cName", m.el) : custom ? $("#cName", m.el) : $("#cKey", m.el)).focus();
1488
1765
  $("#cCheck", m.el).addEventListener("click", async (e) => {
1489
1766
  err("");
1490
1767
  e.target.disabled = true;
@@ -1509,9 +1786,10 @@
1509
1786
  e.target.disabled = true;
1510
1787
  e.target.textContent = `正在测试 ${model}…`;
1511
1788
  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 } });
1789
+ 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
1790
  m.close();
1514
1791
  toast(`已连接,模型 ${model} 测试通过`);
1792
+ modelTab = p.connected || modelTab; // (its tab is the one shown)
1515
1793
  drawProviders(el, p);
1516
1794
  } catch (ex) { err(ex.message); e.target.disabled = false; e.target.textContent = "测试并连接"; }
1517
1795
  });
@@ -1643,28 +1921,42 @@
1643
1921
  try { x = await api(`/api/extensions${project ? `?project=${encodeURIComponent(project)}` : ""}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
1644
1922
  const scopePill = (s) => `<span class="pill${s === "built-in" ? "" : s === "user" ? " accent" : " ok"}">${{ "built-in": "内置", user: "用户", project: "项目" }[s] || esc(s)}</span>`;
1645
1923
  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>`;
1924
+ // 新建: a new conversation with the request written for the model (it knows the formats and asks what is missing)
1925
+ const aiBtn = (kind) => `<button class="button secondary small" data-ai="${kind}" title="打开新会话,写好要求交给模型去做">${ICON.agent}让 AI 新建</button>`;
1647
1926
  $("#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>
1927
+ <div class="section-head"><div><h2>技能</h2><p>skills/&lt;名字&gt;/SKILL.md:模型按描述决定何时加载</p></div>${aiBtn("skill")}</div><div class="panel">${list(x.skills, "skill")}</div>
1928
+ <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>
1929
+ <div class="section-head"><div><h2>自定义命令</h2><p>commands/*.md:在会话里输入 /名字</p></div>${aiBtn("command")}</div><div class="panel">${list(x.commands, "command")}</div>
1930
+ <div class="section-head"><div><h2>MCP 服务器</h2><p>环境变量和请求头的值不会显示(保持 ••• 就是不改)</p></div>${aiBtn("mcp")}</div>
1652
1931
  <div class="panel">${x.mcp.length ? x.mcp.map((s, i) => `<div class="file-row"><span class="name">${esc(s.name)}</span><span class="pill">${esc(s.scope)}</span><span class="desc mono">${esc(s.spec?.url || [s.spec?.command, ...(s.spec?.args || [])].filter(Boolean).join(" "))}</span>${s.scope === "user" || s.scope === ".mcp.json" ? `<button class="button secondary small" data-mcp="${i}">编辑</button>` : `<button class="button secondary small" data-edit="${esc(s.file)}">编辑文件</button>`}</div>`).join("") : '<div class="file-row"><span class="desc">没有配置 MCP 服务器</span></div>'}</div>
1653
1932
  <div class="section-head"><div><h2>Hooks</h2><p>在工具调用前后、提交消息时等运行的命令,写在设置文件的 hooks 里</p></div></div>
1654
1933
  <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
1934
  $("#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]");
1935
+ const ed = e.target.closest("[data-edit]"), ai = e.target.closest("[data-ai]"), mc = e.target.closest("[data-mcp]");
1657
1936
  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
- }
1937
+ if (ai) askModelToCreate(ai.dataset.ai, { project, settingsFile: x.settingsFiles?.user || "" });
1665
1938
  if (mc) mcpDialog(x, x.mcp[Number(mc.dataset.mcp)], project);
1666
1939
  });
1667
- $("#addMcp", el).addEventListener("click", () => mcpDialog(x, null, project));
1940
+ }
1941
+
1942
+ // 让 AI 新建: the new conversation's box with the request (where the file goes, its format), the project's directory
1943
+ // chosen when the page shows one; what the thing should do is left for the user to write at the end.
1944
+ function askModelToCreate(kind, { project, settingsFile }) {
1945
+ const sep = settingsFile.includes("\\") ? "\\" : "/";
1946
+ const userDir = settingsFile ? settingsFile.slice(0, settingsFile.lastIndexOf(sep)) : "~/.claude-pro";
1947
+ const dir = project ? `${project}${sep}.claude-pro` : userDir;
1948
+ const where = project ? `项目 ${project}` : "用户级(所有项目都能用)";
1949
+ const text = {
1950
+ skill: `帮我新建一个技能,放在${where}:${dir}${sep}skills${sep}<名字>${sep}SKILL.md。frontmatter 写 name 和 description(description 说清楚什么时候该用它),正文写步骤和说明。信息不够就先问我。\n\n这个技能用来:`,
1951
+ agent: `帮我新建一个子 agent,放在${where}:${dir}${sep}agents${sep}<名字>.md。frontmatter 写 name、description(什么时候把任务交给它)和 tools,正文是它的系统提示词。信息不够就先问我。\n\n这个子 agent 负责:`,
1952
+ command: `帮我新建一个自定义命令,放在${where}:${dir}${sep}commands${sep}<名字>.md(在会话里输入 /<名字> 使用)。frontmatter 写 description 和 argument-hint,正文是发给模型的内容,用 $ARGUMENTS 代表命令后面的参数。信息不够就先问我。\n\n这个命令要做的事:`,
1953
+ mcp: `帮我添加一个 MCP 服务器,写进${project ? `项目的 ${project}${sep}.mcp.json` : ` ${settingsFile || "用户设置文件"} 的 "mcpServers"`}(写法和 Claude Code 的 mcpServers 一样:stdio 用 command/args/env,远程用 type: "http" 和 url/headers)。需要安装或填密钥就告诉我,先别把密钥写进会提交的文件。\n\n要接入的服务:`,
1954
+ }[kind];
1955
+ if (!text) return;
1956
+ if (draftText("new").trim() && !confirm("新会话输入框里还有没发送的内容,用这段要求替换它吗?")) return;
1957
+ saveDraft("new", text, []);
1958
+ if (project) localStorage.setItem("cpNewDir", project);
1959
+ location.hash = "#/new";
1668
1960
  }
1669
1961
 
1670
1962
  function mcpDialog(x, server, project) {
@@ -1692,8 +1984,9 @@
1692
1984
 
1693
1985
  async function usage() {
1694
1986
  const days = Number(sessionStorage.getItem("usageDays")) || 30;
1987
+ const period = days === 1 ? "今天" : `近 ${days} 天`;
1695
1988
  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>`);
1989
+ <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
1990
  $$("[data-days]", el).forEach((b) => b.addEventListener("click", () => { sessionStorage.setItem("usageDays", b.dataset.days); usage(); }));
1698
1991
  let u;
1699
1992
  try { u = await api(`/api/usage?days=${days}`); } catch (e) { $("#body", el).innerHTML = `<div class="empty">加载失败:${esc(e.message)}</div>`; return; }
@@ -1702,30 +1995,33 @@
1702
1995
  ${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
1996
  </tbody></table>` : '<div class="empty">没有记录</div>';
1704
1997
  $("#body", el).innerHTML = `<div class="cards">
1705
- <div class="panel stat"><div class="label">花费(近 ${days} 天,按价格估算)</div><div class="value">${fmtUsd(total.cost)}</div></div>
1998
+ <div class="panel stat"><div class="label">花费(${period},按价格估算)</div><div class="value">${fmtUsd(total.cost)}</div></div>
1706
1999
  <div class="panel stat"><div class="label">请求</div><div class="value">${total.requests}</div></div>
1707
2000
  <div class="panel stat"><div class="label">tokens(含缓存)</div><div class="value">${fmtTokens(total.tokens)}</div></div>
1708
2001
  <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>
2002
+ <div class="section-head"><h2>${days === 1 ? "每小时" : "每天"}</h2></div><div class="panel panel-pad"><svg class="chart" id="chart"></svg></div>
1710
2003
  <div class="section-head"><h2>按模型</h2></div><div class="panel">${table(u.models, "模型")}</div>
1711
2004
  <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>`;
2005
+ <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
2006
  const drawChart = () => {
1714
2007
  const metric = $("#metric", el).value;
1715
2008
  const val = (d) => (metric === "cost" ? d.cost : metric === "tokens" ? d.input + d.output + d.cacheRead + d.cacheWrite : d.requests);
1716
2009
  const svg = $("#chart", el);
2010
+ const series = days === 1 && u.hours ? u.hours : u.days; // (today: by hour)
1717
2011
  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;
2012
+ const max = Math.max(...series.map(val), metric === "cost" ? 0.01 : 1);
2013
+ const bw = (w - pad.l - pad.r) / series.length;
1720
2014
  const fmt = (v) => (metric === "cost" ? fmtUsd(v) : fmtTokens(v));
1721
2015
  let s = "";
1722
2016
  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) => {
2017
+ const label = (d) => (series === u.days ? d.key.slice(5) : d.key.slice(0, 2));
2018
+ const every = Math.max(1, Math.ceil(series.length / (w < 520 ? 6 : 12)));
2019
+ series.forEach((d, i) => {
1724
2020
  const v = val(d);
1725
2021
  const bh = ((h - pad.t - pad.b) * v) / max;
1726
2022
  const x = pad.l + i * bw;
1727
2023
  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>`;
2024
+ if (i % every === 0) s += `<text x="${x + bw / 2}" y="${h - 8}" text-anchor="middle">${esc(label(d))}</text>`;
1729
2025
  });
1730
2026
  svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
1731
2027
  svg.innerHTML = s;
@@ -1836,15 +2132,57 @@
1836
2132
  setDrawer(false);
1837
2133
  syncVisualHeight();
1838
2134
  $("#logoutBtn").addEventListener("click", async () => { await api("/api/logout", { method: "POST" }).catch(() => {}); location.reload(); });
2135
+ // The console took up new code (an update, an edit): this page is the old one, and the API may differ from it.
2136
+ let pageCode = null, toldReload = false;
2137
+ function noteServerCode(p) {
2138
+ if (!p?.code) return;
2139
+ pageCode ??= p.code;
2140
+ if (p.code === pageCode || toldReload) return;
2141
+ toldReload = true;
2142
+ const el = document.createElement("div");
2143
+ el.className = "reload-note"; // (not .toast: toast() reuses and removes that one)
2144
+ el.innerHTML = `控制台已更新到 v${esc(p.version)}:<button type="button" class="button small" data-reload>刷新页面</button>`;
2145
+ el.querySelector("[data-reload]").addEventListener("click", () => location.reload());
2146
+ document.body.appendChild(el);
2147
+ }
2148
+ let pingTick = 0;
1839
2149
  api("/api/ping").then((p) => {
2150
+ noteServerCode(p);
1840
2151
  $("#brandVersion").textContent = `v${p.version}`;
2152
+ if (p.machine) $("#sideMe").title = `设置与更多 · ${p.machine}`;
1841
2153
  hasNativeFolderPicker = p.nativeFolderPicker === true;
1842
2154
  $("#remoteLinks").classList.toggle("hidden", !p.remote); // opened through 远程访问: switch computer, log out
2155
+ if (p.repo) { $("#repoLink").href = p.repo; $("#repoLink").classList.remove("hidden"); $("#repoSep").classList.remove("hidden"); }
1843
2156
  route();
1844
2157
  loadWorkspace();
1845
2158
  scheduleUpdateCheck();
2159
+ noticeNoProvider();
1846
2160
  }).catch(() => {});
2161
+ // A first start (nothing connected, not even 7bit.fun): said at once, with the way to the page that adds one. Once a
2162
+ // browser session, and not on that page.
2163
+ function noticeNoProvider() {
2164
+ if (sessionStorage.getItem("cpNoProviderShown")) return;
2165
+ api("/api/providers").then((v) => {
2166
+ if (v.gateway?.connected || [...(v.presets || []), ...(v.custom || [])].some((x) => x.connected)) return;
2167
+ if (location.hash.startsWith("#/providers") || sessionStorage.getItem("cpNoProviderShown")) return;
2168
+ sessionStorage.setItem("cpNoProviderShown", "1");
2169
+ const m = modal({
2170
+ title: "先添加一个模型供应商",
2171
+ 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>`,
2172
+ foot: '<button class="button secondary" data-close>稍后</button><button class="button" id="goAddProvider">添加供应商</button>',
2173
+ });
2174
+ $("#goAddProvider", m.el).addEventListener("click", () => {
2175
+ m.close();
2176
+ sessionStorage.setItem("cpOpenAdd", "1");
2177
+ if (location.hash === "#/providers") route(); else location.hash = "#/providers";
2178
+ });
2179
+ $("#goAddProvider", m.el).focus();
2180
+ }).catch(() => {});
2181
+ }
1847
2182
  // 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(() => {});
2183
+ setInterval(() => {
2184
+ const visible = document.visibilityState === "visible";
2185
+ if (visible) loadWorkspace();
2186
+ if (!visible || ++pingTick % 6 === 0) api("/api/ping").then(noteServerCode).catch(() => {}); // (every 30 s while looked at)
2187
+ }, 5000);
1850
2188
  })();