balance-dsh 2.1.4 → 2.1.5

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.
Files changed (3) hide show
  1. package/lib/client.js +455 -85
  2. package/lib/index.js +662 -86
  3. package/package.json +1 -1
package/lib/client.js CHANGED
@@ -168,6 +168,12 @@ window.__ModuleLoader__.load({
168
168
  din 会直接叠在 dout 上,数字糊成一团。 */
169
169
  .balance-footer__dout{animation:balance-roll-out .42s linear both}
170
170
  .balance-footer__din{animation:balance-roll-in .42s linear both}
171
+ /* 会话消耗行的纠正滚动走快档(2026-11-02:「最多因为计算纠正之后数值跳动了一下 也很快啊」)。
172
+ 口径:数字先按本地投影立刻显示,服务端的逐时段分桶到了才滚一下纠正 —— 那一下是"订正",
173
+ 不是"出场秀",所以只给 .24s,错位也从 38ms×4 收到 24ms×3(总 312ms,比原来短一半)。
174
+ 余额胶囊与今日金额不走快档:它们的刷新有语义(手动白光 / 轮询滚动),慢一点才对得上。 */
175
+ .balance-footer__roll--quick .balance-footer__dout,
176
+ .balance-footer__roll--quick .balance-footer__din{animation-duration:.24s}
171
177
  /* ⚠️ 全程 opacity:1,只靠位移互补 —— 不要再用「先淡出再淡入」那套。
172
178
  旧写法是 out 到 60% 淡成 0、in 前 40% 保持 0,中间有约 160ms 两格都看不见,
173
179
  逐帧看就是「数字缺失/位置异常一下」。会话消耗因为变化频率低不显眼,
@@ -826,6 +832,11 @@ window.__ModuleLoader__.load({
826
832
  所以宽高一起固定 —— inline-flex + align-items:center + height:1lh(= 继承的行高,
827
833
  跟随 DSH 字号设置走),待算与算完两态的高度完全一致。 */
828
834
  .balance-usage-cost{white-space:nowrap;font-variant-numeric:tabular-nums;display:inline-flex;align-items:center;min-width:10.6ch;height:20px;height:1lh}
835
+ /* 拿不到分桶时的占位(4 秒兜底之后):一条短横线,**不进逐位滚动结构**。
836
+ 滚格子按「小数点对齐」拆字符,遇到非数字会把它中间那个小数点单独留成一格,
837
+ 加上两侧空位就拼出 下划线-点-下划线 那种碎片(用户 2026-11-02 抓到过一瞬间)。
838
+ 这里给一点透明度,读起来是「算不出来」而不是「钱是 0」。 */
839
+ .balance-usage-dash{opacity:.62}
829
840
  .balance-usage-cost--pending{opacity:1}
830
841
  /* 智能体团队(Agent Teams)小圆片:只在 roster 里有人时才挂。
831
842
  高度 16px(行高 22px,纵向放得下、不会把整行撑高),字号 11px 跟随 DSH 的次要信息档;
@@ -1419,14 +1430,36 @@ window.__ModuleLoader__.load({
1419
1430
  return pricing;
1420
1431
  }
1421
1432
 
1422
- function computeCost(usage, p) {
1423
- const input =
1424
- ((usage.uncachedInputTokens ?? 0) * p.inputCnyPerMillion +
1425
- (usage.cacheReadTokens ?? 0) * p.cacheReadCnyPerMillion +
1426
- (usage.cacheWriteTokens ?? 0) * p.cacheWriteCnyPerMillion) /
1427
- 1_000_000;
1428
- const output = ((usage.outputTokens ?? 0) * p.outputCnyPerMillion) / 1_000_000;
1429
- return input + output;
1433
+ /** 按模型取定价 —— **只取定价,不查余额**(2026-11-02:「快速切换对话会导致对话加载速度异常」)。
1434
+ *
1435
+ * 原来切会话走的是 `fetchBalanceData()`,而 `/balance-api`(不带 lite)每次都会真去查
1436
+ * **官方余额**:实测 `?model=…` 285ms / `?lite=1` 1ms。快速点 5 个对话就是 5 次余额往返排队,
1437
+ * 每一次都在和用户真正在看的那个会话抢同一条线程。
1438
+ * 定价只跟**模型**有关、跟会话无关,而且一个模型的价格在一次运行里不会变 —— 按模型记 10 分钟,
1439
+ * 同一模型下切多少个对话都是 0 次请求。
1440
+ * ⚠️ 走 `lite=1`:服务端会跳过 resolveBalance,只回 pricing。 */
1441
+ const pricingByModel = new Map(); // model -> { at }
1442
+ const PRICING_MODEL_TTL_MS = 10 * 60 * 1000;
1443
+ let pricingModelInFlight = null; // model,同一时刻只问一个
1444
+ async function ensurePricingForModel(model) {
1445
+ if (typeof model !== "string" || model === "") return;
1446
+ const hit = pricingByModel.get(model);
1447
+ if (hit && Date.now() - hit.at < PRICING_MODEL_TTL_MS) return; // 命中:连请求都不发
1448
+ if (pricingModelInFlight === model) return; // 同一模型正在问,别再发一份
1449
+ pricingModelInFlight = model;
1450
+ try {
1451
+ const res = await fetch("/balance-api?lite=1&model=" + encodeURIComponent(model));
1452
+ if (!res.ok) return;
1453
+ const data = await res.json();
1454
+ if (data && data.ok && data.pricing) {
1455
+ setPricing(data.pricing);
1456
+ pricingByModel.set(model, { at: Date.now() });
1457
+ }
1458
+ } catch {
1459
+ // 拿不到就继续用 DEFAULT_PRICING,不阻断任何东西
1460
+ } finally {
1461
+ if (pricingModelInFlight === model) pricingModelInFlight = null;
1462
+ }
1430
1463
  }
1431
1464
 
1432
1465
  /** 分时段金额:优先按服务端已标注的各模型 cost 累加(byModel);
@@ -1693,7 +1726,11 @@ window.__ModuleLoader__.load({
1693
1726
  serverModelProbeAt.set(sessionId, now);
1694
1727
  capSessions(serverModelProbeAt);
1695
1728
  try {
1696
- const res = await fetch("/balance-api?session=" + encodeURIComponent(sessionId));
1729
+ // ⚠️ 必须带 `lite=1`(2026-11-02「快速切换对话会导致对话加载速度异常」):
1730
+ // 不带它时服务端会顺带 `resolveBalance()` —— 一次官方余额往返,实测 **238ms**,
1731
+ // 带 lite 只要 **9ms**,而 `model` 字段照常返回(只是检测会话里的模型,跟余额无关)。
1732
+ // 这条在「每进一个新对话」时都会发一次,连点几个对话就叠成几百毫秒的排队。
1733
+ const res = await fetch("/balance-api?lite=1&session=" + encodeURIComponent(sessionId));
1697
1734
  if (!res.ok) return "";
1698
1735
  const data = await res.json();
1699
1736
  return data && data.ok && typeof data.model === "string" ? data.model : "";
@@ -1702,12 +1739,73 @@ window.__ModuleLoader__.load({
1702
1739
  }
1703
1740
  }
1704
1741
 
1742
+ /** 「服务端这一趟没给数据」的重试节奏(2026-11-02 第三轮)。
1743
+ * 用户报「从消耗量很大的对话切到消耗量很小的对话还是会加载时长异常」——
1744
+ * 真凶不是请求慢(实测 `?lite=1&session=` 7~20ms),而是**一次 null 就再没人问**:
1745
+ * `?session=` 可能因为「会话还在被 DSH 装载 / 读盘被 4s 节流 / 本趟读失败」返回 `usage: null`,
1746
+ * 客户端把这条空结果当成品写进 `splitMap`,去重记录也留着;小对话的 `usageKey` 之后不再变化,
1747
+ * 于是**永远没人重问** → 没有精确值 → 迷雾一直盖到 4 秒兜底才散,看起来就是「加载时长异常」。
1748
+ * 大对话边流式边变 `usageKey`,所以它反而不会卡 —— 这就是用户感觉到的「只有小对话慢」。
1749
+ * 现在:null 结果按 [400, 900, 1800]ms 重试三次,去重记录同步撤掉;
1750
+ * 三次都没拿到才允许收雾显示 `≈ ¥—`(见 costStuck 的第二个条件)。 */
1751
+ const SPLIT_NULL_RETRY_DELAYS = [400, 900, 1800];
1752
+ // 「服务端正在被 DSH 装载、插件主动让路」时的补拉节奏(2026-11-02 第四轮)。
1753
+ // 用户那句「我说的是加载对话历史 是聊天记录」指的是 DSH 自己的「载入历史…」——
1754
+ // 那个窗口里插件绝不能再去解压同一个文件。所以这时**不许**用 400ms 的快重试,
1755
+ // 改成 [1200, 2500, 4000]ms 慢拍:DSH 装好(实测 0.3~0.9s)后那一次就是 live 数据、0 磁盘。
1756
+ const SPLIT_LOADING_RETRY_DELAYS = [1200, 2500, 4000];
1757
+ const splitNullRetryCount = new Map();
1758
+ // 让路补拉单独一本账(2026-11-02 第五轮之三)。混用 `splitNullRetryCount` 会让一轮
1759
+ // 6 秒的让路把 400/900/1800 那三次快补全吃掉,等让路结束反而直接撞 `≈ ¥—`。
1760
+ const splitLoadingRetryCount = new Map();
1761
+ const splitRetryKeyOf = (sessionId, tokens) => sessionId + "\u0000" + tokens;
1762
+ /** `splitMap` 里的条目到底算不算「有数」——判定与 `splitUsable` 同口径。
1763
+ * ⚠️ 去重判据必须用它、不能用「键存在」:`{usage: null}` 也是存在的键。 */
1764
+ function splitEntryUsable(entry) {
1765
+ if (entry == null || entry.usage == null) return false;
1766
+ return (Array.isArray(entry.usage.byModel) && entry.usage.byModel.length > 0)
1767
+ || (entry.usage.totalTokens ?? 0) > 0;
1768
+ }
1769
+
1770
+ /** 「这条请求是被我们主动取消的」—— 与「请求失败(网络/后端异常)」必须分开:
1771
+ * 取消是正常的(用户切走了),**不许写 `{usage:null}` 占位**、也不许留着去重记录;
1772
+ * 失败才要写占位。
1773
+ * 2026-11-02 用户明确要求:「切换对话的时候 上一个消耗没加载出来就停止上一个对话的消耗加载
1774
+ * 就是只加载当前对话的消耗 其他所有点击过的并且没有加载出来的就直接停止终止加载」。 */
1775
+ const SESSION_USAGE_ABORTED = Symbol("session-usage-aborted");
1776
+ /** 当前在飞的 `?session=` 请求:`{ sessionId, controller }`。全局只留一条 ——
1777
+ * 用户要的语义就是「只加载当前对话的消耗」,所以新请求起飞前先把别的会话那条掐掉。 */
1778
+ let sessionUsageInFlight = null;
1779
+ function abortOtherSessionUsage(keepSessionId) {
1780
+ const cur = sessionUsageInFlight;
1781
+ if (!cur || cur.sessionId === keepSessionId) return;
1782
+ sessionUsageInFlight = null;
1783
+ try {
1784
+ cur.controller.abort();
1785
+ } catch {
1786
+ // abort 自身失败无所谓,下面照常把去重记录撤掉
1787
+ }
1788
+ }
1789
+
1705
1790
  /** 拉取指定会话的分时段 usage 及子代理 usage(/balance-api?session=...),失败返回 null。
1706
- * 服务端会顺带回一个 `today`(利用本次已解压的事件现算),用它做「今日消耗」的实时刷新。 */
1707
- async function fetchSessionUsage(sessionId) {
1791
+ * 服务端会顺带回一个 `today`(利用本次已解压的事件现算),用它做「今日消耗」的实时刷新。
1792
+ * `signal` 是「切走就终止」的取消通道(见 SESSION_USAGE_ABORTED 那段注释)。 */
1793
+ async function fetchSessionUsage(sessionId, signal) {
1708
1794
  if (typeof sessionId !== "string" || sessionId === "") return null;
1709
1795
  try {
1710
- const res = await fetch("/balance-api?session=" + encodeURIComponent(sessionId));
1796
+ // ⚠️ **必须带 `lite=1`(2026-11-02:用户报「加载运行的对话很慢」)**。
1797
+ // 不带它时服务端还会顺手 `resolveBalance()` —— 那是一条**官方账号的网络往返**,
1798
+ // 本机实测 150~420ms。消耗行要的只是「这个对话用了多少 token」,跟账户余额毫无关系,
1799
+ // 却每次都得排在那条网络请求后面:实测 `?session=` 184~328ms,`?lite=1&session=` 41ms。
1800
+ // 流式输出时这条每 600ms 跑一次,白等的时间直接就是「数字出得慢」。
1801
+ // 余额由 60 秒轮询 / 对话完成刷新那条独立的请求负责,两件事不该互相拖累。
1802
+ // `today=1` 则保留:今日的实时值就是靠这条响应带回来的(客户端 raiseTodayFromSession)。
1803
+ // ⚠️ `signal` 是「切走就终止」的取消通道(2026-11-02 用户第二轮要求):
1804
+ // 切到别的对话时,上一个对话还没出数的这一条请求立刻 abort —— 只加载当前对话的消耗。
1805
+ // abort 之后由调用处**撤销去重记录**,所以点回去会重新问,不会永久停在加载态。 */
1806
+ const res = await fetch("/balance-api?lite=1&today=1&session=" + encodeURIComponent(sessionId), {
1807
+ signal,
1808
+ });
1711
1809
  if (!res.ok) return null;
1712
1810
  const data = await res.json();
1713
1811
  if (!data || !data.ok) return null;
@@ -1719,8 +1817,17 @@ window.__ModuleLoader__.load({
1719
1817
  // 「有团队才启动」的补拉全被同一个自锁卡死,整个团队 UI 等于死代码。
1720
1818
  team: data.team && typeof data.team === "object" ? data.team : null,
1721
1819
  today: data.today && typeof data.today === "object" ? data.today : null,
1820
+ // ⚠️ **必须转发 `loading`**(2026-11-02 第五轮之三,实测抓到的真 bug):
1821
+ // 服务端在「DSH 正在装载这个会话」时会主动让路,回 `usage: null` + `loading: true`。
1822
+ // 下面的重试分支读的正是 `u.loading`,这一层漏掉它 → `serverLoading` 恒为 false →
1823
+ // `SPLIT_LOADING_RETRY_DELAYS`(1200/2500/4000) 变成死代码,客户端仍用 400/900/1800
1824
+ // 的快拍去砸那个正在解压 65 MB 的窗口,并且 3 次快拍不到 2 秒就用光预算 →
1825
+ // 让路还没结束就先显示 `≈ ¥—`。用户说「怎么还是这样啊」,根子在这一行。
1826
+ loading: data.loading === true,
1722
1827
  };
1723
- } catch {
1828
+ } catch (err) {
1829
+ // 被我们主动取消:**不是失败**,调用处要拿它来区分「别写占位、别记去重」。
1830
+ if (err && (err.name === "AbortError" || err.code === 20)) return SESSION_USAGE_ABORTED;
1724
1831
  return null;
1725
1832
  }
1726
1833
  }
@@ -1840,6 +1947,17 @@ window.__ModuleLoader__.load({
1840
1947
  * 每位自身仍是 linear 420ms、位移分毫不差,所以不会退回「快到位置时发虚」。 */
1841
1948
  const ROLL_STAGGER_MS = 38;
1842
1949
  const ROLL_STAGGER_MAX = 4;
1950
+ // 纠正滚动(会话消耗行专用):订正比出场更需要"马上到位",错位收一半。
1951
+ const COST_ROLL_STAGGER_MS = 24;
1952
+ const COST_ROLL_STAGGER_MAX = 3;
1953
+ /** 加载迷雾的最短可见时长(毫秒)。
1954
+ *
1955
+ * 2026-11-02 用户:「我要的是之前一样的动画」。之前那版雾能看清,是因为 `?session=`
1956
+ * 本身要 254~310ms(还搭着余额的网络往返);现在消耗行走 `lite=1`、服务端 40ms 就回来,
1957
+ * 雾会**一闪而过**,看起来跟没有一样。给它一个下限,把当时的手感原样还原。
1958
+ * ⚠️ 只按「会话切换」起算,流式刷新绝不重播(那样很割裂,2026-10-31 定过)。
1959
+ * 300ms 是下限不是固定等待:请求更慢时雾跟着更久,跟以前一样。 */
1960
+ const COST_FOG_FLOOR_MS = 300;
1843
1961
  // 滚动播完后给 roll 打 done 标记(2026-10-31 方案 3 补充)。
1844
1962
  // 为什么必须做:`dout`/`din` 上的 animation 是常驻声明,只要它还在,
1845
1963
  // 元素经历 display:none → 有盒子时浏览器会取消并重建动画,从 0 秒重播。
@@ -1858,18 +1976,20 @@ window.__ModuleLoader__.load({
1858
1976
  }, [roll, setRoll]);
1859
1977
  }
1860
1978
 
1861
- function renderRollCells(cells, prefix, settled) {
1979
+ function renderRollCells(cells, prefix, settled, quick) {
1862
1980
  // 先按从右往左给「会滚的格子」编号:最右边的滚动格延迟 0
1863
1981
  const total = cells.length;
1982
+ const staggerMs = quick === true ? COST_ROLL_STAGGER_MS : ROLL_STAGGER_MS;
1983
+ const staggerMax = quick === true ? COST_ROLL_STAGGER_MAX : ROLL_STAGGER_MAX;
1864
1984
  return jsx.jsx("span", {
1865
- className: "balance-footer__roll",
1985
+ className: "balance-footer__roll" + (quick === true ? " balance-footer__roll--quick" : ""),
1866
1986
  children: cells.map((cell, i) => {
1867
1987
  if (!cell.changed) {
1868
1988
  return jsx.jsx("span", { className: "balance-footer__dcell", children: cell.to === ROLL_EMPTY ? "\u00a0" : cell.to }, prefix + i);
1869
1989
  }
1870
1990
  const fromRight = total - 1 - i;
1871
- const step = Math.min(fromRight, ROLL_STAGGER_MAX);
1872
- const delay = step * ROLL_STAGGER_MS;
1991
+ const step = Math.min(fromRight, staggerMax);
1992
+ const delay = step * staggerMs;
1873
1993
  const style = delay > 0 ? { animationDelay: delay + "ms" } : undefined;
1874
1994
  return jsx.jsxs("span", {
1875
1995
  // 新值是空位(位数减少)时加 --gone:滚完自己收成 0 宽,否则尾巴多一格,
@@ -2374,7 +2494,10 @@ const CN_CALENDAR_SOURCES = [
2374
2494
  }
2375
2495
  /** 按当前时段调整价格:高峰 × 倍率、空闲原价。
2376
2496
  * ⚠️ p 必须是**目录价**(服务端 pricing 字段即目录价);倍率来自设置的 peakMultiplier,
2377
- * 若服务端传来的价已含倍率,这里会再乘一次造成金额虚高。 */
2497
+ * 若服务端传来的价已含倍率,这里会再乘一次造成金额虚高。
2498
+ * ⚠️ 2026-11-02 起**没有任何调用点**(它就是「兜底投影整段乘当前倍率」那半个实现,
2499
+ * 兜底投影已删除,见 UsageCostLine 里 `costResolved` 那段)。留着当工具函数,
2500
+ * **绝不许**再拿它去乘整段 usage——那正是「空闲时段会话虚高 2 倍」的来源。 */
2378
2501
  function periodAdjustedPricing(p, multiplier = 2) {
2379
2502
  if (currentPeriod() !== "peak") return p;
2380
2503
  return {
@@ -2686,7 +2809,16 @@ const CN_CALENDAR_SOURCES = [
2686
2809
  if (!res.ok) return todayCache.value;
2687
2810
  const data = await res.json();
2688
2811
  if (data && typeof data.today === "object" && data.today !== null) {
2689
- todayCache.value = data.today;
2812
+ // ⚠️ 同日不许往小退(2026-11-02,与服务端 mergeTodayMax 同一条规则)。
2813
+ // `?today=1` 走的是持久化文件口径,当前对话还没落盘的那一截它看不见 ——
2814
+ // 于是「先按实时值显示 1.57、一个全量返回又退回 1.06」这种回退会周期性发生,
2815
+ // 看着就是今日金额自己在往回跳。两个来源都是真值的下界,取较大者即可。
2816
+ const prevToday = todayCache.value;
2817
+ todayCache.value = prevToday !== null
2818
+ && prevToday.date === data.today.date
2819
+ && Number(prevToday.cost ?? 0) > Number(data.today.cost ?? 0)
2820
+ ? { ...prevToday, provisional: true }
2821
+ : data.today;
2690
2822
  todayCache.at = Date.now();
2691
2823
  const partial = data.todayPartial === true && todayCache.retries < 3;
2692
2824
  todayCache.ttl = partial ? 3000 : 20000;
@@ -2726,6 +2858,42 @@ const CN_CALENDAR_SOURCES = [
2726
2858
  })();
2727
2859
  return todayCache.inFlight;
2728
2860
  }
2861
+ /** 用 `?session=` 响应里的今日值**立即向上抬一次**(2026-11-02)。
2862
+ *
2863
+ * 为什么需要:`?today=1` 走的是**持久化文件**口径,当前对话在内存里、还没被 DSH 落盘
2864
+ * 的那一截它看不见 —— 冷启动那一刻磁盘上今天还是空的,于是今日显示 ¥0.0000,
2865
+ * 而真实消耗早就产生了(用户 2026-11-02:「今日好像在今日第一次打开的时候消耗不计算」)。
2866
+ * 服务端在 `?session=` 里顺手把「含实时事件的今日桶」算出来了,传上来却只被当成
2867
+ * "去补拉一次" 的开关(还要等 20 秒 TTL 过期才真的发请求),等于白算。
2868
+ *
2869
+ * 规则(全部必要):
2870
+ * · **只抬不降**:两个来源都是真值的下界,当日消耗只增不减。任何"降"都只会是
2871
+ * 更旧的口径(磁盘落后),显示上宁高不低。
2872
+ * · **同日才抬**:跨天由 `?today=1` 说了算,别把昨天的数字搬到今天。
2873
+ * · **不动 `at` / `ttl`**:那本账管的是 `?today=1` 的补拉节奏,动了会让
2874
+ * "其余会话的更新"永远等不到,今日就只剩当前会话那一桶。
2875
+ * · 采纳即 `settled = true`:手上已经有一个服务端给的确切数字,不必再挂等待态。
2876
+ */
2877
+ function raiseTodayFromSession(today) {
2878
+ if (today == null || typeof today.cost !== "number" || !Number.isFinite(today.cost)) return;
2879
+ const prev = todayCache.value;
2880
+ if (prev !== null) {
2881
+ if (prev.date !== today.date) return;
2882
+ if (!(today.cost > Number(prev.cost ?? 0))) {
2883
+ // 值没变大也说明「服务端确实算过今天」——把等待态撤掉即可,别改数字。
2884
+ if (!todayCache.settled) {
2885
+ todayCache.settled = true;
2886
+ notifyToday();
2887
+ }
2888
+ return;
2889
+ }
2890
+ }
2891
+ todayCache.value = today;
2892
+ todayCache.tried = true;
2893
+ todayCache.settled = true;
2894
+ notifyToday();
2895
+ }
2896
+
2729
2897
  // 「今日」金额不和插件一起加载:插件本体(余额行 / 指针 / 色带)先渲染出来,
2730
2898
  // **等余额真的到位**之后才去问今日(用户 2026-10-31:打开 DSH 时先加载插件,
2731
2899
  // 加载完再加载今日消耗)。
@@ -2743,7 +2911,13 @@ const CN_CALENDAR_SOURCES = [
2743
2911
  // 发 fetch 不耗 CPU,真正贵的是服务端解压(同步 CPU,35 MB 会话单次 723 ms)。
2744
2912
  // 曾经是 600ms,用户 2026-10-31 直接问「为什么本对话消耗加载这么慢」:
2745
2913
  // 那 600ms 纯属空等,把同一件迟早要做的事往后推了半秒。
2746
- const SESSION_USAGE_DELAY_MS = 80;
2914
+ // ⚠️ 2026-11-02 从 80 调到 240:「快速切换对话会导致对话加载速度异常」。
2915
+ // 80ms 下每次点击都会真的发出 `?lite=1&session=`,连点 5 个对话就是 5 个**冷会话解压**
2916
+ // (实测单次 350~900ms 同步 CPU,插件与 DSH 同进程 → 界面掉帧、最后那个对话反而最慢)。
2917
+ // 240ms 让「连续点」期间的 timer 全部被 cleanup 掉,只有停下来的那个会话发请求。
2918
+ // 这个延迟**不会让数字变晚**:迷雾本身就有 300ms 最短可见时长(COST_FOG_FLOOR_MS),
2919
+ // 而 `costPending` 会一直盖到响应回来为止。
2920
+ const SESSION_USAGE_DELAY_MS = 240;
2747
2921
 
2748
2922
  /** 「今日」金额的显示精度:数额越小位数越多,大了就逐级省略。
2749
2923
  * 用户 2026-10-31:如果数额小可以显示到小数点后 4 位,越大就相应省略一位。
@@ -4124,9 +4298,12 @@ function makeTodayFlowStyle() {
4124
4298
  closeTimer.current = null;
4125
4299
  setStatsClosing(false);
4126
4300
  setStatsOpen(false);
4127
- // 双击:在应用内打开官方用量页(官方版自带内嵌浏览器;旧版回退系统浏览器)
4128
- // 双击:打开官方用量页(官方版用带平台凭据的原生视口,无需网页登录)
4129
- openPlatformOrUrl("usage", USAGE_URL);
4301
+ // 双击:打开官方用量页 —— 一律交系统默认浏览器(见 openPlatformOrUrl)。
4302
+ // ⚠️ 参数只能传 URL(2026-11-02 用户:「双击余额的检查官方用量怎么没了」)。
4303
+ // 这里曾经写成 `openPlatformOrUrl("usage", USAGE_URL)` —— 函数只有一个形参,
4304
+ // 于是真正被打开的是相对地址 "usage"(会解析成 127.0.0.1:xxxx/usage),
4305
+ // 双击看起来毫无反应。USAGE_URL 才是要传的那个。
4306
+ openPlatformOrUrl(USAGE_URL);
4130
4307
  };
4131
4308
  // 余额元素的交互。悬停提示不用原生 title,统一走主题化浮层(见 withPanel)。
4132
4309
  // 余额元素的交互。悬停提示不用原生 title,统一走主题化浮层(见 withPanel)。
@@ -4949,6 +5126,9 @@ function UsageCostLine({ useProjection, sessionId }) {
4949
5126
  // 存成表而不是单值:来回切会话时命中缓存,立刻就是正确金额,不闪。
4950
5127
  const SPLIT_CACHE_MAX = 32;
4951
5128
  const [splitMap, setSplitMap] = react.useState(() => ({}));
5129
+ // 「空结果重试」的踢腿计数器:+1 就让下面那个请求 effect 重跑一拍。
5130
+ // 值本身没意义,只用作依赖里的触发信号(真正的重试次数记在模块级 splitNullRetryCount)。
5131
+ const [splitRetryGen, setSplitRetryGen] = react.useState(0);
4952
5132
  // splitMap 的镜像:下面那个请求 effect 需要知道「这个会话问过没有」来决定用
4953
5133
  // 首挂载延迟还是 debounce 延迟,但直接把 splitMap 放进依赖会让每次响应都重跑 effect
4954
5134
  // (响应 → setSplitMap → effect 重跑 → 再请求),死循环。用 ref 读当前值。
@@ -5006,16 +5186,17 @@ function UsageCostLine({ useProjection, sessionId }) {
5006
5186
  // 而那条接口每次都要真去查官方余额(实测 419ms)。一个十秒回复能把官方接口打几十次,
5007
5187
  // 服务端排队后整体变慢 —— 用户 2026-10-31 就是问这个:「以前没这么慢的啊」。
5008
5188
  // 现在用 ref 记住"已经为哪个会话的哪个模型刷过定价",只有模型真的换了才重发。
5189
+ // ⚠️ 2026-11-02:这里**不许**再调 `fetchBalanceData()`(切会话 = 一次官方余额往返,285ms)。
5190
+ // 定价按模型缓存,切会话命中缓存时零请求;余额由 60 秒轮询 / 对话完成那条独立负责。
5009
5191
  const pricingModelRef = react.useRef("");
5010
5192
  react.useEffect(() => {
5011
5193
  let disposed = false;
5012
5194
  resolveSessionModel(sessionId).then((resolved) => {
5013
5195
  if (disposed || resolved === "") return;
5014
- // key 里带 sessionId:切会话时即使模型名相同也要重新取一次定价
5015
- const stamp = String(sessionId) + "\u0000" + resolved;
5196
+ const stamp = String(resolved);
5016
5197
  if (pricingModelRef.current === stamp) return;
5017
5198
  pricingModelRef.current = stamp;
5018
- fetchBalanceData().catch(() => {});
5199
+ void ensurePricingForModel(resolved);
5019
5200
  });
5020
5201
  return () => {
5021
5202
  disposed = true;
@@ -5184,8 +5365,15 @@ function UsageCostLine({ useProjection, sessionId }) {
5184
5365
  // → costPending 恒为 true → 本会话消耗永久停在加载动画。
5185
5366
  // 重挂本身是常态,所以这个 bug 看起来「不知道怎么复现」,其实只要重挂就中。
5186
5367
  // 补上 haveResult 之后:结果丢了就重问一次,代价只是那一次解压。
5187
- const haveSplitResult = Object.prototype.hasOwnProperty.call(splitMapRef.current, sessionId);
5188
- if (usageAskedMap.get(sessionId) === usageKey && haveSplitResult) return;
5368
+ // ⚠️ 2026-11-02 再收一格:**「有键」不算「有数」**。服务端偶尔回 `usage: null`
5369
+ // (会话还在被 DSH 装载 / 读盘节流 / 本趟读失败),旧判据会把这条空结果当成"问过了",
5370
+ // 而小对话的 `usageKey` 之后不再变化 → 永远不再问 → 迷雾一直盖到 4 秒兜底。
5371
+ // 现在只有「真的能算出金额的条目」才算问过,空结果一律允许重问。
5372
+ const haveUsableSplit = splitEntryUsable(splitMapRef.current[sessionId]);
5373
+ if (usageAskedMap.get(sessionId) === usageKey && haveUsableSplit) return;
5374
+ // 这一拍是不是「空结果重试」(2026-11-02 第三轮):重试不该再吃 600ms 的流式 debounce,
5375
+ // 否则 [400,900,1800] 再加上 600 就变成 1 秒起步、三次跑完近 5 秒 —— 又成了「加载很久」。
5376
+ const pendingRetry = (splitNullRetryCount.get(splitRetryKeyOf(sessionId, usageKey)) ?? 0) > 0;
5189
5377
  let disposed = false;
5190
5378
  // `asked` 也走模块级:重挂后仍记得「问过」,走 600ms debounce 而不是首挂载快路径。
5191
5379
  const askedSessions = globalThis.__balanceAsked instanceof Set
@@ -5195,14 +5383,15 @@ function UsageCostLine({ useProjection, sessionId }) {
5195
5383
  askedSessions.add(sessionId);
5196
5384
  let timer = null;
5197
5385
  let poll = null;
5198
- // ⚠️ **不要 abort**(2026-10-31 第十一轮:「我快速点了几个对话就这样了,
5199
- // 只有在对话消耗刷新的时候才会在刷新过了的对话正常显示」)。
5200
- // 这个 effect 依赖 [sessionId, usageKey],快速切会话时它会反复重跑,
5201
- // 每次 cleanup 都把正在飞的 `?session=` 中断掉 —— 结果永远拿不到,
5202
- // splitMap 里永远没有该会话的数据,于是「快速点几个对话就一直加载」。
5203
- // 正确的做法是让请求自然跑完:结果按 sessionId 落表(下面的 setSplitMap
5204
- // 不判断 disposed),切回来时立刻就有数。代价只是服务端那一次解压不会白省,
5205
- // 但那本来就是它该做的工作,比"永远加载不出来"好得多。
5386
+ // ⚠️ **切走就终止上一个对话的加载**(2026-11-02 用户第二轮,明确要求的语义):
5387
+ // 「切换对话的时候 上一个消耗没加载出来就停止上一个对话的消耗加载 就是只加载当前对话的消耗
5388
+ // 其他所有点击过的并且没有加载出来的就直接停止终止加载」。
5389
+ // 所以进入这个 effect 的第一件事,就是把**别的会话**那条在飞的 `?session=` 掐掉。
5390
+ // ⚠️ 但绝不能像 2026-10-31 第十一轮那样在 cleanup 里无脑 abort:「快速点了几个对话就一直加载」
5391
+ // 的根因是 abort 之后结果永远拿不到、`usageAskedMap` 里的去重记录还留着,点回去直接被跳过。
5392
+ // 现在两条一起做:abort + **撤销该会话的去重记录**(见 SESSION_USAGE_ABORTED 分支),
5393
+ // 点回去会重新发请求,不会卡在加载态。
5394
+ abortOtherSessionUsage(sessionId);
5206
5395
  const fire = () => {
5207
5396
  if (disposed) return;
5208
5397
  // 已问过 → 600ms debounce(流式期间每次 usageKey 变化都会重跑本 effect 并清掉这个
@@ -5210,10 +5399,26 @@ function UsageCostLine({ useProjection, sessionId }) {
5210
5399
  // 首挂载 → SESSION_USAGE_DELAY_MS,只留够画首帧。
5211
5400
  timer = setTimeout(() => {
5212
5401
  if (disposed) return;
5402
+ // 起飞前再掐一次:等这 240ms/600ms 的间隙里用户可能又切走了。
5403
+ abortOtherSessionUsage(sessionId);
5213
5404
  // 到这里才记录:请求确实要发了。写在 effect 顶部会让「被取消的那次」也留下
5214
5405
  // 记录,于是同一 usageKey 永远不再重试 —— 会话消耗卡在加载态。
5215
5406
  usageAskedMap.set(sessionId, usageKey);
5216
- fetchSessionUsage(sessionId).then((u) => {
5407
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
5408
+ sessionUsageInFlight = controller ? { sessionId, controller } : null;
5409
+ fetchSessionUsage(sessionId, controller ? controller.signal : undefined).then((u) => {
5410
+ // 自己这条已经跑完:把槽清掉(只清自己,别清掉后来者的)。
5411
+ if (sessionUsageInFlight && sessionUsageInFlight.controller === controller) {
5412
+ sessionUsageInFlight = null;
5413
+ }
5414
+ // ⚠️ **被我们主动取消 ≠ 失败**(2026-11-02 用户要求「切走就终止」)。
5415
+ // abort 之后绝不能写占位、也不能留着去重记录,否则点回去会命中去重、永久停在加载态
5416
+ // (这正是 2026-10-31 那次「快速点几个对话就一直加载」的根因)。
5417
+ // 删掉记录就够了:回到该对话时 `haveUsableSplit` 为假,effect 会重新问。
5418
+ if (u === SESSION_USAGE_ABORTED) {
5419
+ if (usageAskedMap.get(sessionId) === usageKey) usageAskedMap.delete(sessionId);
5420
+ return;
5421
+ }
5217
5422
  // ⚠️ `disposed` 只表示「这一轮 effect 失效」(切会话 / 依赖变化),
5218
5423
  // **不表示组件卸载,更不表示这个结果没用**。
5219
5424
  // 2026-10-31:「点击 A 对话还在加载,我这时候立即点击 B 对话 就能卡出这个 bug」——
@@ -5227,11 +5432,47 @@ function UsageCostLine({ useProjection, sessionId }) {
5227
5432
  // 原因:`?session=` 的响应里带着服务端用 updateTodayCostWithSession 增量算出的
5228
5433
  // today,而 `?today=1` 那边还有一条「快照 → 精算」的补拉。两路同时写同一个数,
5229
5434
  // 用户什么都没做,数字就自己变了两次。
5230
- // 定型前只让 `?today=1` 这一条路径有机会改值 —— 它自己是串行的(partial → 补拉)。
5435
+ // 2026-11-02 补充:现在**先直接采纳**它(`raiseTodayFromSession`,只抬不降),
5436
+ // 因为磁盘口径看不见当前会话还没落盘的那一截 —— 只当"补拉开关"用的时候,
5437
+ // 冷启动会一直停在 ¥0.0000,最长要等一个 TTL(20s) 才动。
5438
+ if (u && u.today && typeof u.today.cost === "number") raiseTodayFromSession(u.today);
5231
5439
  if (!disposed && todayCache.settled && u && u.today && typeof u.today.cost === "number") {
5232
5440
  void fetchTodayOnce(false);
5233
5441
  }
5442
+ // ⚠️ **空结果要重试**(2026-11-02 第三轮,「从大对话切到小对话还是加载很久」的真因):
5443
+ // 服务端这一趟可能因为「会话还在被 DSH 装载 / 读盘被 4s 节流 / 本趟读失败」返回 null。
5444
+ // 旧行为把这条 null 当成品:写进表 + 去重记录留着 → 小对话的 usageKey 不再变化 →
5445
+ // 此后**没有任何人再问一次** → 没有精确值 → 迷雾一直盖到 4 秒兜底。
5446
+ // 现在按 [400, 900, 1800]ms 重试三次(撤去重记录 + 踢一拍 effect),三次都空才认账。
5447
+ // 只在还停在当前会话时排重试(`disposed` 表示用户已经切走,别再为它烧 CPU)。
5448
+ const gotUsable = u && u.usage != null;
5449
+ const retryKey = splitRetryKeyOf(sessionId, usageKey);
5450
+ // 服务端说「DSH 正在装载这个会话,我先不读盘」→ 慢拍补拉(见 SPLIT_LOADING_RETRY_DELAYS)。
5451
+ // ⚠️ 让路这几次**不占 null 重试的预算**:两本账各 3 次,谁也别吃谁的额度。
5452
+ const serverLoading = !!(u && u.loading === true);
5453
+ if (gotUsable) {
5454
+ splitNullRetryCount.delete(retryKey);
5455
+ splitLoadingRetryCount.delete(retryKey);
5456
+ } else if (!disposed && u !== SESSION_USAGE_ABORTED) {
5457
+ const delays = serverLoading ? SPLIT_LOADING_RETRY_DELAYS : SPLIT_NULL_RETRY_DELAYS;
5458
+ const counter = serverLoading ? splitLoadingRetryCount : splitNullRetryCount;
5459
+ const tries = counter.get(retryKey) ?? 0;
5460
+ if (tries < delays.length) {
5461
+ counter.set(retryKey, tries + 1);
5462
+ if (counter.size > 64) {
5463
+ const oldest = counter.keys().next().value;
5464
+ if (oldest !== void 0) counter.delete(oldest);
5465
+ }
5466
+ // 撤掉去重记录,否则下一拍会被上面那条守卫直接跳过
5467
+ if (usageAskedMap.get(sessionId) === usageKey) usageAskedMap.delete(sessionId);
5468
+ setTimeout(() => {
5469
+ if (disposed) return;
5470
+ setSplitRetryGen((x) => x + 1);
5471
+ }, delays[tries]);
5472
+ }
5473
+ }
5234
5474
  // 拿不到也记一条(usage:null),表示"这个会话已经问过了",按本地估算走。
5475
+ // ⚠️ 但**「问过了」不再等于「永不再问」**(2026-11-02):见下面 SPLIT_NULL_RETRY_DELAYS。
5235
5476
  // ⚠️ 这里**不判断 disposed**:`splitMap` 按 sessionId 索引、对全部会话有效,
5236
5477
  // 切走后收到的结果照样要落表,否则点回去还得再等一轮解压。
5237
5478
  // ⚠️ **拿到 null 时不许立刻把表里那份可用结果冲掉**(2026-11-01:「余额从 90 跳到 115」)。
@@ -5287,6 +5528,10 @@ function UsageCostLine({ useProjection, sessionId }) {
5287
5528
  // 请求本身失败(网络 / 后端异常)时把去重记录撤掉,否则同一 usageKey
5288
5529
  // 再也不会重试,本会话消耗会一直停在加载态。
5289
5530
  usageAskedMap.delete(sessionId);
5531
+ // 在飞槽也要清(只清自己那条,别把后来者的清掉)
5532
+ if (sessionUsageInFlight && sessionUsageInFlight.controller === controller) {
5533
+ sessionUsageInFlight = null;
5534
+ }
5290
5535
  // ⚠️ **还要给 splitMap 写一条占位结果**(2026-10-31)。
5291
5536
  // 只删去重记录不够:对话已经结束、`usageKey` 不再变化时这个 effect 不会重跑,
5292
5537
  // 于是没有任何人再去发请求 → `splitAsked` 恒 false → 永久加载。
@@ -5297,7 +5542,7 @@ function UsageCostLine({ useProjection, sessionId }) {
5297
5542
  : { ...prev, [sessionId]: { usage: null, subagentUsage: null, team: null } }));
5298
5543
  });
5299
5544
  fetchBalanceData().catch(() => {});
5300
- }, asked ? 600 : SESSION_USAGE_DELAY_MS);
5545
+ }, pendingRetry ? SESSION_USAGE_DELAY_MS : asked ? 600 : SESSION_USAGE_DELAY_MS);
5301
5546
  };
5302
5547
  if (asked) {
5303
5548
  fire();
@@ -5326,7 +5571,7 @@ function UsageCostLine({ useProjection, sessionId }) {
5326
5571
  // `splitFor` 身份不变 → `costEpisodeAwaiting` 的 `costEpisodeFrom === splitFor` 恒真 →
5327
5572
  // 迷雾死等 4 秒兜底才散,白白露一段"卡住"的动画。
5328
5573
  // 误触发已知会放大成真请求,所以两条离场探测都加了 `lineRenderableRef` 前提(见声明处)。
5329
- }, [sessionId, usageKey, costReentrySeq]);
5574
+ }, [sessionId, usageKey, costReentrySeq, splitRetryGen]);
5330
5575
 
5331
5576
  // ── 金额与逐位滚动 ────────────────────────────────────────────────────
5332
5577
  // ⚠️ 这段是**计算 + hooks**,必须写在下面两处早退之前:hook 不能跟在条件 return 后面,
@@ -5345,10 +5590,12 @@ function UsageCostLine({ useProjection, sessionId }) {
5345
5590
  const splitUsable =
5346
5591
  split != null && ((Array.isArray(split.byModel) && split.byModel.length > 0) || (split.totalTokens ?? 0) > 0);
5347
5592
  // 「这个会话问过服务端没有」——没问过就还在算。
5348
- // 本地估算此时只是临时值:它把**整段历史**按当前时段价一次性乘(高峰窗口里就是 ×2),
5349
- // 而服务端是按每条消息实际发生的时段分桶。所以高峰时段点进旧会话必然先高后低
5350
- // (2026-10-30 实测:先显 ¥107、随即跳到 ¥69,比值 1.55 正好是「一半历史在空闲时段」)。
5351
- // 与其先闪一个会变的数字,不如先留空,拿到结果后一次到位。
5593
+ // ⚠️ 2026-11-02 **口径反转**(用户:「之前没加动画的时候 数字显示的很快啊 最多因为计算纠正之后
5594
+ // 数值跳动了一下 也很快啊」):本地投影**立刻显示**,服务端的逐时段分桶到了再滚一下纠正(快档 .24s)。
5595
+ // 早先的「与其先闪一个会变的数字,不如先留空,拿到结果后一次到位」已经被推翻 ——
5596
+ // 那条让每次进场都要等服务端往返(`?session=` 254~310ms),观感就是"数字出得慢"。
5597
+ // 需要知道的代价:高峰时段点进旧会话,本地投影会把整段历史按当前时段价乘一次(实测 ¥107 → 纠正成 ¥69),
5598
+ // 用户明确接受这个"跳一下",别再用等待去掩盖它。
5352
5599
  const splitAsked =
5353
5600
  sessionId != null && sessionId !== "" && Object.prototype.hasOwnProperty.call(splitMap, sessionId);
5354
5601
  const costPending = !splitAsked && usageKey > 0;
@@ -5385,6 +5632,9 @@ function UsageCostLine({ useProjection, sessionId }) {
5385
5632
  // 所以它既不算「已出数」,也不能在迷雾退场后被当成最终值。
5386
5633
  const splitUnresolved = splitAsked && splitFor != null && split == null;
5387
5634
  const costProvisional = splitUnresolved && !costEpisodeExpired;
5635
+ // 「这一次进场还在等数据」(含服务端给了 null、现在显示的是本地投影)。
5636
+ // 只为下面那个 4 秒兜底计时器服务:请求挂死时不能让迷雾永远转圈。
5637
+ const costWaiting = costEpisodeAwaiting || costProvisional;
5388
5638
 
5389
5639
  // 「这个对话已经出过数字了」—— 出过就不再显示加载动效(但记忆只属于**这一次进场**)。
5390
5640
  // 用户 2026-10-31:「如果对话在工作时,实时的对话消耗会导致会话加载动效重新播放,这样看起来很割裂」。
@@ -5417,24 +5667,15 @@ function UsageCostLine({ useProjection, sessionId }) {
5417
5667
  if (!shouldMarkReady || costEpisodeAwaiting || costEpisodeFresh || splitUnresolved) return;
5418
5668
  animWrite("cost-ready-session", sessionId);
5419
5669
  }, [shouldMarkReady, sessionId, costEpisodeAwaiting, costEpisodeFresh, splitUnresolved]);
5420
- // 只有「这个对话在本次进场里还没出过数」才播加载动效;已出过数的,刷新期间保持旧数字不动。
5421
- // ⚠️ 还要并上「本次进场的数据还没回来」(2026-10-31 第十八轮:点回看过的对话要有加载动画)。
5422
- // 缓存命中时不猜时间,靠响应到位的这一刻切换,所以「迷雾 → 开窗」是一条连续的进场动画。
5423
- // costProvisional:服务端给了 null(还在解码 / 读取失败)时也继续保持迷雾,
5424
- // 否则会先显示本地投影的假数字、再跳到真值 —— 就是「90 跳到 115」那一下。
5425
- const costWaiting = costEpisodeAwaiting || costProvisional;
5426
- const showCostLoading = (staleUsage || costPending || costWaiting) && !sessionReady;
5427
- // 等待兜底:4 秒还没等到(请求一直不返回 / 服务端卡住),停止等、退回缓存值。
5428
- // ⚠️ 依赖只留这三个(2026-10-31 第二十二轮审计):早先 `showCostLoading` 也在依赖里,
5429
- // 而它含 staleUsage / costPending,流式期间每变一次就 cleanup 重排 → 计时器被无限顺延,
5430
- // 卡住的会话永远等不到 expired,兜底等于没写。
5431
- // ⚠️ 判据用 `costWaiting`(进场等待 + 服务端给 null 的临时值)。两者都要能被这 4 秒收掉:
5432
- // 服务端一直返回 null 时迷雾不能永久转圈,超时就退回本地投影那个数字。
5433
- react.useEffect(() => {
5434
- if (!costWaiting || costEpisodeExpired) return undefined;
5435
- const id = setTimeout(() => setCostEpisodeExpired(true), 4000);
5436
- return () => clearTimeout(id);
5437
- }, [costWaiting, costEpisodeExpired, sessionId]);
5670
+ // ⚠️ **2026-11-02 二次定案:恢复原来的迷雾判据**。
5671
+ // 上一版(同一天早上)把判据改成「这一帧算不算得出金额」,结果是把所有「有数」的情形
5672
+ // 都不当加载 —— 用户看到的直接后果是「加载时的迷雾动画没了」,而那时数字也没快到
5673
+ // 让人满意的程度(`?session=` 还搭着余额的网络往返)。现在的处置:
5674
+ // · 迷雾判据回到 `(staleUsage || costPending) && !sessionReady`(和 2026-10-31 那版一致);
5675
+ // · 真正让数字变快的地方放到**请求本身**(消耗行改走 `lite=1`,不查余额),
5676
+ // 不靠删动画换速度;
5677
+ // · 因为请求快了,再加 `COST_FOG_FLOOR_MS` 保证雾至少看清一次,而不是一闪而过。
5678
+ // 数字「先本地投影、再纠正」那套滚动保留(用户接受那一下跳),只是不再是**进场**的主路径。
5438
5679
  // 子代理消耗(2026-10-31:「把字智能体的消费也算上 并且显示在这里」)。
5439
5680
  // 主会话和子代理分开算(各自有 byModel / peak / offpeak 桶),但**合计进同一个数字**:
5440
5681
  // 消耗行金额、明细浮层的「Token 用量」和「本会话金额」都是「含子代理」的口径,
@@ -5449,13 +5690,101 @@ function UsageCostLine({ useProjection, sessionId }) {
5449
5690
  const subagentNewTokens = hasSubagent
5450
5691
  ? (subagentUsage.inputTokens ?? 0) + (subagentUsage.outputTokens ?? 0)
5451
5692
  : 0;
5693
+ // 「这一次进场最近一次拿到的**精确值**」——投影增量的锚点。
5694
+ // 只按会话记住(切会话就不认),存 token 总数、金额和平均单价(元/token)。
5695
+ const costExactRef = react.useRef({ sessionId: null, tokens: 0, cost: 0, rate: 0 });
5452
5696
  const subagentCount = hasSubagent ? (subagentUsage.sessions ?? 0) : 0;
5453
- const cost = splitUsable
5454
- ? computeSplitCost(split, p, peakMultiplier) + subagentCost
5455
- : computeCost(usage ?? {}, periodAdjustedPricing(p, peakMultiplier)) + subagentCost;
5697
+ // 服务端分桶可用时算出来的**精确值**(含子代理)。不可用时为 null。
5698
+ const splitCostValue = splitUsable ? computeSplitCost(split, p, peakMultiplier) + subagentCost : null;
5699
+ // ⚠️ **兜底投影已删除**(2026-11-02 用户:「既然有了加载过程 并且有了动画 这个兜底投影是不是
5700
+ // 就可以取消了删除了」)。原来拿不到分桶时会把**整段 token** 按**当前时段**价重算
5701
+ // (高峰窗 9–12 / 14–18 的倍率是 2),一条全部跑在空闲窗的会话于是被正正好放大 2 倍
5702
+ // (实测 337.4M token、peak 桶为 0:真值 ¥19.4691 / 投影 ¥38.9382,就是那对 39.89 → 19.47)。
5703
+ // 现在只有两种数:
5704
+ // · 服务端精确值(byModel 已标价);
5705
+ // · 这次进场曾经拿到过精确值 → 按**平均单价补增量**(新 token 与旧 token 同源,单位成本几乎一致)。
5706
+ // 两者都没有 ⇒ `cost === null`,继续迷雾;4 秒兜底之后显示 `¥—`(说明算不出来,而不是编一个数)。
5707
+ const lastExact = costExactRef.current;
5708
+ const canDeltaProject =
5709
+ lastExact.sessionId === sessionId && lastExact.tokens > 0 && usageKey >= lastExact.tokens;
5710
+ const heldCost = canDeltaProject
5711
+ ? lastExact.cost + (usageKey - lastExact.tokens) * lastExact.rate
5712
+ : null;
5713
+ const cost = splitCostValue != null
5714
+ ? splitCostValue
5715
+ : heldCost != null
5716
+ ? heldCost
5717
+ : usageKey === 0
5718
+ ? subagentCost // 一条 token 都没有的新对话:¥0.0000,不要傻等
5719
+ : null;
5720
+ const costResolved = cost != null;
5721
+ const [costFogFloor, setCostFogFloor] = react.useState(false);
5722
+ react.useEffect(() => {
5723
+ // `usageKey > 0` 才起算:一条 token 都没有的对话没什么可算的,别凭空演 300ms。
5724
+ if (sessionId == null || sessionId === "" || !(usageKey > 0)) {
5725
+ setCostFogFloor(false);
5726
+ return undefined;
5727
+ }
5728
+ setCostFogFloor(true);
5729
+ const id = setTimeout(() => setCostFogFloor(false), COST_FOG_FLOOR_MS);
5730
+ return () => clearTimeout(id);
5731
+ }, [sessionId, usageKey > 0]);
5732
+ // ⚠️ `costStuck`:请求挂死时(4 秒都没回来)雾必须收,否则一直转圈、数字永不出现
5733
+ // —— 这正是 `costEpisodeExpired` 那条兜底存在的理由(2026-10-31 第二十一轮)。
5734
+ // 2026-11-02:删掉兜底投影之后,「拿不到分桶」也要能被这 4 秒收掉,否则雾永远不散、
5735
+ // 连 `¥—` 都不会出现。
5736
+ // ⚠️ 但**已经拿到答复(null)且重试机会用尽**时,这 4 秒不该再等 —— 那是「算不出来」,
5737
+ // 不是「还在算」。小对话的 usageKey 不会变,硬等 4 秒就是用户说的「加载时长异常」
5738
+ // (2026-11-02 第三轮:从大对话切到小对话时最明显)。所以 costStuck 多了第二个条件。
5739
+ const costRetryLeft = sessionId
5740
+ ? Math.max(0, SPLIT_NULL_RETRY_DELAYS.length - (splitNullRetryCount.get(splitRetryKeyOf(sessionId, usageKey)) ?? 0))
5741
+ : 0;
5742
+ const costAnsweredNull = splitAsked && !costResolved && costRetryLeft === 0;
5743
+ const costStuck = (costEpisodeExpired && (costPending || !costResolved)) || costAnsweredNull;
5744
+ const showCostLoading = (staleUsage || costPending || costFogFloor || !costResolved)
5745
+ && !sessionReady && !costStuck;
5746
+ // 等待兜底:4 秒还没等到(请求一直不返回 / 服务端卡住),停止等、退回缓存值。
5747
+ // ⚠️ 依赖只留这三个(2026-10-31 第二十二轮审计):早先 `showCostLoading` 也在依赖里,
5748
+ // 而它含 staleUsage / costPending,流式期间每变一次就 cleanup 重排 → 计时器被无限顺延,
5749
+ // 卡住的会话永远等不到 expired,兜底等于没写。
5750
+ // ⚠️ 判据用 `costWaiting`(进场等待 + 服务端给 null 的临时值)。两者都要能被这 4 秒收掉:
5751
+ // 服务端一直返回 null 时迷雾不能永久转圈,超时就退回本地投影那个数字。
5752
+ react.useEffect(() => {
5753
+ if (!costWaiting || costEpisodeExpired) return undefined;
5754
+ const id = setTimeout(() => {
5755
+ setCostEpisodeExpired(true);
5756
+ // 一行诊断:用户再报「加载很久」时,这一行就能定位到卡在哪一段
5757
+ // (是请求压根没发 / 发了回 null / 有数据但算不出钱)。只在超时那一刻打一次。
5758
+ try {
5759
+ console.warn("[balance] 本会话消耗等待超时", {
5760
+ sessionId,
5761
+ usageKey,
5762
+ asked: splitAsked,
5763
+ usable: splitUsable,
5764
+ nullRetries: splitNullRetryCount.get(splitRetryKeyOf(sessionId, usageKey)) ?? 0,
5765
+ });
5766
+ } catch {
5767
+ // 控制台不可用不影响渲染
5768
+ }
5769
+ }, 4000);
5770
+ return () => clearTimeout(id);
5771
+ }, [costWaiting, costEpisodeExpired, sessionId]);
5772
+ // 记住这一帧的精确值,供下一帧的增量投影用。
5773
+ // ⚠️ 写 ref 放在 effect 里(不在渲染期),StrictMode 下渲染两次也不会写出半成品。
5774
+ react.useEffect(() => {
5775
+ if (splitCostValue == null || usageKey <= 0) return;
5776
+ costExactRef.current = {
5777
+ sessionId,
5778
+ tokens: usageKey,
5779
+ cost: splitCostValue,
5780
+ rate: splitCostValue / usageKey,
5781
+ };
5782
+ }, [sessionId, usageKey, splitCostValue]);
5456
5783
  // 位数由 formatCostText 决定(至少两位小数、千位以下合计不超过 5 位数字),
5457
5784
  // 不再固定 toFixed(4) —— 那个会显示成 ≈ ¥120.2032,宽度不可控且挤到右侧。
5458
- const costText = formatCostText(cost);
5785
+ // `cost === null`(拿不到分桶、也没有可用的增量锚点)→ 占位 `—`:迷雾 4 秒后仍未算出时
5786
+ // 就显示它。**不许再编一个数字**(那正是 2 倍误差的来源)。
5787
+ const costText = costResolved ? formatCostText(cost) : "—";
5459
5788
 
5460
5789
  // 逐位滚动:数值一变就翻(和余额胶囊自动刷新共用 buildRollCells/renderRollCells)。
5461
5790
  // usePrePaintEffect 是必须的 —— 等 useEffect(paint 之后)才挂滚动结构的话,
@@ -5463,7 +5792,12 @@ function UsageCostLine({ useProjection, sessionId }) {
5463
5792
  // skipCostRoll:切会话/待算/无 usage 时把基准清空,这样下次出现是「首次显示」而不是「从某个值滚过来」。
5464
5793
  // 加载动效风格:决定等待时显示什么、数据到手怎么进场(两种语言不混用)
5465
5794
  const loadingIsText = settings.usageLoadingStyle === "text";
5466
- const skipCostRoll = staleUsage || costPending || !usage || showCostLoading;
5795
+ // ⚠️ `costPending` 不能参与(2026-11-02):拿到服务端分桶之前会显示增量投影,
5796
+ // 若把它当「整段失效」,滚动基准会被清掉 → 服务端值到达那一下就没有从旧值滚过去的纠正动画,
5797
+ // 数字直接硬跳。只有「这一帧根本没有可显示的数」才丢基准。
5798
+ // `!costResolved` 也要丢:占位 `—` 不是数字,拿它当滚动起点会拼出「空格子 + 小数点」那种
5799
+ // 半截结构(用户 2026-11-02 看到过一瞬间 `_._`)。占位单独静态渲染,见下面两处 body。
5800
+ const skipCostRoll = staleUsage || !usage || showCostLoading || costPending || !costResolved;
5467
5801
  const [costRoll, setCostRoll] = react.useState(null);
5468
5802
  const lastCostTextRef = react.useRef(null);
5469
5803
  usePrePaintEffect(() => {
@@ -5503,6 +5837,11 @@ function UsageCostLine({ useProjection, sessionId }) {
5503
5837
  const [costRevealFor, setCostRevealFor] = react.useState("");
5504
5838
  const costRevealOn = costRevealKey !== "" && costRevealFor === costRevealKey;
5505
5839
  const costRevealPlayed = animRead("cost-reveal-played");
5840
+ // ⚠️ 开窗(擦出)只在「刚从迷雾里出来」的那一帧授权(2026-11-02:「动画不要为了动画而动画」)。
5841
+ // 没有迷雾的数字一律直接给 —— 现在绝大多数进场都没有迷雾(本地投影立刻能算出数),
5842
+ // 若还按会话授权一次开窗,等于每次切对话都白演 280ms 的 clip 擦出,数字看着就"慢半拍"。
5843
+ // 判据用一个 ref 记住上一帧是不是迷雾(layout effect 在 paint 前跑,读到的是上一次 commit 的值)。
5844
+ const costCameFromFog = react.useRef(false);
5506
5845
  usePrePaintEffect(() => {
5507
5846
  // ⚠️ `!usage` 必须挡掉(2026-10-31 第十八轮:「还是没有」)。挂载时 usage 往往还是
5508
5847
  // null(首屏还没拿到),而那时 staleUsage / costPending 可能都是 false ——
@@ -5512,10 +5851,16 @@ function UsageCostLine({ useProjection, sessionId }) {
5512
5851
  // usage 有值 + 不在迷雾 + 不是样式2。
5513
5852
  // loadingIsText(样式2「计算中」)根本不会渲染 reveal 这棵树,同理别烧额度。
5514
5853
  if (showCostLoading || loadingIsText || !usage || costRevealKey === "" || costRevealOn) return;
5854
+ if (!costCameFromFog.current) return;
5515
5855
  if (costRevealPlayed === costRevealKey) return;
5516
5856
  animWrite("cost-reveal-played", costRevealKey);
5517
5857
  setCostRevealFor(costRevealKey);
5518
5858
  }, [showCostLoading, loadingIsText, usage, costRevealKey, costRevealOn, costRevealPlayed]);
5859
+ usePrePaintEffect(() => {
5860
+ // ⚠️ 必须并上 `usage != null`:usage 还没到时组件在下面直接 return null、屏幕上什么都没有,
5861
+ // 那一帧不算"演过迷雾"。否则首个数字冒出来时会白演一次 280ms 擦出 —— 又变回"数字慢半拍"。
5862
+ costCameFromFog.current = showCostLoading && usage != null;
5863
+ }, [showCostLoading, usage]);
5519
5864
  react.useEffect(() => {
5520
5865
  // 依赖是「被授权的那个会话键」而不是任何数值:普通刷新碰不到这个计时器,
5521
5866
  // 只有真的换会话(键变了)才会清掉 —— 与今日那边同一条教训。
@@ -5727,14 +6072,19 @@ function UsageCostLine({ useProjection, sessionId }) {
5727
6072
  // 静态也走逐字格:裸文本与 inline-block 逐字格的宽度/字距不等,
5728
6073
  // 来回切换会让整串左右挪一下(同今日金额,2026-10-31)。
5729
6074
  // 外层 key 恒定,只有变化的那一格换 key 重挂,否则滚动结束整串重挂会闪一下。
5730
- jsx.jsx("span", {
5731
- children: renderRollCells(
5732
- costRoll === null ? buildRollCells(costText, costText) : buildRollCells(costRoll.from, costText),
5733
- "u" + (costRoll === null ? "" : costRoll.at),
5734
- // 播完就定格:摘掉 animation 声明,展开侧栏不再重播
5735
- costRoll !== null && costRoll.done === true,
5736
- ),
5737
- }, "txt"),
6075
+ // ⚠️ 占位 `—` 不进滚格子(理由见下面 reveal 分支同一处)。
6076
+ costResolved
6077
+ ? jsx.jsx("span", {
6078
+ children: renderRollCells(
6079
+ costRoll === null ? buildRollCells(costText, costText) : buildRollCells(costRoll.from, costText),
6080
+ "u" + (costRoll === null ? "" : costRoll.at),
6081
+ // 播完就定格:摘掉 animation 声明,展开侧栏不再重播
6082
+ costRoll !== null && costRoll.done === true,
6083
+ // 快档:这一串是"订正"(本地投影 → 服务端逐时段分桶),不是出场秀
6084
+ true,
6085
+ ),
6086
+ }, "txt")
6087
+ : jsx.jsx("span", { className: "balance-usage-dash", children: "—" }, "dash"),
5738
6088
  ],
5739
6089
  }),
5740
6090
  }))
@@ -5771,14 +6121,21 @@ function UsageCostLine({ useProjection, sessionId }) {
5771
6121
  jsx.jsx("span", { children: "¥" }, "cur"),
5772
6122
  // 只有数字参与逐位滚动:¥ 是定值,跟着滚会把整个符号一起翻。
5773
6123
  // 静态也走逐字格 + 外层 key 恒定,理由同上(宽度恒定、滚动结束不重挂)。
5774
- jsx.jsx("span", {
5775
- children: renderRollCells(
5776
- costRoll === null ? buildRollCells(costText, costText) : buildRollCells(costRoll.from, costText),
5777
- "u" + (costRoll === null ? "" : costRoll.at),
5778
- // 播完就定格:摘掉 animation 声明,展开侧栏不再重播
5779
- costRoll !== null && costRoll.done === true,
5780
- ),
5781
- }, "txt"),
6124
+ // ⚠️ 占位 `—`(拿不到分桶、4 秒兜底之后)**不进滚格子**:它不是数字,
6125
+ // 滚格子会按「小数点对齐」拆出一个只有 `.` 的中间格,加上空位就是一串
6126
+ // 看着像 `_._` 的碎片(用户 2026-11-02 抓到过一瞬间)。占位直接静态文本。
6127
+ costResolved
6128
+ ? jsx.jsx("span", {
6129
+ children: renderRollCells(
6130
+ costRoll === null ? buildRollCells(costText, costText) : buildRollCells(costRoll.from, costText),
6131
+ "u" + (costRoll === null ? "" : costRoll.at),
6132
+ // 播完就定格:摘掉 animation 声明,展开侧栏不再重播
6133
+ costRoll !== null && costRoll.done === true,
6134
+ // 快档:订正滚动(同上面那处)
6135
+ true,
6136
+ ),
6137
+ }, "txt")
6138
+ : jsx.jsx("span", { className: "balance-usage-dash", children: "—" }, "dash"),
5782
6139
  ],
5783
6140
  }, "body"),
5784
6141
  ],
@@ -5840,13 +6197,21 @@ function UsageCostLine({ useProjection, sessionId }) {
5840
6197
  (Number(split?.webSearchBillable ?? 0) || 0) + (Number(split?.webFetchBillable ?? 0) || 0);
5841
6198
  const webToolCost = Number(split?.webToolCost ?? 0) || 0;
5842
6199
  if (webSearchCalls + webFetchCalls > 0) {
6200
+ // ⚠️ 「免费期内」是**有期限**的文案(2026-11-02 用户:「今天都11/2号了 怎么还显示啊」)。
6201
+ // 原来只判 `webToolCost > 0`:计费已开始、但这几次调用本来就不计费(或在 11-01 之前发生的)
6202
+ // 时,金额是 0,于是永远显示「免费期内(11-01 起收费)」。必须和统计面板一样按日期判。
6203
+ const webBillingStarted = Date.now() >= WEB_TOOL_BILLING_START;
5843
6204
  costDetails.push(
5844
6205
  ["网页搜索 / 抓取", webSearchCalls + " / " + webFetchCalls + " 次"],
5845
6206
  [
5846
6207
  "网页工具费用",
5847
6208
  webToolCost > 0
5848
6209
  ? "¥" + webToolCost.toFixed(4) + " · 计费 " + webBillable + " 次"
5849
- : "免费期内(11-01 起收费)",
6210
+ : webBillingStarted
6211
+ ? webBillable > 0
6212
+ ? "¥0.0000 · 计费 " + webBillable + " 次"
6213
+ : "¥0.0000 · 均在免费期内产生"
6214
+ : "免费期内(11-01 起收费)",
5850
6215
  ],
5851
6216
  );
5852
6217
  }
@@ -5887,7 +6252,12 @@ function UsageCostLine({ useProjection, sessionId }) {
5887
6252
  "本会话金额",
5888
6253
  ],
5889
6254
  }),
5890
- jsx.jsx("span", { className: "balance-usage-panel__value", children: "≈ ¥" + cost.toFixed(4) }),
6255
+ jsx.jsx("span", {
6256
+ className: "balance-usage-panel__value",
6257
+ // cost 现在可能是 null(拿不到分桶、也没有增量锚点,见 costResolved)。
6258
+ // 直接 toFixed 会抛 TypeError、整块明细炸掉 —— 显示 `≈ ¥—`。
6259
+ children: costResolved ? "≈ ¥" + cost.toFixed(4) : "≈ ¥—",
6260
+ }),
5891
6261
  ],
5892
6262
  }),
5893
6263
  jsx.jsx("div", { className: "balance-usage-panel__rule" }),