dsh-dock 0.21.2 → 0.23.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.
@@ -2,7 +2,8 @@
2
2
  //
3
3
  // 嵌入功能坞面板的统计视图(无独立 overlay 外壳;全屏用 dock 弹窗自带的「最大化」):
4
4
  // - 秒级时间范围查询 + 会话ID/提供商/模型(联动)/状态/推理强度 筛选,条件本地暂存
5
- // - 9 张 KPI 卡 + 分组统计表 + 明细表(点击表头排序、会话ID点击即筛选、100 行/页上下双分页)
5
+ // - 会话可选「任务累计(含全部后代子任务)/仅本会话」;同时展示自身与子任务拆分
6
+ // - 8 张 KPI 卡 + 分组统计表 + 明细表(点击表头排序、会话ID点击即筛选、100 行/页上下双分页)
6
7
  // - 状态列显示 HTTP 状态码徽章,行内【查看详情】弹窗展示完整信息;CSV 导出(中文表头,列序与明细表一致 + 合计行)
7
8
  // - 独立的「单价设置」子弹窗:按模型配置单价(多段分时价 + 日期类型/法定节假日)并持久化,费用按自填单价重算
8
9
  // - 挂载即扫描历史+按暂存条件查询;挂载期间每 5s 静默自动刷新
@@ -102,6 +103,10 @@ function hourOf(ts) { return new Date(ts).getHours(); }
102
103
  const EXPORT_COLUMNS = [
103
104
  ["时间", (r) => fmtTime(r.time)],
104
105
  ["会话ID", (r) => r.sessionId || ""],
106
+ ["直接父会话ID", (r) => r.parentSessionId || ""],
107
+ ["根会话ID", (r) => r.rootSessionId || r.sessionId || ""],
108
+ ["会话层级", (r) => String(r.sessionDepth || 0)],
109
+ ["会话类型", (r) => r.isSubtask ? "子任务" : "主会话"],
105
110
  ["提供商", (r) => r.provider || "—"],
106
111
  ["模型", (r) => r.model || "—"],
107
112
  ["输入(命中)", (r) => fmtNum(r.cacheReadTokens)],
@@ -149,7 +154,7 @@ function buildExportCsv(rows, rate) {
149
154
  // ---------- 筛选条件暂存(本地) ----------
150
155
  // 打开视图时恢复上次保存的条件; 从未保存过则时间范围不选(显示全部记录)。
151
156
  const STORE_KEY = "dsh-dock/tokenlog/filters/v1";
152
- const FILTER_FIELDS = ["fromStr", "toStr", "provider", "model", "status", "effort", "sessionId", "dim"];
157
+ const FILTER_FIELDS = ["fromStr", "toStr", "provider", "model", "status", "effort", "sessionId", "sessionScope", "dim"];
153
158
  function loadSavedFilters() {
154
159
  try {
155
160
  if (typeof localStorage === "undefined") return null;
@@ -173,6 +178,7 @@ function shortId(sid) {
173
178
  if (sid.length <= 16) return sid;
174
179
  return sid.slice(0, 8) + "…" + sid.slice(-6);
175
180
  }
181
+ function sessionType(r) { return r && r.isSubtask ? "子任务" : "主会话"; }
176
182
  function statusInfo(r) {
177
183
  if (r.status === "completed") return { code: 200, label: "200", cls: "ok", title: "成功" };
178
184
  if (r.status === "max-tokens") return { code: 200, label: "200", cls: "warn", title: "完成(达到输出上限)" };
@@ -407,6 +413,9 @@ const css = `
407
413
  .dtok-empty{text-align:center;color:var(--dsw-alias-label-secondary);padding:32px 0;font-size:13px;}
408
414
  .dtok-sid{color:var(--dk-accent);cursor:pointer;text-decoration:underline dotted;}
409
415
  .dtok-sid:hover{filter:brightness(1.25);}
416
+ .dtok-scope-note{font-size:12px;color:var(--dsw-alias-label-secondary);padding:7px 10px;border-left:3px solid var(--dk-accent);background:var(--dsw-alias-bg-layer-1);border-radius:4px;line-height:1.5;}
417
+ .dtok-session-kind{display:inline-block;margin-left:5px;padding:1px 5px;border-radius:4px;font-size:10px;color:var(--dk-accent);background:rgb(96 165 250 / .12);vertical-align:middle;}
418
+ .dtok-session-tree{font-family:ui-monospace,monospace;}
410
419
  .dtok-code{font-weight:700;font-family:ui-monospace,monospace;}
411
420
  .dtok-code.ok{color:var(--dsw-alias-state-success-primary,#4ade80);}
412
421
  .dtok-code.warn{color:var(--dk-warn);}
@@ -549,6 +558,10 @@ function Detail({ rec, onClose, rate }) {
549
558
  const rateCny = Number(rate) > 0 ? Number(rate) : 7.2;
550
559
  const rows = [
551
560
  ["会话 ID", rec.sessionId],
561
+ ["会话类型", sessionType(rec)],
562
+ ["直接父会话 ID", rec.parentSessionId || "—"],
563
+ ["根会话 ID", rec.rootSessionId || rec.sessionId],
564
+ ["会话层级", String(rec.sessionDepth || 0)],
552
565
  ["时间", fmtTime(rec.time)],
553
566
  ["提供商", rec.provider],
554
567
  ["模型", rec.model],
@@ -993,6 +1006,10 @@ export function TokenLogView(props) {
993
1006
  const [effort, setEffort] = useState(() => (savedFilters && savedFilters.effort) || "");
994
1007
  // 会话入口(chip/深链)带入的 sessionId 优先于暂存条件:下拉框初值即选中该会话
995
1008
  const [sessionId, setSessionId] = useState(() => navSession || (savedFilters && savedFilters.sessionId) || "");
1009
+ // 新入口默认任务累计;用户切到仅本会话后记住选择。宿主 config 是跨浏览器默认值,
1010
+ // 本地 filter 是这台浏览器上次的显式选择;首次没有本地值时采用宿主返回值。
1011
+ const [sessionScope, setSessionScope] = useState(() => (savedFilters && savedFilters.sessionScope) || "tree");
1012
+ const scopeTouchedRef = useRef(!!(savedFilters && savedFilters.sessionScope));
996
1013
  const [dim, setDim] = useState(() => (savedFilters && savedFilters.dim) || "");
997
1014
  const [sortKey, setSortKey] = useState("time");
998
1015
  const [sortDir, setSortDir] = useState("desc");
@@ -1028,8 +1045,8 @@ export function TokenLogView(props) {
1028
1045
 
1029
1046
  // 暂存筛选条件: 任一筛选变化即写入 localStorage, 下次打开恢复同样条件
1030
1047
  useEffect(() => {
1031
- saveFilters({ fromStr, toStr, provider, model, status, effort, sessionId, dim });
1032
- }, [fromStr, toStr, provider, model, status, effort, sessionId, dim]);
1048
+ saveFilters({ fromStr, toStr, provider, model, status, effort, sessionId, sessionScope, dim });
1049
+ }, [fromStr, toStr, provider, model, status, effort, sessionId, sessionScope, dim]);
1033
1050
 
1034
1051
  // 挂载时: 扫描历史后按暂存条件查询(未设置时间则不限制, 显示全部记录)
1035
1052
  useEffect(() => {
@@ -1044,6 +1061,7 @@ export function TokenLogView(props) {
1044
1061
  if (savedFilters.status) q.status = savedFilters.status;
1045
1062
  if (savedFilters.effort) q.effort = savedFilters.effort;
1046
1063
  if (savedFilters.sessionId) q.sessionId = savedFilters.sessionId;
1064
+ if (savedFilters.sessionScope) q.sessionScope = savedFilters.sessionScope;
1047
1065
  if (savedFilters.dim) q.dim = savedFilters.dim;
1048
1066
  }
1049
1067
  // 从会话入口点入时按带入的会话查(优先于暂存条件):打开即出当前会话结果,
@@ -1054,6 +1072,7 @@ export function TokenLogView(props) {
1054
1072
  .then((d) => {
1055
1073
  if (cancel) return;
1056
1074
  setData(d);
1075
+ if (!scopeTouchedRef.current && d && (d.defaultSessionScope === "tree" || d.defaultSessionScope === "session")) setSessionScope(d.defaultSessionScope);
1057
1076
  })
1058
1077
  .catch((e) => { if (!cancel) setErr(String((e && e.message) || e)); })
1059
1078
  .finally(() => { if (!cancel) setLoading(false); });
@@ -1069,10 +1088,11 @@ export function TokenLogView(props) {
1069
1088
  if (status) q.status = status;
1070
1089
  if (effort) q.effort = effort;
1071
1090
  if (sessionId) q.sessionId = sessionId;
1091
+ if (sessionId) q.sessionScope = sessionScope;
1072
1092
  const dimNow = dimOverride !== undefined ? dimOverride : dim;
1073
1093
  if (withDim && dimNow) q.dim = dimNow;
1074
1094
  return q;
1075
- }, [fromStr, toStr, provider, model, status, effort, sessionId, dim]);
1095
+ }, [fromStr, toStr, provider, model, status, effort, sessionId, sessionScope, dim]);
1076
1096
 
1077
1097
  // dimOverride:分组按钮点击时按「即将切换到」的维度立即查询(闭包里的 dim 还是旧值)
1078
1098
  const runQuery = useCallback((dimOverride) => {
@@ -1087,16 +1107,18 @@ export function TokenLogView(props) {
1087
1107
  // 挂载时的首次带入已并入初始查询(sessionId 初值 + 挂载 effect),以 navAt 判同跳过,
1088
1108
  // 避免打开面板时同一条件跑两遍、且挂载查询链路较慢把会话结果覆盖回全量。
1089
1109
  const navAppliedRef = useRef(navAt);
1110
+ const lastNavSessionRef = useRef(navSession);
1090
1111
  useEffect(() => {
1091
- if (!navSession || navAppliedRef.current === navAt) return;
1112
+ if (!navSession || (navAppliedRef.current === navAt && lastNavSessionRef.current === navSession)) return;
1092
1113
  navAppliedRef.current = navAt;
1114
+ lastNavSessionRef.current = navSession;
1093
1115
  setSessionId(navSession);
1094
1116
  setLoading(true); setErr("");
1095
- rpcCall("query", Object.assign({}, buildQ(true), { sessionId: navSession }))
1117
+ rpcCall("query", Object.assign({}, buildQ(true), { sessionId: navSession, sessionScope }))
1096
1118
  .then((d) => { setData(d); setPage(0); })
1097
1119
  .catch((e) => setErr(String((e && e.message) || e)))
1098
1120
  .finally(() => setLoading(false));
1099
- }, [navAt]);
1121
+ }, [navAt, navSession]);
1100
1122
 
1101
1123
  // USD→CNY 汇率: host 返回(默认 7.2, 可被 settings dsh-dock.tokenlog.usdCnyRate 覆盖)。
1102
1124
  // 必须在所有引用它的表达式(cards/summaryRows/detailRows/Detail/exportCsv)之前声明,
@@ -1105,7 +1127,8 @@ export function TokenLogView(props) {
1105
1127
 
1106
1128
  // 重置: 清空所有筛选(时间不选=显示全部记录), 并立即查询
1107
1129
  const resetFilters = useCallback(() => { setFromStr(""); setToStr("");
1108
- setProvider(""); setModel(""); setStatus(""); setEffort(""); setSessionId(""); setDim("");
1130
+ setProvider(""); setModel(""); setStatus(""); setEffort(""); setSessionId(""); setSessionScope("tree"); setDim("");
1131
+ scopeTouchedRef.current = false;
1109
1132
  setLoading(true); setErr("");
1110
1133
  rpcCall("query", {})
1111
1134
  .then((d) => { setData(d); setPage(0); })
@@ -1151,6 +1174,14 @@ export function TokenLogView(props) {
1151
1174
 
1152
1175
  const records = (data && data.records) || [];
1153
1176
  const totals = data && data.totals;
1177
+ const scopeInfo = data && data.sessionScope;
1178
+ const directTotals = data && data.directTotals;
1179
+ const breakdown = (data && data.sessionBreakdown) || [];
1180
+ const childTotals = scopeInfo && scopeInfo.scope === "tree" ? {
1181
+ calls: Math.max(0, (totals && totals.calls || 0) - (directTotals && directTotals.calls || 0)),
1182
+ totalTokens: Math.max(0, (totals && totals.totalTokens || 0) - (directTotals && directTotals.totalTokens || 0)),
1183
+ cost: Math.max(0, (totals && totals.cost || 0) - (directTotals && directTotals.cost || 0)),
1184
+ } : null;
1154
1185
  const sessionIds = (data && data.sessionIds) || [];
1155
1186
  const sorted = useMemo(() => {
1156
1187
  const arr = records.slice();
@@ -1171,12 +1202,12 @@ export function TokenLogView(props) {
1171
1202
 
1172
1203
  const cards = totals ? [
1173
1204
  { v: fmtNum(totals.calls), l: "调用次数" },
1174
- { v: fmtCompact(totals.totalTokens), l: "总 Token" },
1205
+ { v: fmtCompact(totals.totalTokens), l: scopeInfo && scopeInfo.scope === "tree" ? "累计 Token(含子任务)" : "总 Token" },
1175
1206
  { v: fmtCompact(totals.cacheReadTokens), l: "输入(命中)" },
1176
1207
  { v: fmtCompact(totals.inputTokens), l: "输入(未命中)" },
1177
1208
  { v: totals.cacheHitPct + "%", l: "缓存命中率" },
1178
1209
  { v: fmtCompact(totals.outputTokens), l: "输出" },
1179
- { v: fmtCostCny(totals.cost, rateCny), l: "消耗金额(估算·人民币)" },
1210
+ { v: fmtCostCny(totals.cost, rateCny), l: (scopeInfo && scopeInfo.scope === "tree" ? "累计金额" : "消耗金额") + "(估算·人民币)" },
1180
1211
  { v: fmtDuration(totals.llmMs), l: "累计耗时" + (totals.timed ? " (" + totals.timed + "步)" : "") },
1181
1212
  ] : [];
1182
1213
 
@@ -1188,6 +1219,19 @@ export function TokenLogView(props) {
1188
1219
  ? (data.modelsByProvider[provider] || [])
1189
1220
  : (data && data.models) || [];
1190
1221
 
1222
+ const changeScope = (next) => {
1223
+ scopeTouchedRef.current = true;
1224
+ setSessionScope(next);
1225
+ setLoading(true); setErr("");
1226
+ // 先保存跨浏览器默认值,再按新口径查询,避免 query 先读到旧默认值。
1227
+ // 保存失败不阻断本次查询(本地筛选仍生效),但保留可见错误提示。
1228
+ rpcCall("config", { sessionScope: next })
1229
+ .catch((e) => { setErr(String((e && e.message) || e)); })
1230
+ .then(() => rpcCall("query", Object.assign({}, buildQ(true), { sessionScope: next })))
1231
+ .then((d) => { setData(d); setPage(0); })
1232
+ .catch((e) => setErr(String((e && e.message) || e)))
1233
+ .finally(() => setLoading(false));
1234
+ };
1191
1235
  const summaryRows = (data && data.summary || []).map((r) => (
1192
1236
  <tr key={r.key}>
1193
1237
  <td>{r.key}</td><td>{fmtNum(r.calls)}</td><td>{fmtCompact(r.cacheReadTokens)}</td>
@@ -1209,7 +1253,7 @@ export function TokenLogView(props) {
1209
1253
  return (
1210
1254
  <tr key={r.id}>
1211
1255
  <td>{fmtTime(r.time)}</td>
1212
- <td><span className="dtok-sid" title="点击按此会话筛选" onClick={() => { setSessionId(r.sessionId); runQuery(); }}>{shortId(r.sessionId)}</span></td>
1256
+ <td><span className="dtok-sid" title={"会话:" + r.sessionId + (r.parentSessionId ? "\n直接父会话:" + r.parentSessionId : "") + "\n点击按此会话筛选"} onClick={() => { setSessionId(r.sessionId); setLoading(true); setErr(""); rpcCall("query", Object.assign({}, buildQ(true), { sessionId: r.sessionId })).then((d) => { setData(d); setPage(0); }).catch((e) => setErr(String((e && e.message) || e))).finally(() => setLoading(false)); }}>{shortId(r.sessionId)}</span><span className="dtok-session-kind">{sessionType(r)}</span></td>
1213
1257
  <td>{r.provider || "—"}</td>
1214
1258
  <td>{r.model || "—"}</td>
1215
1259
  <td>{fmtNum(r.cacheReadTokens)}</td>
@@ -1245,12 +1289,34 @@ export function TokenLogView(props) {
1245
1289
  <ChartsPanel key={"charts-" + fetchedAt} records={records} rate={rateCny} />
1246
1290
  );
1247
1291
  } else {
1292
+ if (scopeInfo && scopeInfo.sessionId) bodyNodes.push(
1293
+ <div key="scope-note" className="dtok-scope-note">
1294
+ {scopeInfo.scope === "tree"
1295
+ ? "任务累计 = 本会话 + 全部后代子任务;按实际调用 ID 去重,子任务继承的历史不会重复计算。"
1296
+ : "仅统计当前会话自己的调用,不包含派发的子任务。"}
1297
+ {" 本会话 " + fmtCompact(directTotals && directTotals.totalTokens || 0) + " Token"}
1298
+ {childTotals ? " · 子任务 " + fmtCompact(childTotals.totalTokens) + " Token / " + fmtCostCny(childTotals.cost, rateCny) + "(" + scopeInfo.descendantCount + " 个会话)" : ""}
1299
+ {scopeInfo.complete === false ? " · 谱系部分缺失,仅累计已知会话" : ""}
1300
+ </div>
1301
+ );
1248
1302
  if (cards.length) bodyNodes.push(
1249
1303
  // key 带 fetchedAt:每次「手动查询 / 首次加载」拿到新数据时重建一次,KPI 卡重播回弹动画
1250
1304
  <div className={"dtok-cards" + (fetchedAt ? " dtok-pop" : "")} key={"cards-" + fetchedAt}>
1251
1305
  {cards.map((c, i) => <div className="dtok-card" key={c.l} style={{ "--i": String(i) }}><div className="v">{c.v}</div><div className="l">{c.l}</div></div>)}
1252
1306
  </div>
1253
1307
  );
1308
+ if (breakdown.length) bodyNodes.push(
1309
+ <div key="session-sum" className="dtok-section-title">会话用量拆分({breakdown.length} 个有用量的会话)</div>,
1310
+ <div key="session-sum-table" className="dtok-table-wrap">
1311
+ <table className="dtok-table">
1312
+ <thead><tr><th>会话</th><th>类型</th><th>调用</th><th>总 Token</th><th>金额(人民币)</th></tr></thead>
1313
+ <tbody>{breakdown.map((r) => <tr key={r.sessionId}>
1314
+ <td className="dtok-session-tree" title={"会话:" + r.sessionId + (r.parentSessionId ? "\n直接父会话:" + r.parentSessionId : "")}>{r.sessionDepth ? "└ ".repeat(Math.min(r.sessionDepth, 4)) : ""}{shortId(r.sessionId)}</td>
1315
+ <td>{r.sessionId === scopeInfo.sessionId ? "当前会话" : sessionType(r)}</td><td>{fmtNum(r.calls)}</td><td>{fmtCompact(r.totalTokens)}</td><td>{fmtCostCny(r.cost, rateCny)}</td>
1316
+ </tr>)}</tbody>
1317
+ </table>
1318
+ </div>
1319
+ );
1254
1320
  if (summaryRows.length) bodyNodes.push(
1255
1321
  <div key="sum" className="dtok-section-title">统计分组: {dim || "无"} ({summaryRows.length} 组)</div>,
1256
1322
  <div key="sumtab" className="dtok-table-wrap">
@@ -1323,6 +1389,9 @@ export function TokenLogView(props) {
1323
1389
  <select className="dtok-select" value={sessionId} onChange={(e) => setSessionId(e.target.value)}>
1324
1390
  <option value="">全部</option>{opts(sessionIds)}
1325
1391
  </select>
1392
+ {sessionId ? <><label>会话口径</label><select className="dtok-select" value={sessionScope} aria-label="会话用量口径" onChange={(e) => changeScope(e.target.value)}>
1393
+ <option value="tree">任务累计(含子任务)</option><option value="session">仅本会话</option>
1394
+ </select></> : null}
1326
1395
  <label>提供商</label>
1327
1396
  <select className="dtok-select" value={provider} onChange={(e) => { setProvider(e.target.value); setModel("") }}>
1328
1397
  <option value="">全部</option>{opts(data && data.providers)}
@@ -1388,10 +1457,10 @@ function TokenLogHomeStat() {
1388
1457
  return <span>今日 {fmtNum(t.calls)} 次调用 · {fmtCompact(t.totalTokens)} Token · {fmtCostCny(t.cost, snap.rate)}</span>;
1389
1458
  }
1390
1459
 
1391
- // ---------- 会话输入区 chip:显示当前会话总 Token(10s 静默刷新),点击打开功能坞并按该会话筛选 ----------
1460
+ // ---------- 会话输入区 chip:默认显示当前会话+后代子任务累计(10s 静默刷新) ----------
1392
1461
  export function TokenLogChip(props) {
1393
1462
  const sid = (props && props.sessionId) || (props && props.session && props.session.sessionId) || null;
1394
- const [snap, setSnap] = useState({ totals: null, rate: 7.2, err: "" });
1463
+ const [snap, setSnap] = useState({ totals: null, directTotals: null, scope: null, rate: 7.2, err: "" });
1395
1464
  useEffect(() => {
1396
1465
  if (!sid) return;
1397
1466
  let cancel = false;
@@ -1401,8 +1470,8 @@ export function TokenLogChip(props) {
1401
1470
  // 无效请求、不再刷控制台报错。此前会一直重试到页面关闭(实测控制台连续 405)。
1402
1471
  if (cancel || isTokenlogRouteGone()) return null;
1403
1472
  return rpcCall("query", { sessionId: sid })
1404
- .then((d) => { if (!cancel) setSnap({ totals: d && d.totals, rate: (d && d.rateUsdCny) || 7.2, err: "" }); })
1405
- .catch((e) => { if (!cancel) setSnap((s) => ({ totals: s.totals, rate: s.rate, err: String((e && e.message) || e) })); });
1473
+ .then((d) => { if (!cancel) setSnap({ totals: d && d.totals, directTotals: d && d.directTotals, scope: d && d.sessionScope, rate: (d && d.rateUsdCny) || 7.2, err: "" }); })
1474
+ .catch((e) => { if (!cancel) setSnap((s) => ({ ...s, err: String((e && e.message) || e) })); });
1406
1475
  };
1407
1476
  load();
1408
1477
  timer = setInterval(load, 10000);
@@ -1410,6 +1479,10 @@ export function TokenLogChip(props) {
1410
1479
  }, [sid]);
1411
1480
  if (!sid) return null;
1412
1481
  const t = snap.totals;
1482
+ const cumulative = snap.scope && snap.scope.scope === "tree";
1483
+ const own = snap.directTotals;
1484
+ const childTokens = cumulative ? Math.max(0, (t && t.totalTokens || 0) - (own && own.totalTokens || 0)) : 0;
1485
+ const childCost = cumulative ? Math.max(0, (t && t.cost || 0) - (own && own.cost || 0)) : 0;
1413
1486
  const gone = isTokenlogRouteGone();
1414
1487
  // chip 文案用紧凑人民币金额(2 位小数),避免撑爆输入卡工具行;
1415
1488
  // 完整金额在 title 悬浮提示里。
@@ -1426,11 +1499,13 @@ export function TokenLogChip(props) {
1426
1499
  const title = gone
1427
1500
  ? routeGoneMessage() + "\n(可在功能坞里启用「用量记录」)"
1428
1501
  : t
1429
- ? "本会话 " + fmtNum(t.calls) + " 次调用 · " + fmtNum(t.totalTokens) + " Token · " + fmtCostCny(t.cost, snap.rate) + "(估算)\n点击在功能坞查看用量记录"
1502
+ ? (cumulative ? "任务累计(含子任务)" : "仅本会话") + " " + fmtNum(t.calls) + " 次调用 · " + fmtNum(t.totalTokens) + " Token · " + fmtCostCny(t.cost, snap.rate) + "(估算)"
1503
+ + (cumulative ? "\n本会话 " + fmtCompact(own && own.totalTokens || 0) + " Token / " + fmtCostCny(own && own.cost || 0, snap.rate) + " · 子任务 " + fmtCompact(childTokens) + " Token / " + fmtCostCny(childCost, snap.rate) + "(" + snap.scope.descendantCount + " 个会话)" : "")
1504
+ + (cumulative && snap.scope.complete === false ? "\n谱系部分缺失,仅累计已知会话" : "") + "\n点击在功能坞查看用量记录"
1430
1505
  : (snap.err ? snap.err + "\n" : "") + "点击在功能坞查看用量记录";
1431
1506
  // 路由不可用时不做成报错态(红色),它不是错误,是「这个功能当前没开」。
1432
1507
  return (
1433
- <button type="button" className={"dockchip" + (snap.err && !t && !gone ? " err" : "")} title={title} aria-label="会话用量"
1508
+ <button type="button" className={"dockchip" + (snap.err && !t && !gone ? " err" : "")} title={title} aria-label={cumulative ? "任务累计用量(含子任务)" : "本会话用量"}
1434
1509
  onClick={() => openPanel("tokenlog", { sessionId: sid, navAt: Date.now() })}>
1435
1510
  {/* 窄屏只显示这枚小图标:点它进配方看具体数据(title 里是完整数值) */}
1436
1511
  <span className="dockchip-svg" aria-hidden="true">
@@ -1440,7 +1515,7 @@ export function TokenLogChip(props) {
1440
1515
  </span>
1441
1516
  <span className="dockchip-dot" style={{ background: gone ? "var(--dsw-alias-label-tertiary,#8b95ab)" : "var(--dk-warn)" }} />
1442
1517
  {labelIcon ? <span className="dockchip-ic">{labelIcon}</span> : null}
1443
- {hasData ? <span className="dockchip-pre-s">用量 </span> : null}<span className="dockchip-val">{labelMain}</span>{labelExtra ? <span className="dockchip-x">{labelExtra}</span> : null}
1518
+ {hasData ? <span className="dockchip-pre-s">{cumulative ? "累计 " : "用量 "}</span> : null}<span className="dockchip-val">{labelMain}</span>{labelExtra ? <span className="dockchip-x">{labelExtra}</span> : null}
1444
1519
  </button>
1445
1520
  );
1446
1521
  }
@@ -1450,7 +1525,7 @@ export const feature = {
1450
1525
  name: "用量记录",
1451
1526
  order: 110,
1452
1527
  accent: "#fbbf24",
1453
- description: "记录全部 LLM API 调用:秒级时间筛选、Token/费用统计(可配置各模型单价,持久保存并按自填单价计费;多段分时价可限定工作日/周末节假日,内置峰谷计价+官网价目自动同步作兜底)、分组汇总、明细检索与 CSV 导出",
1528
+ description: "记录全部 LLM API 调用:秒级筛选、主任务+后代子任务累计/仅本会话切换、会话用量拆分、Token/费用统计(自定义单价与峰谷价)、分组汇总、明细检索与 CSV 导出",
1454
1529
  css,
1455
1530
  View: TokenLogView,
1456
1531
  HomeStat: TokenLogHomeStat,
package/index.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // 不含任何具体功能逻辑。
9
9
  //
10
10
  // 功能清单(宿主半部;客户端菜单次序由 view 模块的 order 字段决定):
11
- // - modelconfig 模型设置(v0.3.0):模型目录读 + 官方配置写
11
+ // - modelconfig 模型能力(v0.3.0):模型目录读 + 官方配置写
12
12
  // - visionproxy 图片理解代理(v0.3.1):纯文本模型收图自动走视觉模型识别
13
13
  // - balance 模型余额(v0.2.0):各 Provider 账户余额/配额
14
14
  // - tokenlog 用量记录(v0.4.0):LLM 调用记账与统计(移植自 @wycto/dsh-token-usage)
@@ -16,8 +16,8 @@
16
16
  // - notify 任务通知:完成/异常/需确认通知 + 提示音/系统通知/钉钉飞书推送(从任务动画拆出)
17
17
  // - runstate 运行状态:进行中任务与最近完成一览(从任务动画拆出;只读,无配置段)
18
18
  // - tts 语音朗读:把会话回复读出来(浏览器 TTS;宿主半部只管配置 + 共享任务追踪)
19
- // - modelconfig 模型设置:模型目录的输入模态与思考强度(写回官方配置)
20
- // - providerconfig 模型提供商:Provider 增删改 + API Key + 拉取上游模型列表
19
+ // - modelconfig 模型能力:模型目录的输入模态与思考强度(写回官方配置)
20
+ // - providerconfig 模型管理:Provider 增删改 + API Key + 拉取上游模型列表
21
21
  // - mobile-relay 远程访问:账号密码登录的远程入口(网关 + 账号 + 浏览模式目录选择器)
22
22
  import { DockConfig, sendJson, readBody, rejectUntrustedRequest, migrateNotifyConfig, migrateModelsFeatureId, migrateImportedFeatures, migrateImportedSections, bindDockConfig, readDockRoot, mutateDockSection } from './src/host-core.js'
23
23
  import { injectWelcomeAck } from './src/welcome-ack.js'
@@ -31,6 +31,7 @@ import { feature as fNotify } from './features/notify/host.js'
31
31
  import { feature as fRunState } from './features/runstate/host.js'
32
32
  import { feature as fTts } from './features/tts/host.js'
33
33
  import { feature as fMobileRelay } from './features/mobile-relay/host.js'
34
+ import { feature as fMcpConfig } from './features/mcpconfig/host.js'
34
35
 
35
36
  export const name = 'dsh-dock'
36
37
 
@@ -74,6 +75,7 @@ export function apply(ctx, config) {
74
75
  fRunState,
75
76
  fTts,
76
77
  fMobileRelay,
78
+ fMcpConfig,
77
79
  ]
78
80
 
79
81
  // 绑定 Config 镜像(替代已移除的 settings.get);volatile 字段热更时重绑。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-dock",
3
- "version": "0.21.2",
4
- "description": "DeepSeek Harness 功能坞插件(dsh-dock):模块化功能中枢——每个功能一个 features/ 模块(可单独提取成包发布,又可经 dockBridge 装回面板)。含用量记录(LLM 调用记账/费用统计,支持各模型自定义单价、多段分时价与周末/节假日谷价)、模型设置、图片理解代理、模型余额、任务动画(19 种运行动画 + 桌面伙伴 3D 场景)、任务通知(完成/异常/需确认通知、提示音、语音播报可选音色、系统通知、钉钉/飞书推送)、运行状态(进行中任务与最近完成一览)、语音朗读(浏览器 TTS 读回复:回合下方喇叭按钮 + 自动朗读);侧栏入口 + 可拖拽弹窗(最大化/最小化/缩放)。",
3
+ "version": "0.23.0",
4
+ "description": "DeepSeek Harness 功能坞插件(dsh-dock):模块化功能中枢——每个功能一个 features/ 模块(可单独提取成包发布,又可经 dockBridge 装回面板)。含用量记录(LLM 调用记账/费用统计,支持各模型自定义单价、多段分时价与周末/节假日谷价)、模型能力、图片理解代理、模型余额、任务动画(19 种运行动画 + 桌面伙伴 3D 场景)、任务通知(完成/异常/需确认通知、提示音、语音播报可选音色、系统通知、钉钉/飞书推送)、运行状态(进行中任务与最近完成一览)、语音朗读(浏览器 TTS 读回复:回合下方喇叭按钮 + 自动朗读);侧栏入口 + 可拖拽弹窗(最大化/最小化/缩放)。",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "files": [
@@ -43,7 +43,7 @@
43
43
  "scripts": {
44
44
  "build:client": "node scripts/build-client.mjs",
45
45
  "test:client": "node scripts/test-client-views.mjs",
46
- "test:host": "node scripts/test-task-host.mjs && node scripts/test-tokenlog-host.mjs && node scripts/test-balance-host.mjs && node scripts/test-route-trust-host.mjs && node scripts/test-tts-host.mjs && node scripts/test-legacy-import.mjs && node scripts/test-mobile-relay-host.mjs && node scripts/test-mobile-relay.mjs && node scripts/test-welcome-ack.mjs",
46
+ "test:host": "node scripts/test-task-host.mjs && node scripts/test-mcpconfig-host.mjs && node scripts/test-tokenlog-host.mjs && node scripts/test-balance-host.mjs && node scripts/test-route-trust-host.mjs && node scripts/test-tts-host.mjs && node scripts/test-legacy-import.mjs && node scripts/test-mobile-relay-host.mjs && node scripts/test-mobile-relay.mjs && node scripts/test-welcome-ack.mjs",
47
47
  "dev:client": "node scripts/watch-client.mjs",
48
48
  "dev:link": "node scripts/dev-link-deps.mjs"
49
49
  },
package/src/client.jsx CHANGED
@@ -21,8 +21,6 @@ import {
21
21
  import { feature as fTokenlog } from "../features/tokenlog/view.jsx";
22
22
  import { feature as fModelconfig } from "../features/modelconfig/view.js";
23
23
  import { feature as fProviderConfig } from "../features/providerconfig/view.js";
24
- import { feature as fHeartbeat } from "../features/heartbeat/view.js";
25
- import { feature as fTheme } from "../features/theme/view.js";
26
24
  import { feature as fBalance } from "../features/balance/view.js";
27
25
  import { feature as fAnimation } from "../features/animation/view.jsx";
28
26
  import { feature as fNotify } from "../features/notify/view.jsx";
@@ -30,12 +28,13 @@ import { feature as fRunState } from "../features/runstate/view.jsx";
30
28
  import { feature as fTts } from "../features/tts/view.jsx";
31
29
  import { feature as fGames } from "../features/games/view.jsx";
32
30
  import { feature as fMobileRelay } from "../features/mobile-relay/view.jsx";
31
+ import { feature as fMcpConfig } from "../features/mcpconfig/view.js";
33
32
 
34
33
  const name = "dsh-dock";
35
- const DOCK_VERSION = "0.21.2";
34
+ const DOCK_VERSION = "0.23.0";
36
35
 
37
36
  // ---- 内置功能注册表:新功能 = features/<id>/ 加模块 + 这里 import 一行 ----
38
- const BUILTIN_FEATURES = [fTokenlog, fModelconfig, fProviderConfig, fHeartbeat, fTheme, fBalance, fAnimation, fNotify, fRunState, fTts, fGames, fMobileRelay];
37
+ const BUILTIN_FEATURES = [fTokenlog, fModelconfig, fProviderConfig, fMcpConfig, fBalance, fAnimation, fNotify, fRunState, fTts, fGames, fMobileRelay];
39
38
  // 规划占位(路线图):接入后移除并建 features/<id>/ 模块
40
39
  const PLANNED_FEATURES = [];
41
40
  const PLANNED_NOTES = {};
@@ -169,8 +168,10 @@ const SHELL_CSS = [
169
168
  ".dockm-page-wide-btn{flex:none;margin-left:auto;display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-secondary);font-family:inherit;font-size:12px;cursor:pointer;}",
170
169
  ".dockm-page-wide-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary);}",
171
170
  /* 面板页的左侧菜单收窄:给右侧列表/表格让出宽度,别留大片空白 */
172
- ".dockm-page .dockm-nav{width:140px;padding:8px 6px;}",
173
- ".dockm-page .dockm-nav-item{padding:7px 8px;font-size:12.5px;gap:6px;}",
171
+ // 左侧菜单列:内容只有 8px 圆点 + 4 字标签,140px 会留一大条空白(用户反馈「这个宽度可以缩小点」)。
172
+ // 用 border-box 收到 110px(含内距):既够放最长标签「MCP管理 / 远程访问」,又把右侧死区收掉,正文区更宽。
173
+ ".dockm-page .dockm-nav{box-sizing:border-box;width:110px;padding:8px 7px;}",
174
+ ".dockm-page .dockm-nav-item{padding:7px 8px;font-size:12.5px;gap:6px;overflow:hidden;}",
174
175
  ".dockm-page-body>.dockm-body{flex:1;min-height:0;}",
175
176
  ".dockm-page-icon{flex:none;display:flex;align-items:center;justify-content:center;width:34px;height:34px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}",
176
177
  ".dockm-page-titles{min-width:0;}",
package/src/host-core.js CHANGED
@@ -45,6 +45,9 @@ export const DockConfig = z.object({
45
45
  // 折扣、自建端点等),这里保存用户自填单价并优先用于费用估算。
46
46
  // 详见 features/tokenlog/host.js 的 resolvePricing(优先级:自定义 > 官网 > 内置 > 兜底)。
47
47
  tokenlog: z.object({
48
+ /** 会话用量默认口径:tree=当前会话+全部后代子任务;session=仅当前会话。
49
+ * 全局查询(未指定会话)不受此项影响,始终按实际 LLM 调用逐条统计。 */
50
+ sessionScope: z.union([z.const('tree'), z.const('session')]).default('tree'),
48
51
  /** USD→CNY 汇率(金额内部以 USD 记录,界面按人民币展示)。 */
49
52
  usdCnyRate: z.number().default(7.2),
50
53
  /** 是否仍抓取官网刊例价,作为「自定义单价」未命中时的兜底。 */
package/src/shared.js CHANGED
@@ -252,6 +252,11 @@ export function taskActivityAt(task) {
252
252
  /** 任务是否「正在忙」(有在飞的工具调用 / 正在压缩上下文),与耗时无关的那部分信号。 */
253
253
  export function taskBusy(task, now, capMs) {
254
254
  if (!task) return false;
255
+ // PTC(Programmatic Tool Calling / run_code)程序执行期间整体算「在忙」:一次程序会串起若干
256
+ // 子调用(wait_agent 等子代理 / job_output 等后台任务 / bash 长命令 / ask_user_question 等人),
257
+ // 这些子调用可阻塞数分钟且期间零事件,属于在干活/等人,不能按停滞处理。子调用各有自身超时
258
+ // (程序不会无限静默),因此这里不设上限(与「主任务在等子任务」同一口径)。
259
+ if (task.ptcProgram === true) return true;
255
260
  const at = typeof now === "number" ? now : Date.now();
256
261
  const cap = typeof capMs === "number" && capMs > 0 ? capMs : TASK_BUSY_MS;
257
262
  if (task.compacting === true) {
package/src/task-track.js CHANGED
@@ -161,6 +161,8 @@ function createTracker(ctx) {
161
161
  //(isSubtask 由会话头 origin/delegationDepth 异步判定,判定前按主任务处理)
162
162
  isSubtask: false,
163
163
  parentSessionId: '',
164
+ // 主任务标题:子任务结束通知要点名「哪个主任务的哪个子任务」(卡片/语音/群推送共用)
165
+ parentTitle: '',
164
166
  lastToolName: '',
165
167
  // 工具等待用户确认(dsh 会话流 approval/asked):浏览器侧据此弹"需确认"通知
166
168
  approvals: new Map(), // approvalId -> { toolName, reason, askedAt }
@@ -179,6 +181,12 @@ function createTracker(ctx) {
179
181
  compacting: false,
180
182
  compactStartedAt: 0,
181
183
  compactId: '',
184
+ // PTC(Programmatic Tool Calling / run_code)程序执行状态:一次 run_code 会包住若干子调用
185
+ // (wait_agent 等子代理 / job_output 等后台任务 / bash 长命令 / ask_user_question 等人),
186
+ // 子调用执行期间本会话可能长时间零事件——那是在干活/等人,不是卡住。卡住判定据此豁免。
187
+ ptcProgram: false,
188
+ ptcTool: '',
189
+ ptcStartedAt: 0,
182
190
  phase: 'think',
183
191
  phaseAt: Date.now(),
184
192
  lastActivityAt: Date.now(),
@@ -198,6 +206,18 @@ function createTracker(ctx) {
198
206
  s.isSubtask = h.origin === 'subagent'
199
207
  || (typeof h.delegationDepth === 'number' && h.delegationDepth > 0)
200
208
  s.parentSessionId = typeof h.parentSession === 'string' && h.parentSession ? h.parentSession : ''
209
+ // 子任务:顺手解析主任务标题。优先内存里的父会话(常见:主任务还在跑),
210
+ // 没有再问标题服务;都拿不到就留空,结束时 finishSession 还会再兜一次。
211
+ if (s.isSubtask && s.parentSessionId) {
212
+ const liveParent = activeSessions.get(s.parentSessionId)
213
+ if (liveParent && (liveParent.title || liveParent.firstPrompt)) {
214
+ s.parentTitle = liveParent.title || truncate(liveParent.firstPrompt, 60)
215
+ } else {
216
+ readSessionFacts(s.parentSessionId, sessionQuery).then((pf) => {
217
+ if (activeSessions.get(sid) === s && pf.title) s.parentTitle = pf.title
218
+ }).catch(() => { /* 主任务标题读不到:通知退化为不带主任务名 */ })
219
+ }
220
+ }
201
221
  }
202
222
  }).catch(() => { /* 标题/归属读失败:title 走 firstPrompt 兜底,归属按主任务 */ })
203
223
  return record
@@ -210,6 +230,14 @@ function createTracker(ctx) {
210
230
  activeSessions.delete(sid)
211
231
  const endTime = Date.now()
212
232
  const duration = endTime - session.startTime
233
+ // 主任务标题三级兜底:还在跑的父会话(标题可能比子任务晚到,以结束时最新值为准)
234
+ // → 已归档的父会话 → 子任务开始时解析到的标题。都没有就留空(消费方显示「未知」)。
235
+ const liveParent = session.parentSessionId ? activeSessions.get(session.parentSessionId) : null
236
+ const archivedParent = session.parentSessionId && !liveParent
237
+ ? completedSessions.find((r) => r.sessionId === session.parentSessionId) : null
238
+ const parentTitle = liveParent
239
+ ? (liveParent.title || truncate(liveParent.firstPrompt, 60))
240
+ : (archivedParent ? archivedParent.title : (session.parentTitle || ''))
213
241
  const record = {
214
242
  sessionId: sid,
215
243
  title: session.title || truncate(session.firstPrompt, 60) || '(无标题)',
@@ -229,6 +257,11 @@ function createTracker(ctx) {
229
257
  lastText: session.lastText,
230
258
  startTime: session.startTime,
231
259
  endTime,
260
+ // 主/子归属进完成记录:结束通知(卡片/语音/系统通知/群推送)据此区分
261
+ // 「任务完成」与「子任务完成」,并点名是哪个主任务的哪个子任务
262
+ isSubtask: !!session.isSubtask,
263
+ parentSessionId: session.parentSessionId || '',
264
+ parentTitle: parentTitle || '',
232
265
  }
233
266
  completedSessions.unshift(record)
234
267
  if (completedSessions.length > MAX_COMPLETED) completedSessions.pop()
@@ -330,6 +363,32 @@ function createTracker(ctx) {
330
363
  // 调用落地 → 不再有在飞的调用(同一时刻只会有一个工具在跑)
331
364
  s.pendingTool = ''
332
365
  s.toolStartedAt = 0
366
+ // run_code(PTC 程序)整体落地:程序结束,清掉 PTC 忙标记。
367
+ s.ptcProgram = false
368
+ s.ptcTool = ''
369
+ s.ptcStartedAt = 0
370
+ } else if (event.type === 'tool/ptc-dispatch-start' && event.data) {
371
+ // PTC 子调用开始:run_code 程序正在执行某个子工具(wait_agent / job_output / bash /
372
+ // ask_user_question…)。这些子调用可阻塞数分钟(等子代理、等后台任务、等用户回答),
373
+ // 期间本会话零事件——但任务在干活/等人,不是卡住。标记整段 PTC 程序为「在忙」。
374
+ s.ptcProgram = true
375
+ const subName = typeof event.data.name === 'string' ? event.data.name : ''
376
+ s.ptcTool = subName
377
+ s.ptcStartedAt = now
378
+ s.lastMotionAt = now
379
+ // PTC 内的 ask_user_question:与直接 tool/call 一样要能弹「需回答」而不是「卡住」。
380
+ if (subName === 'ask_user_question') {
381
+ const subId = typeof event.data.subCallId === 'string' ? event.data.subCallId : ''
382
+ if (subId) s.questions.set(subId, describeQuestion(event.data.arguments, now))
383
+ }
384
+ } else if (event.type === 'tool/ptc-dispatch' && event.data) {
385
+ // PTC 子调用结束:清掉对应提问挂起项;程序本身可能还有后续子调用(ptcProgram 保持到
386
+ // 外层 run_code 的 tool/result 再清)。
387
+ const subId2 = typeof event.data.subCallId === 'string' ? event.data.subCallId : ''
388
+ if (subId2) s.questions.delete(subId2)
389
+ s.ptcTool = ''
390
+ s.ptcStartedAt = 0
391
+ s.lastMotionAt = now
333
392
  } else if (event.type === 'compaction/start' && event.data) {
334
393
  // 压缩上下文开始:期间会话零事件,但这是**正在干活**。记成在忙,别按停滞算。
335
394
  s.compacting = true
@@ -457,11 +516,16 @@ function createTracker(ctx) {
457
516
  // 卡住播报/卡住卡专用:主/子归属(会话头判定)与最后调用的工具
458
517
  isSubtask: !!s.isSubtask,
459
518
  parentSessionId: s.parentSessionId || '',
519
+ parentTitle: s.parentTitle || '',
460
520
  lastToolName: s.lastToolName || '',
461
521
  approvals: [...s.approvals.entries()].map(([id, v]) => ({ id, ...v })),
462
522
  // 等人回答的提问(ask_user_question 挂起中):与 approvals 同属「等人介入」,
463
523
  // 客户端据此显示「等待回答」而不是「卡住」。
464
524
  questions: [...s.questions.entries()].map(([id, v]) => ({ id, ...v })),
525
+ // PTC(run_code 程序)执行状态:客户端据此把整段程序当「在忙」,避免等待子代理 /
526
+ // 后台任务 / 用户回答期间被误判成「卡住」(见 src/shared.js 的 taskBusy)。
527
+ ptcProgram: !!s.ptcProgram,
528
+ ptcTool: s.ptcTool || '',
465
529
  })
466
530
  }
467
531
  return { now: at, active, recent: completedSessions.slice(0, 20) }
@@ -1,35 +0,0 @@
1
- // dsh-dock · 功能模块【心跳监视】· 客户端视图(纯 Client 功能,无宿主半部)
2
- import react from "react";
3
-
4
- // 面板加载时刻:心跳视图与首页总揽共用的运行时长基准(同一数字,不分谁先挂载)
5
- const loadedAt = Date.now();
6
- function uptimeText() {
7
- const sec = Math.max(0, Math.floor((Date.now() - loadedAt) / 1000));
8
- const m = Math.floor(sec / 60);
9
- return "面板已运行 " + (m > 0 ? m + " 分 " : "") + (sec % 60) + " 秒";
10
- }
11
-
12
- function HeartbeatView(props) {
13
- const ctx = props && props.ctx;
14
- const [txt, setTxt] = react.useState(uptimeText());
15
- react.useEffect(() => (ctx && typeof ctx.interval === "function" ? ctx.interval(() => setTxt(uptimeText()), 1000) : undefined), []);
16
- return react.createElement("div", null, txt);
17
- }
18
-
19
- function HeartbeatStat(props) {
20
- const ctx = props && props.ctx;
21
- const [txt, setTxt] = react.useState(uptimeText());
22
- react.useEffect(() => (ctx && typeof ctx.interval === "function" ? ctx.interval(() => setTxt(uptimeText()), 1000) : undefined), []);
23
- return react.createElement("span", null, txt);
24
- }
25
-
26
- export const feature = {
27
- id: "heartbeat",
28
- name: "心跳监视",
29
- order: 140,
30
- accent: "#34d399",
31
- description: "示例功能:面板侧运行时长心跳(纯 Client)",
32
- defaultEnabled: false,
33
- View: HeartbeatView,
34
- HomeStat: HeartbeatStat,
35
- };