dsh-desktop-statusbar 3.0.2 → 3.0.4

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/lib/client.js CHANGED
@@ -48,6 +48,8 @@ window.__ModuleLoader__.load({
48
48
  /** 气泡定位诊断的上报端点(host 落到 tip-diag.log)。 */
49
49
  const TIP_DIAG_URL = "/dsh-desktop-statusbar/api/tip-diag";
50
50
  const PRICES_URL = "/dsh-desktop-statusbar/api/prices";
51
+ /** 中转站:每个模型一条余额查询配置(channelKey = 模型名;密文只 POST,GET 只回布尔)。 */
52
+ const RELAY_URL = "/dsh-desktop-statusbar/api/relay-balance-config";
51
53
  const HOLIDAYS_URL = "/dsh-desktop-statusbar/api/holidays";
52
54
  const VERSION_URL = "/dsh-desktop-statusbar/api/version";
53
55
  /** 一键更新:由本插件自己的 host 端执行(不依赖任何别的插件,见 self-update 说明)。 */
@@ -74,15 +76,31 @@ window.__ModuleLoader__.load({
74
76
  */
75
77
  const CONFIG_VERSION = 6;
76
78
  /** 插件版本:显示在设置页底部,用来确认页面加载的是哪一版客户端代码。 */
77
- const VERSION = "3.0.2";
78
- /** 官方参考价的版本:官方调价时改这个数字,老价格库会自动并入新参考价。 */
79
- const PRICE_VERSION = 2;
79
+ const VERSION = "3.0.4";
80
+ /** 官方参考价的版本:官方调价时改这个数字,老价格库会自动并入新参考价。
81
+ * v4:官方模型目录(MODEL_PRESENTATION)**默认全部加入价格表**(按官网价播种),
82
+ * 不再需要「点名字加入」;用户删掉的模型可用「恢复默认」找回。
83
+ * v5:清理旧版目录点选加入、现已下架的官方模型(它们不该落进「自定义模型」组)。
84
+ * v6:官方目录**新增**的模型自动补播给老用户(只补缺失项,已有条目不动)。
85
+ * v7:每个条目补内部基准价 `base`(切币种来回切不漂的锚点,见 normalizeBase)。
86
+ * v8:官方目录新增 Claude Fable 5.2,老用户价格库自动补播(只补缺失项,已有条目不覆盖)。 */
87
+ const PRICE_VERSION = 8;
88
+ /** 官方目录默认播种的版本(v4 一次性迁移;后续版本不再重复播种)。 */
89
+ const PRICE_SEED_VERSION = 4;
90
+ /** 清理已下架官方残留条目的版本(v5 起;v8 再清一次 MiniMax / 阶跃星辰两个默认条目)。
91
+ * v8 起与 PRICE_VERSION 同步:价格库版本 <8 的老用户升级时清理一次,≥8 不再重复。 */
92
+ const PRICE_RETIRED_PRUNE_VERSION = 8;
93
+ /** 补播官方目录新增模型的版本(v6 起每次目录加型号都靠这条自动补;v8 补 Claude Fable 5.2)。
94
+ * 只补当前价格库缺失项,已有条目(用户改过的价 / 倍率)一律不动。 */
95
+ const PRICE_BACKFILL_VERSION = 8;
96
+ /** 给价格条目补「基准价」的版本(v7 一次性迁移;缺 base 的条目按当前值 + 当前币种补,不改数值)。 */
97
+ const PRICE_BASE_VERSION = 7;
80
98
  /** 项目主页:设置页那个「去 GitHub 点 star」按钮跳这里(与 package.json 的 repository 同址)。 */
81
99
  const REPO_URL = "https://github.com/raphael-y7/dsh-desktop-statusbar";
82
100
 
83
101
  /* ------------------------------------------------------------ 价格库 */
84
102
 
85
- /** DeepSeek 参考价(CNY / 1M tokens)。高峰时段为北京时间周一至周五 9:00-12:00、14:00-18:00(法定节假日除外),空闲价为高峰价的一半。 */
103
+ /** 官方 CNY 价表。DeepSeek 既有参考值保持不动。 */
86
104
  const DEFAULT_PRICES = {
87
105
  "deepseek-flash": {
88
106
  peak: { input: 2, cacheRead: 0.04, cacheWrite: 0, output: 8 },
@@ -94,7 +112,7 @@ window.__ModuleLoader__.load({
94
112
  }
95
113
  };
96
114
 
97
- /** 官方参考价的美元表:与人民币表同一页面(2026-09 核对)。空闲价同样是高峰价的一半。 */
115
+ /** 既有官方 USD 价表保持原样,和 CNY 表双表键集合一致。 */
98
116
  const DEFAULT_PRICES_USD = {
99
117
  "deepseek-flash": {
100
118
  peak: { input: 0.3, cacheRead: 0.006, cacheWrite: 0, output: 1.2 },
@@ -106,6 +124,117 @@ window.__ModuleLoader__.load({
106
124
  }
107
125
  };
108
126
 
127
+ /**
128
+ * 官方模型目录(数据源:docs/official-models.json,2026-11-04 核验、2026-11-10 补 Claude Fable 5.2;每厂商只留最新一代)。
129
+ * 只保留 UI 需要的两样:厂商 id + 官方价;来源链接 / 备注 / 分档说明不进界面。
130
+ * 价格字段为 null = 官网未公布 → 不参与自动计费(不要填 0)。
131
+ * 厂商与模型顺序 = JSON 的 vendors / models 顺序。
132
+ */
133
+ const MODEL_PRESENTATION = {
134
+ "claude-fable-5.2": { manufacturer: "anthropic", price: { tiered: false, currency: "USD", peak: { input: 8, cacheRead: 0.2, cacheWrite: 10, output: 40 }, offPeak: { input: 8, cacheRead: 0.2, cacheWrite: 10, output: 40 } } },
135
+ "claude-fable-5.1": { manufacturer: "anthropic", price: { tiered: false, currency: "USD", peak: { input: 10, cacheRead: 0.25, cacheWrite: 12.5, output: 50 }, offPeak: { input: 10, cacheRead: 0.25, cacheWrite: 12.5, output: 50 } } },
136
+ "claude-opus-5.5": { manufacturer: "anthropic", price: { tiered: false, currency: "USD", peak: { input: 4, cacheRead: 0.2, cacheWrite: 5, output: 20 }, offPeak: { input: 4, cacheRead: 0.2, cacheWrite: 5, output: 20 } } },
137
+ "claude-sonnet-5.5": { manufacturer: "anthropic", price: { tiered: false, currency: "USD", peak: { input: 2, cacheRead: 0.1, cacheWrite: 2.5, output: 10 }, offPeak: { input: 2, cacheRead: 0.1, cacheWrite: 2.5, output: 10 } } },
138
+ "claude-haiku-5.5": { manufacturer: "anthropic", price: { tiered: false, currency: "USD", peak: { input: 0.1, cacheRead: 0.01, cacheWrite: 0.125, output: 0.5 }, offPeak: { input: 0.1, cacheRead: 0.01, cacheWrite: 0.125, output: 0.5 } } },
139
+ "gpt-6-astra": { manufacturer: "openai", price: { tiered: false, currency: "USD", peak: { input: 10, cacheRead: 1, cacheWrite: 12.5, output: 50 }, offPeak: { input: 10, cacheRead: 1, cacheWrite: 12.5, output: 50 } } },
140
+ "gpt-6.1-sol": { manufacturer: "openai", price: { tiered: false, currency: "USD", peak: { input: 2, cacheRead: 0.1, cacheWrite: 2.5, output: 10 }, offPeak: { input: 2, cacheRead: 0.1, cacheWrite: 2.5, output: 10 } } },
141
+ "gpt-6.1-terra": { manufacturer: "openai", price: { tiered: false, currency: "USD", peak: { input: 1, cacheRead: 0.05, cacheWrite: 1.25, output: 5 }, offPeak: { input: 1, cacheRead: 0.05, cacheWrite: 1.25, output: 5 } } },
142
+ "gpt-6-luna": { manufacturer: "openai", price: { tiered: false, currency: "USD", peak: { input: 0.1, cacheRead: 0.01, cacheWrite: 0.125, output: 0.5 }, offPeak: { input: 0.1, cacheRead: 0.01, cacheWrite: 0.125, output: 0.5 } } },
143
+ "gemini-4-argon": { manufacturer: "google", price: { tiered: false, currency: "USD", peak: { input: 2, cacheRead: 0.1, cacheWrite: null, output: 10 }, offPeak: { input: 2, cacheRead: 0.1, cacheWrite: null, output: 10 } } },
144
+ "gemini-3.8-flash": { manufacturer: "google", price: { tiered: false, currency: "USD", peak: { input: 0.75, cacheRead: 0.075, cacheWrite: null, output: 3.75 }, offPeak: { input: 0.75, cacheRead: 0.075, cacheWrite: null, output: 3.75 } } },
145
+ "kimi-k3.1-pro": { manufacturer: "moonshot", price: { tiered: false, currency: "CNY", peak: { input: 13, cacheRead: 1.3, cacheWrite: 13, output: 68 }, offPeak: { input: 13, cacheRead: 1.3, cacheWrite: 13, output: 68 } } },
146
+ "kimi-k3.1-pro-highspeed": { manufacturer: "moonshot", price: { tiered: false, currency: "CNY", peak: { input: 26, cacheRead: 1.3, cacheWrite: 26, output: 136 }, offPeak: { input: 26, cacheRead: 1.3, cacheWrite: 26, output: 136 } } },
147
+ "kimi-k3": { manufacturer: "moonshot", price: { tiered: false, currency: "CNY", peak: { input: 20, cacheRead: 2, cacheWrite: 20, output: 100 }, offPeak: { input: 20, cacheRead: 2, cacheWrite: 20, output: 100 } } },
148
+ "muse-wonder-1.0": { manufacturer: "muse", price: { tiered: false, currency: "USD", peak: { input: 4, cacheRead: 0.2, cacheWrite: null, output: 20 }, offPeak: { input: 4, cacheRead: 0.2, cacheWrite: null, output: 20 } } },
149
+ "muse-spark-1.3": { manufacturer: "muse", price: { tiered: false, currency: "USD", peak: { input: 1.25, cacheRead: 0.15, cacheWrite: null, output: 4.25 }, offPeak: { input: 1.25, cacheRead: 0.15, cacheWrite: null, output: 4.25 } } },
150
+ "grok-4.7": { manufacturer: "xai", price: { tiered: false, currency: "USD", peak: { input: 2, cacheRead: 0.5, cacheWrite: null, output: 6 }, offPeak: { input: 2, cacheRead: 0.5, cacheWrite: null, output: 6 } } },
151
+ "qwen3.8-flash": { manufacturer: "alibaba", price: { tiered: false, currency: "CNY", peak: { input: 0.8, cacheRead: null, cacheWrite: null, output: 2.7 }, offPeak: { input: 0.8, cacheRead: null, cacheWrite: null, output: 2.7 } } },
152
+ "qwen3.8-27b": { manufacturer: "alibaba", price: { tiered: false, currency: "CNY", peak: { input: 3, cacheRead: null, cacheWrite: null, output: 12 }, offPeak: { input: 3, cacheRead: null, cacheWrite: null, output: 12 } } },
153
+ "deepseek-flash": { manufacturer: "deepseek", price: { tiered: true, currency: "USD", peak: { input: 0.3, cacheRead: 0.006, cacheWrite: null, output: 1.2 }, offPeak: { input: 0.15, cacheRead: 0.003, cacheWrite: null, output: 0.6 } } },
154
+ "deepseek-v4-pro": { manufacturer: "deepseek", price: { tiered: true, currency: "USD", peak: { input: 1.32, cacheRead: 0.044, cacheWrite: null, output: 3.96 }, offPeak: { input: 0.66, cacheRead: 0.022, cacheWrite: null, output: 1.98 } } },
155
+ "GLM-5.3": { manufacturer: "zhipu", price: { tiered: false, currency: "CNY", peak: { input: 8, cacheRead: 2, cacheWrite: 0, output: 28 }, offPeak: { input: 8, cacheRead: 2, cacheWrite: 0, output: 28 } } },
156
+ "GLM-5.3-Flash": { manufacturer: "zhipu", price: { tiered: false, currency: "CNY", peak: { input: 0.8, cacheRead: 0.23, cacheWrite: 0, output: 2.8 }, offPeak: { input: 0.8, cacheRead: 0.23, cacheWrite: 0, output: 2.8 } } },
157
+ "GLM-5.3-FlashX": { manufacturer: "zhipu", price: { tiered: false, currency: "CNY", peak: { input: 2, cacheRead: 0.57, cacheWrite: 0, output: 7 }, offPeak: { input: 2, cacheRead: 0.57, cacheWrite: 0, output: 7 } } },
158
+ "mimo-v2.6-pro": { manufacturer: "xiaomi", price: { tiered: false, currency: "CNY", peak: { input: 3, cacheRead: 0.025, cacheWrite: 0, output: 6 }, offPeak: { input: 3, cacheRead: 0.025, cacheWrite: 0, output: 6 } } },
159
+ "mimo-v2.6-flash": { manufacturer: "xiaomi", price: { tiered: false, currency: "CNY", peak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 2 }, offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 2 } } },
160
+ "mimo-v2.6-pro-ultraspeed": { manufacturer: "xiaomi", price: { tiered: false, currency: "CNY", peak: { input: 30, cacheRead: 0.25, cacheWrite: 0, output: 60 }, offPeak: { input: 30, cacheRead: 0.25, cacheWrite: 0, output: 60 } } },
161
+ };
162
+ const MODEL_MANUFACTURERS = ["anthropic", "openai", "google", "moonshot", "muse", "xai", "alibaba", "deepseek", "zhipu", "xiaomi"];
163
+ const MODEL_MANUFACTURER_LABEL_KEYS = {
164
+ deepseek: "priceManufacturerDeepseek",
165
+ anthropic: "priceManufacturerAnthropic",
166
+ zhipu: "priceManufacturerZhipu",
167
+ alibaba: "priceManufacturerAlibaba",
168
+ moonshot: "priceManufacturerMoonshot",
169
+ google: "priceManufacturerGoogle",
170
+ xai: "priceManufacturerXai",
171
+ xiaomi: "priceManufacturerXiaomi",
172
+ muse: "priceManufacturerMuse",
173
+ openai: "priceManufacturerOpenai",
174
+ };
175
+ /* 价格目录的默认厂商顺序:官方 10 家 + 自定义模型组在末尾。 */
176
+ const DEFAULT_CATALOG_ORDER = MODEL_MANUFACTURERS.concat(["__custom"]);
177
+ /** catalogOrder 归一化:补缺失、去重、丢弃未知项;默认顺序兜底。 */
178
+ function normalizeCatalogOrder(raw) {
179
+ const out = [];
180
+ (Array.isArray(raw) ? raw : []).forEach((id) => {
181
+ if (typeof id === "string" && DEFAULT_CATALOG_ORDER.indexOf(id) !== -1 && out.indexOf(id) === -1) out.push(id);
182
+ });
183
+ DEFAULT_CATALOG_ORDER.forEach((id) => {
184
+ if (out.indexOf(id) === -1) out.push(id);
185
+ });
186
+ return out;
187
+ }
188
+
189
+ /**
190
+ * 旧版官方目录里「点选加入」过的**已下架官方模型名**(来源:一次性调研名单
191
+ * retired-official-models.json,240 条;精简目录后它们不再属于官方目录)。
192
+ * 用途:v5 迁移时从价格库按**确切名字**删掉,避免落进「自定义模型」组;
193
+ * 用户真正自建的模型名字不同,不会被命中。
194
+ */
195
+ const RETIRED_OFFICIAL_MODELS = [
196
+ "GLM-4-Air-250414", "GLM-4-AirX", "GLM-4-Assistant", "GLM-4-Flash-250414", "GLM-4-FlashX-250414", "GLM-4-Long",
197
+ "GLM-4-Plus", "GLM-4.1V-Thinking-Flash", "GLM-4.1V-Thinking-FlashX", "GLM-4.5-Air", "GLM-4.5V", "GLM-4.6V",
198
+ "GLM-4.6V-Flash", "GLM-4.6V-FlashX", "GLM-4.7", "GLM-4.7-Flash", "GLM-4.7-FlashX", "GLM-4V-Flash",
199
+ "GLM-4V-Plus-0111", "GLM-5-Turbo", "GLM-5.1", "GLM-5.2", "GLM-5.3-FlashX-Legal", "GLM-5V-Turbo",
200
+ "GLM-Image", "GLM-OCR", "GLM-Z1-Air", "GLM-Z1-AirX", "GLM-Z1-Flash", "GLM-Z1-FlashX",
201
+ "MiniMax-H3", "MiniMax-H3-Context-IR", "MiniMax-H3-Highspeed", "MiniMax-H3-Lite", "MiniMax-H3-Max", "MiniMax-H3-Regeneration",
202
+ "MiniMax-Hailuo-02", "MiniMax-Hailuo-2.3", "MiniMax-Hailuo-2.3-Fast", "MiniMax-M3", "MiniMax-M3.1-Flash", "claude-fable-5", "claude-haiku-3.5",
203
+ "claude-haiku-4.5", "claude-mem", "claude-mythos-5", "claude-mythos-5.1", "claude-opus-4", "claude-opus-4.1",
204
+ "claude-opus-4.5", "claude-opus-4.6", "claude-opus-4.7", "claude-opus-4.8", "claude-opus-5", "claude-opus-5-5",
205
+ "claude-sonnet-4", "claude-sonnet-4.5", "claude-sonnet-4.6", "claude-sonnet-5", "claude-sonnet-5-5", "deepseek-harness",
206
+ "deepseek-v4-flash", "deepseek-v4-flash-vision-exp", "doubao-seed-2.1-lite", "doubao-seed-2.1-pro", "doubao-seed-2.1-turbo", "gemini-2.5-flash",
207
+ "gemini-2.5-flash-image", "gemini-2.5-flash-lite", "gemini-2.5-flash-native-audio", "gemini-2.5-flash-preview-tts", "gemini-2.5-pro", "gemini-2.5-pro-preview-tts",
208
+ "gemini-3-flash-preview", "gemini-3-pro-image", "gemini-3.1-flash-image", "gemini-3.1-flash-lite", "gemini-3.1-flash-lite-image", "gemini-3.1-flash-live-preview",
209
+ "gemini-3.1-flash-tts-preview", "gemini-3.1-pro-preview", "gemini-3.1-pro-preview-customtools", "gemini-3.5-flash-lite", "gemini-3.5-live-translate-preview", "gemini-3.5-transcribe",
210
+ "gemini-3.5-transcribe-live", "gemini-3.6-flash", "gemini-3.8-flash-lite-tts", "gemini-3.8-flash-tts", "gemini-3.8-live", "gemini-3.8-live-extended-thinking",
211
+ "gemini-31-pro-preview-customtools", "gemini-api", "gemini-embedding", "gemini-embedding-001", "gemini-embedding-2", "gemini-enterprise-agent-platform",
212
+ "gemini-nano-banana-2.1", "gemini-omni-1.1-flash", "gemini-omni-flash", "gemini-robotics-er-2", "gemini-robotics-er-2-preview", "gemini-robotics-er-2-streaming",
213
+ "gemini-robotics-er-2-streaming-preview", "gpt-4.1", "gpt-4.1-2025-04-14", "gpt-4.1-mini", "gpt-4.1-mini-2025-04-14", "gpt-4o",
214
+ "gpt-4o-mini", "gpt-4o-mini-transcribe", "gpt-4o-mini-tts", "gpt-4o-transcribe", "gpt-5-mini", "gpt-5-nano",
215
+ "gpt-5-pro", "gpt-5.1", "gpt-5.2", "gpt-5.2-pro", "gpt-5.3-codex", "gpt-5.4",
216
+ "gpt-5.4-mini", "gpt-5.4-nano", "gpt-5.4-pro", "gpt-5.5", "gpt-5.5-cyber", "gpt-5.5-pro",
217
+ "gpt-5.6-cyber", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.x", "gpt-6-astra-law",
218
+ "gpt-6-l", "gpt-6-rosalind", "gpt-6-sol", "gpt-6.1-luna", "gpt-audio", "gpt-audio-1.5",
219
+ "gpt-audio-mi", "gpt-audio-mini", "gpt-image-1-mini", "gpt-image-1.5", "gpt-image-2", "gpt-image-2.5-flare",
220
+ "gpt-image-2.5-sunburst", "gpt-image-latest", "gpt-live", "gpt-live-1", "gpt-live-transcribe", "gpt-oss",
221
+ "gpt-realtime", "gpt-realtime-1.5", "gpt-realtime-2", "gpt-realtime-2.1", "gpt-realtime-2.1-mini", "gpt-realtime-mini",
222
+ "gpt-realtime-translate", "gpt-realtime-whisper", "gpt-rosalind-discovery", "gpt-rosalind-for-life-sciences-research", "gpt-rosalind-research", "gpt-transcribe",
223
+ "grok-4.20", "grok-4.20-0309-non-reasoning", "grok-4.20-0309-reasoning", "grok-4.20-multi-agent-0309", "grok-4.3", "grok-4.5",
224
+ "grok-4.6", "grok-build", "grok-build-0.1", "grok-imagine-image", "grok-imagine-image-2.0", "grok-imagine-video",
225
+ "grok-imagine-video-1.5", "grok-imagine-video-1.5-lite", "grok-voice-2.0", "grok-voice-3.0", "kimi-chat.md", "kimi-in-hermes-agent.md",
226
+ "kimi-k2-6-quickstart", "kimi-k2-6-quickstart.md", "kimi-k2-7-code-quickstart", "kimi-k2-7-code-quickstart.md", "kimi-k2.6", "kimi-k2.7-code",
227
+ "kimi-k2.7-code-highspeed", "kimi-k3-1-pro-quickstart", "kimi-k3-1-pro-quickstart.md", "kimi-k3-quickstart", "kimi-k3-quickstart.md",
228
+ "kimi-k3-to-setup-agent.md", "kimi-k3-tool-calling-best-practice.md", "kimi-llms.txt", "mimo-v2", "mimo-v2.5", "mimo-v2.5-asr",
229
+ "mimo-v2.5-pro", "mimo-v2.5-tts", "mimo-v2.5-tts-voiceclone", "mimo-v2.5-tts-voicedesign", "mimo-v2.6-ultraspeed", "muse-spark-1.1",
230
+ "muse-spark-1.2", "muse-spark-1.2-contributor", "muse-spark-1.3-contributor", "o3-pro", "o4-mini", "qwen-flash",
231
+ "qwen-flash-2025-07-28", "qwen-plus-2025-12-01", "qwen.html", "qwen.txt", "qwen3.5-27b", "qwen3.5-flash",
232
+ "qwen3.5-flash-2026-02-23", "qwen3.6-27b", "qwen3.6-35b-a3b", "qwen3.6-flash", "qwen3.6-flash-2026-04-16", "qwen3.7-flash",
233
+ "qwen3.7-flash-2026-07-15", "qwen3.7-max", "qwen3.7-max-2026-05-17", "qwen3.7-max-2026-05-20", "qwen3.7-max-2026-06-08", "qwen3.7-max-preview",
234
+ "qwen3.8-2.4t-a95b", "qwen3.8-max", "qwen3.8-max-0902", "step-1o-turbo-vision", "step-3.5-flash", "step-3.5-flash-2603",
235
+ "step-3.5-flash.md", "step-3.7-flash", "step-3.7-flash.md", "step-5-preview", "step-5-preview-price-adjustment.md", "step-5-preview.md", "step-plan",
236
+ ];
237
+
109
238
  /** 取某个币种的官方参考价表。 */
110
239
  function referencePrices(currency) {
111
240
  return currency === "USD" ? DEFAULT_PRICES_USD : DEFAULT_PRICES;
@@ -181,9 +310,10 @@ window.__ModuleLoader__.load({
181
310
  if (Number.isFinite(value) !== true) return amount;
182
311
  const a = normalizeCurrency(from);
183
312
  const b = normalizeCurrency(to);
184
- if (a === b || REFERENCE_RATE === null || Number.isFinite(REFERENCE_RATE) !== true || REFERENCE_RATE <= 0) return value;
313
+ const rate = liveRate();
314
+ if (a === b || rate === null || Number.isFinite(rate) !== true || rate <= 0) return value;
185
315
  /* 比率是"人民币 / 美元":CNY → USD 就除,USD → CNY 就乘 */
186
- return a === "CNY" ? value / REFERENCE_RATE : value * REFERENCE_RATE;
316
+ return a === "CNY" ? value / rate : value * rate;
187
317
  }
188
318
 
189
319
  /**
@@ -228,6 +358,21 @@ window.__ModuleLoader__.load({
228
358
  /** host 带回来的当前汇率(「1 USD = ? CNY」);没拿到过是 null。 */
229
359
  let liveExchangeRate = null;
230
360
 
361
+ /**
362
+ * 价格库数值按汇率换算后的取整:**四舍五入到小数点后两位**(存库与显示都按这个精度)。
363
+ * 纯四舍五入,不做任何兜底/最小值:极小值该舍成 0 就舍成 0(用户确认不存在"变免费"的问题)。
364
+ */
365
+ function roundPrice2(value) {
366
+ if (typeof value !== "number" || Number.isFinite(value) !== true) return value;
367
+ return Math.round(value * 100) / 100;
368
+ }
369
+ /** 价格输入框的显示文本:固定两位小数(12.5 → "12.50"),空值保持空串。 */
370
+ function priceText(value) {
371
+ return value === null || value === undefined || value === ""
372
+ ? ""
373
+ : (Number.isFinite(Number(value)) ? Number(value).toFixed(2) : String(value));
374
+ }
375
+
231
376
  /** 一格未填时的占位:用 `null` 表示"这里还没填过",与用户明确填的 0 区分开。 */
232
377
  const EMPTY_TIER = { input: null, cacheRead: null, cacheWrite: null, output: null };
233
378
 
@@ -283,7 +428,199 @@ window.__ModuleLoader__.load({
283
428
  return { peak: flat, offPeak: flat };
284
429
  }
285
430
 
431
+
432
+ /**
433
+ * 价格条目的「基准价」:**上一次保存 / 播种时**的数值 + 币种(非密、客户端内部字段,界面与上报都不带)。
434
+ * 切币种以它为锚:切回 `base.currency` 直接用原值(**不换算、不取整**),切到别的币种从它按汇率换算。
435
+ * 否则「CNY→USD→CNY」来回切两次,两位小数的舍入会让官方价越切越小(用户实测)。
436
+ */
437
+ function normalizeBase(raw, fallbackCurrency) {
438
+ if (raw === null || raw === undefined || typeof raw !== "object") return null;
439
+ const price = normalizePrice(raw);
440
+ if (price === null) return null;
441
+ const currency = raw.currency === undefined || raw.currency === null ? fallbackCurrency : raw.currency;
442
+ return {
443
+ currency: normalizeCurrency(currency),
444
+ peak: normalizeTier(price.peak),
445
+ offPeak: normalizeTier(price.offPeak)
446
+ };
447
+ }
448
+ /** 条目的基准价:旧配置没有 base 时用「当前值 + 当前币种」兜底(与 v7 迁移写进去的完全一样)。 */
449
+ function baseOf(entry, fallbackCurrency) {
450
+ const entryCurrency = entry !== null && entry !== undefined && entry.currency !== undefined && entry.currency !== null
451
+ ? entry.currency
452
+ : fallbackCurrency;
453
+ const stored = normalizeBase(entry === null || entry === undefined ? null : entry.base, entryCurrency);
454
+ if (stored !== null) return stored;
455
+ const price = normalizePrice(entry);
456
+ return { currency: normalizeCurrency(entryCurrency), peak: normalizeTier(price.peak), offPeak: normalizeTier(price.offPeak) };
457
+ }
458
+ /** 从基准价换算出一条新价格:两位小数,null(没填 / 官网未公布)保持 null。 */
459
+ function tiersFromBase(base, to, rate) {
460
+ const convertTier = (tier) => ({
461
+ input: tier.input === null ? null : roundPrice2(convertWithRate(tier.input, base.currency, to, rate)),
462
+ cacheRead: tier.cacheRead === null ? null : roundPrice2(convertWithRate(tier.cacheRead, base.currency, to, rate)),
463
+ cacheWrite: tier.cacheWrite === null ? null : roundPrice2(convertWithRate(tier.cacheWrite, base.currency, to, rate)),
464
+ output: tier.output === null ? null : roundPrice2(convertWithRate(tier.output, base.currency, to, rate))
465
+ });
466
+ return { peak: convertTier(base.peak), offPeak: convertTier(base.offPeak) };
467
+ }
468
+ /**
469
+ * 价格条目的「中转站」费用倍率:可选、数字 >0;缺省 / 非法一律按 1。
470
+ * 只在 ≠1 时才写进条目(避免配置膨胀)—— 1 就表示"没有倍率",按旧格式存。
471
+ */
472
+ function normalizeFeeMultiplier(raw) {
473
+ const n = Number(raw);
474
+ if (Number.isFinite(n) !== true || n <= 0 || n > 1000) return 1;
475
+ return n;
476
+ }
477
+
478
+ /**
479
+ * 余额字段单框:`¥data.quota / 500000` → `{ currency, balancePath, balanceDivisor }`。
480
+ * 空串 = 不提交这三项(Host 保留原值 / 默认值);格式不对返回 null。
481
+ * `¥`/`$` 前缀 → CNY/USD;路径归一成 `data.quota`;`/ 数字` → 除数(缺省 1)。
482
+ */
483
+ function parseBalanceField(text) {
484
+ const raw = typeof text === "string" ? text.trim() : "";
485
+ if (raw.length === 0) return {};
486
+ const match = /^([¥$])?\s*([^\s/]+)?\s*(?:\/\s*([0-9]+(?:\.[0-9]+)?))?$/.exec(raw);
487
+ if (match === null) return null;
488
+ const symbol = match[1] === undefined ? "" : match[1];
489
+ const rawPath = match[2] === undefined ? "" : match[2];
490
+ const rawDivisor = match[3] === undefined ? "" : match[3];
491
+ const path = rawPath.replace(/^\$?\.?/, "");
492
+ if (path.length === 0) return null;
493
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*|\[[0-9]+\])*$/.test(path) !== true) return null;
494
+ const divisor = rawDivisor.length === 0 ? 1 : Number(rawDivisor);
495
+ if (Number.isFinite(divisor) !== true || divisor <= 0 || divisor > 1e12) return null;
496
+ const out = { balancePath: path, balanceDivisor: divisor };
497
+ if (symbol === "¥") out.currency = "CNY";
498
+ if (symbol === "$") out.currency = "USD";
499
+ return out;
500
+ }
501
+ /** 反向:价格条目里的 relay 配置 → 同一个单框写法(编辑气泡回填用)。 */
502
+ function balanceFieldText(relay) {
503
+ if (relay === null || relay === undefined) return "";
504
+ const path = typeof relay.balancePath === "string" ? relay.balancePath.replace(/^\$?\.?/, "") : "";
505
+ if (path.length === 0) return "";
506
+ const symbol = relay.currency === "USD" ? "$" : (relay.currency === "CNY" ? "¥" : "");
507
+ const divisor = typeof relay.balanceDivisor === "number" && Number.isFinite(relay.balanceDivisor) && relay.balanceDivisor > 0
508
+ ? relay.balanceDivisor
509
+ : 1;
510
+ return symbol + path + (divisor === 1 ? "" : " / " + String(divisor));
511
+ }
512
+ /** 价格条目里的中转站配置:**只有非密字段**(白名单重建,密文永远进不来)。 */
513
+ function normalizeRelayConfig(raw) {
514
+ if (raw === null || raw === undefined || typeof raw !== "object") return null;
515
+ const endpoint = typeof raw.endpoint === "string" && raw.endpoint.trim().length > 0 ? raw.endpoint.trim() : "";
516
+ if (endpoint.length === 0) return null;
517
+ return {
518
+ endpoint: endpoint,
519
+ tokenHeader: typeof raw.tokenHeader === "string" && raw.tokenHeader.length > 0 ? raw.tokenHeader : "authorization",
520
+ userIdHeader: typeof raw.userIdHeader === "string" && raw.userIdHeader.length > 0 ? raw.userIdHeader : "New-Api-User",
521
+ balancePath: typeof raw.balancePath === "string" && raw.balancePath.length > 0 ? raw.balancePath : "$.balance",
522
+ currency: typeof raw.currency === "string" && /^[A-Z]{3}$/.test(raw.currency) ? raw.currency : "CNY",
523
+ balanceDivisor: typeof raw.balanceDivisor === "number" && Number.isFinite(raw.balanceDivisor) && raw.balanceDivisor > 0
524
+ ? raw.balanceDivisor
525
+ : 1
526
+ };
527
+ }
528
+
529
+ /**
530
+ * 第三方平台档案:`{ endpoint, userIdHeader, balancePath, currency, balanceDivisor,
531
+ * models: [{ model, feeMultiplier }] }`。
532
+ * **endpoint 可以为空** —— 只按倍率计费、不查余额(Magpie 这类路由确定不了上游的平台)。
533
+ * 令牌 / 用户 ID 是密文,绝不进这份配置:它们只随 POST 提交到宿主凭据(channelKey = 平台名)。
534
+ */
535
+ function normalizePlatformModels(raw) {
536
+ const out = [];
537
+ (Array.isArray(raw) ? raw : []).forEach((one) => {
538
+ const model = typeof one === "string"
539
+ ? one.trim()
540
+ : (one !== null && one !== undefined && typeof one.model === "string" ? one.model.trim() : "");
541
+ if (model.length === 0) return;
542
+ if (out.some((entry) => sameModelName(entry.model, model) === true)) return;
543
+ const feeConfigured = one !== null && typeof one === "object" && one.feeConfigured === true;
544
+ out.push(Object.assign({
545
+ model: model,
546
+ feeMultiplier: normalizeFeeMultiplier(one !== null && typeof one === "object" ? one.feeMultiplier : 1)
547
+ }, feeConfigured === true ? { feeConfigured: true } : {}));
548
+ });
549
+ return out;
550
+ }
551
+ function normalizePlatform(raw) {
552
+ if (raw === null || raw === undefined || typeof raw !== "object") return null;
553
+ const endpoint = typeof raw.endpoint === "string" ? raw.endpoint.trim() : "";
554
+ if (endpoint.length > 0 && /^https?:\/\//i.test(endpoint) !== true) return null;
555
+ return {
556
+ endpoint: endpoint,
557
+ /* 令牌请求头固定 authorization + Bearer 前缀,界面不暴露(与旧模型气泡同一套映射) */
558
+ tokenHeader: "authorization",
559
+ /* 以下四项**没填就存空**(currency 空串 / divisor null):默认值只在向宿主提交
560
+ 余额查询配置时补(见 savePlatform)。档案里存示例值,再次编辑就会把用户根本
561
+ 没填的东西显示成已填 —— 用户实测反馈的就是这个。 */
562
+ userIdHeader: typeof raw.userIdHeader === "string" ? raw.userIdHeader.trim() : "",
563
+ balancePath: typeof raw.balancePath === "string" ? raw.balancePath.trim() : "",
564
+ currency: typeof raw.currency === "string" && /^[A-Z]{3}$/.test(raw.currency.trim()) ? raw.currency.trim() : "",
565
+ balanceDivisor: typeof raw.balanceDivisor === "number" && Number.isFinite(raw.balanceDivisor) && raw.balanceDivisor > 0
566
+ ? raw.balanceDivisor
567
+ : null,
568
+ models: normalizePlatformModels(raw.models)
569
+ };
570
+ }
571
+ /** 平台表:逐条归一化;非法条目直接丢(手改配置也不该把界面搞崩)。 */
572
+ function normalizePlatforms(raw) {
573
+ const out = {};
574
+ if (raw === null || raw === undefined || typeof raw !== "object") return out;
575
+ Object.keys(raw).forEach((name) => {
576
+ const platform = normalizePlatform(raw[name]);
577
+ if (platform !== null && name.length > 0) out[name] = platform;
578
+ });
579
+ return out;
580
+ }
581
+ /**
582
+ * 平台档案里的模型名 ↔ 价格条目键:**宽容匹配**(同名或归一化紧凑串相同,与 pickPriceKey 同一套口径)。
583
+ * 平台里存的是价格库键,但迁移 / 手改配置来的名字可能带 provider 前缀或不同分隔符。
584
+ */
585
+ function sameModelName(a, b) {
586
+ if (a === b) return true;
587
+ if (typeof a !== "string" || typeof b !== "string") return false;
588
+ return compactModelKey(a) !== "" && compactModelKey(a) === compactModelKey(b);
589
+ }
590
+ /** 会话模型 → 它归属的第三方平台名;取不到返回 null(余额请求就不带 relay 参数)。 */
591
+ function platformOfBook(book, platforms, model) {
592
+ if (book === null || book === undefined || platforms === null || platforms === undefined
593
+ || typeof platforms !== "object") return null;
594
+ const key = pickPriceKey(book, typeof model === "string" ? model : "");
595
+ const wanted = key === null ? model : key;
596
+ if (typeof wanted !== "string" || wanted.length === 0) return null;
597
+ const names = Object.keys(platforms);
598
+ for (let i = 0; i < names.length; i += 1) {
599
+ const platform = platforms[names[i]];
600
+ if (platform === null || platform === undefined || Array.isArray(platform.models) !== true) continue;
601
+ for (let j = 0; j < platform.models.length; j += 1) {
602
+ const one = platform.models[j];
603
+ if (one !== null && one !== undefined && sameModelName(one.model, wanted) === true) return names[i];
604
+ }
605
+ }
606
+ return null;
607
+ }
608
+
286
609
  /* ------------------------------------------------------------ 模型名匹配 */
610
+ /**
611
+ * 模型名归一化成「紧凑串」:小写 → 去掉 provider 前缀(取最后一个 `/` 之后)→ 只留 [a-z0-9]。
612
+ * 例:`Remote-Magpie/group/Claude Opus 5-5` 与价格键 `claude-opus-5.5` 都归一成 `claudeopus55`。
613
+ * 只做「完全相等」判定(`deepseek-v4` 不会命中 `deepseek-v4-pro`);空串 / 纯符号返回 "",不参与匹配。
614
+ */
615
+ function compactModelKey(name) {
616
+ if (typeof name !== "string") return "";
617
+ const lower = name.toLowerCase();
618
+ const slash = lower.lastIndexOf("/");
619
+ const tail = slash === -1 ? lower : lower.slice(slash + 1);
620
+ return tail.replace(/[^a-z0-9]/g, "");
621
+ }
622
+
623
+
287
624
  /**
288
625
  * 模型名切成词元:忽略大小写,分隔符(- . _ 空格等)都当边界。
289
626
  * `DeepSeek-V4.1-Flash-SG` → ["deepseek","v4","1","flash","sg"]
@@ -346,6 +683,16 @@ window.__ModuleLoader__.load({
346
683
  for (let i = 0; i < keys.length; i += 1) {
347
684
  if (keys[i].toLowerCase() === lower && usable(keys[i])) return keys[i];
348
685
  }
686
+ /* ①b 紧凑串完全相等:`Claude Opus 5-5` / `claude-opus-5.5` / 带 provider 前缀的会话名都命中同一价格;
687
+ 只认完全相等(deepseek-v4 不会命中 deepseek-v4-pro),空串不参与。 */
688
+ const modelCompact = compactModelKey(model);
689
+ if (modelCompact.length > 0) {
690
+ for (let i = 0; i < keys.length; i += 1) {
691
+ if (usable(keys[i]) !== true) continue;
692
+ if (compactModelKey(keys[i]) === modelCompact) return keys[i];
693
+ }
694
+ }
695
+
349
696
  /* ②③ 一次评选:子串命中的键与词元全含命中的键放在一起比 weight,取最具体的那个。
350
697
  不能按"先全部子串、再全部词元"两轮跑 —— 那样模型名里只要含一个短键(如 flash),
351
698
  就会把更具体的 deepseek-flash(只能靠词元档命中)挤掉。
@@ -412,6 +759,8 @@ window.__ModuleLoader__.load({
412
759
  const price = normalizePrice(book[key]);
413
760
  if (price === null) return null;
414
761
  price.tiered = isTiered(book[key]);
762
+ /* 「中转站」费用倍率按**该模型的价格条目**取(默认 1),计价时直接乘进去 */
763
+ price.feeMultiplier = normalizeFeeMultiplier(book[key].feeMultiplier);
415
764
  return price;
416
765
  }
417
766
 
@@ -426,8 +775,9 @@ window.__ModuleLoader__.load({
426
775
  * 依据《国务院办公厅关于2026年部分节假日安排的通知》(国办发明电〔2025〕7号):
427
776
  * 元旦 1/1-1/3、春节 2/15-2/23、清明 4/4-4/6、劳动节 5/1-5/5、端午 6/19-6/21、
428
777
  * 中秋 9/25-9/27、国庆 10/1-10/7。
429
- * 官方每年 10 月底到 11 月中发布下一年的安排;设置页常驻「更新节假峰谷」按钮,
430
- * 点了就把下一年写进配置(holidayDays),内嵌这份只作出厂兜底。
778
+ * 官方每年 10 月底到 11 月中发布下一年的安排;客户端每年 12/31 自动抓下一年,
779
+ * 平时只要发现当年在配置里完全缺失就补抓(长期未开机的兜底),
780
+ * 写进配置(holidayDays),内嵌这份只作出厂兜底。
431
781
  */
432
782
  const HOLIDAYS = {
433
783
  "2026": [
@@ -463,43 +813,77 @@ window.__ModuleLoader__.load({
463
813
  const fetched = fetchedHolidays[year];
464
814
  return fetched !== undefined && fetched.has(key);
465
815
  }
816
+ /** 自动补抓失败后的冷却:同一个目标年 24 小时内不再重试(内存 ref 记录,重启后再试一次)。 */
817
+ const HOLIDAY_RETRY_MS = 24 * 3600 * 1000;
466
818
  /**
467
- * 「更新节假峰谷」的目标年份:永远是下一年。
468
- * 官方一般 10 月底到 11 月中公布下一年的安排;按钮常驻,什么时候点都行。
819
+ * 自动更新节假峰谷的时机:
820
+ * - 每年 12/31 抓下一年(原逻辑;官方一般 10 月底到 11 月中已发布);
821
+ * - 其余任何日期,只要 holidayDays 里完全没有当年数据就补抓当年。
822
+ * 这是「12/30 到 2/10 一直没开机,2/10 打开时当年假期缺失」的兜底,
823
+ * 不再限定 1/1-1/7(2/10、3/15 等任何日期都能补)。
824
+ * `lastFailure` = { 年份字符串: 失败时间戳 }:每个目标年各自 24 小时冷却,
825
+ * 避免 12/31 两个候选年互相覆盖、每个时钟 tick 都发请求。返回目标年份;不需要更新时返回 false。
826
+ * holidayDays 里已有目标年份的任意一天就不再抓(每个目标年只自动成功一次)。
469
827
  */
470
- function nextHolidayYear(now) {
828
+ function shouldAutoUpdateHolidays(now, holidayDays, lastFailure) {
471
829
  const at = new Date((typeof now === "number" && now > 0 ? now : Date.now()) + 8 * 3600 * 1000);
472
- return at.getUTCFullYear() + 1;
473
- }
474
- /** 某一年已录入多少个节假日(内嵌 + 抓取,去重),没有就是 0。 */
475
- function holidayCount(year) {
476
- const name = String(year);
477
- const seen = new Set();
478
- const builtin = HOLIDAY_SETS[name];
479
- if (builtin !== undefined) builtin.forEach((day) => seen.add(day));
480
- const fetched = fetchedHolidays[name];
481
- if (fetched !== undefined) fetched.forEach((day) => seen.add(day));
482
- return seen.size;
830
+ const thisYear = at.getUTCFullYear();
831
+ const days = Array.isArray(holidayDays) ? holidayDays : [];
832
+ const hasYear = (year) => {
833
+ const prefix = String(year) + "-";
834
+ for (let i = 0; i < days.length; i += 1) {
835
+ if (typeof days[i] === "string" && days[i].indexOf(prefix) === 0) return true;
836
+ }
837
+ return false;
838
+ };
839
+ const coolingDown = (year) => {
840
+ if (lastFailure === null || lastFailure === undefined || typeof lastFailure !== "object") return false;
841
+ const failedAt = Number(lastFailure[String(year)]);
842
+ if (Number.isFinite(failedAt) !== true) return false;
843
+ const nowMs = typeof now === "number" && now > 0 ? now : Date.now();
844
+ return nowMs - failedAt < HOLIDAY_RETRY_MS;
845
+ };
846
+ const candidates = [];
847
+ /* 原逻辑:12/31 抓下一年 */
848
+ if (at.getUTCMonth() === 11 && at.getUTCDate() === 31) candidates.push(thisYear + 1);
849
+ /* 补漏:当年完全没有任何数据就补抓当年,任何日期都适用 */
850
+ candidates.push(thisYear);
851
+ for (let i = 0; i < candidates.length; i += 1) {
852
+ if (hasYear(candidates[i]) === true || coolingDown(candidates[i]) === true) continue;
853
+ return candidates[i];
854
+ }
855
+ return false;
483
856
  }
484
857
  /**
485
- * 按钮右边那行状态文案用的概况:有下一年的表就报下一年,否则报当年;
486
- * 当年也没有(跨年还没更新)就用已录入里最靠后的一年,别显示 0 天。
858
+ * 时钟 effect 每次跳(以及打开 DSH 的首次渲染)调用一次自动检查并抓取。
859
+ * `state` 是可变的 { busy, failed }(由 useRef 提供):busy 防并发,
860
+ * failed 记「每个失败年份 → 时间」做 24 小时冷却。开发模式一律不发真实请求。
861
+ * 返回 Promise<boolean>:这次是否真的发起了抓取(测试与排错用)。
487
862
  */
488
- function holidaySummary(now) {
489
- const at = new Date((typeof now === "number" && now > 0 ? now : Date.now()) + 8 * 3600 * 1000);
490
- const thisYear = at.getUTCFullYear();
491
- const nextCount = holidayCount(thisYear + 1);
492
- if (nextCount > 0) return { year: thisYear + 1, count: nextCount };
493
- const count = holidayCount(thisYear);
494
- if (count > 0) return { year: thisYear, count: count };
495
- let latest = null;
496
- Object.keys(HOLIDAY_SETS).concat(Object.keys(fetchedHolidays)).forEach((name) => {
497
- const year = Number(name);
498
- if (latest === null || year > latest) latest = year;
863
+ function autoUpdateHolidays(now, holidayDays, state, devActive) {
864
+ if (devActive === true || typeof window.fetch !== "function") return Promise.resolve(false);
865
+ if (state === null || state === undefined || typeof state !== "object") return Promise.resolve(false);
866
+ const target = shouldAutoUpdateHolidays(now, holidayDays, state.failed);
867
+ if (target === false || state.busy === true) return Promise.resolve(false);
868
+ state.busy = true;
869
+ const startedAt = typeof now === "number" && now > 0 ? now : Date.now();
870
+ let pending;
871
+ try {
872
+ pending = updateHolidays(target);
873
+ } catch (error) {
874
+ pending = Promise.resolve({ ok: false, year: target, reason: "fetch-failed" });
875
+ }
876
+ return pending.then((result) => {
877
+ state.busy = false;
878
+ const failed = state.failed !== null && state.failed !== undefined && typeof state.failed === "object"
879
+ ? state.failed
880
+ : {};
881
+ if (result !== null && result !== undefined && result.ok === true) delete failed[String(target)];
882
+ else failed[String(target)] = startedAt;
883
+ state.failed = failed;
884
+ return true;
499
885
  });
500
- return latest === null ? { year: thisYear, count: 0 } : { year: latest, count: holidayCount(latest) };
501
886
  }
502
-
503
887
  /** 按北京时间取日期键(YYYY-MM-DD),用来查节假日。 */
504
888
  function beijingDateKey(beijing) {
505
889
  const month = String(beijing.getUTCMonth() + 1).padStart(2, "0");
@@ -559,7 +943,7 @@ window.__ModuleLoader__.load({
559
943
  function ensurePrices() {
560
944
  if (!pricesMissing(config.models)) return Promise.resolve(false);
561
945
  const fallback = () => {
562
- setConfig({ models: normalizeModels(referencePrices(config.currency)), priceVersion: PRICE_VERSION, priceConfigured: true });
946
+ setConfig({ models: normalizeModels(officialDefaultModels(config.currency), config.currency), priceVersion: PRICE_VERSION, priceConfigured: true });
563
947
  return false;
564
948
  };
565
949
  try {
@@ -603,7 +987,7 @@ window.__ModuleLoader__.load({
603
987
  }
604
988
 
605
989
  function currencySymbol(currency) {
606
- return currency === "USD" ? "$" : "¥";
990
+ return currency === "USD" ? "$" : currency === "EUR" ? "€" : currency === "GBP" ? "£" : "¥";
607
991
  }
608
992
 
609
993
  /**
@@ -700,10 +1084,10 @@ window.__ModuleLoader__.load({
700
1084
  if (price === null || bucket === undefined || bucket === null) return null;
701
1085
  /* 没勾「峰谷计价」= 全天一个价:两档都取 peak,别在空闲时段挑到空档、把费用算成 0 */
702
1086
  const tier = price.tiered === false ? price.peak : (isPeakTime(at) ? price.peak : price.offPeak);
703
- return ((bucket.input || 0) * tier.input
1087
+ return (((bucket.input || 0) * tier.input
704
1088
  + (bucket.cacheRead || 0) * tier.cacheRead
705
1089
  + (bucket.cacheWrite || 0) * tier.cacheWrite
706
- + (bucket.output || 0) * tier.output) / 1e6;
1090
+ + (bucket.output || 0) * tier.output) / 1e6) * price.feeMultiplier;
707
1091
  }
708
1092
 
709
1093
  /**
@@ -715,10 +1099,10 @@ window.__ModuleLoader__.load({
715
1099
  const price = priceOf(model);
716
1100
  if (price === null || bucket === undefined || bucket === null) return null;
717
1101
  const tier = price.tiered === false ? price.peak : (peak === true ? price.peak : price.offPeak);
718
- return ((bucket.input || 0) * tier.input
1102
+ return (((bucket.input || 0) * tier.input
719
1103
  + (bucket.cacheRead || 0) * tier.cacheRead
720
1104
  + (bucket.cacheWrite || 0) * tier.cacheWrite
721
- + (bucket.output || 0) * tier.output) / 1e6;
1105
+ + (bucket.output || 0) * tier.output) / 1e6) * price.feeMultiplier;
722
1106
  }
723
1107
 
724
1108
  /**
@@ -1115,19 +1499,31 @@ window.__ModuleLoader__.load({
1115
1499
  const box = prev !== null ? prev : {
1116
1500
  sessionId: null, seen: new Map(), cost: 0, tokens: null,
1117
1501
  priced: false, subCostSettled: 0, debts: new Map(),
1502
+ /* 「中转站」倍率指纹:变了就把金额类账本整份重算(见下面 feeChanged) */
1503
+ feeFingerprint: "",
1118
1504
  /* ① 用的**指纹缓存**(上一拍的 calls 数组 + 它的计数表 + 长度 + 当时的兜底模型)。
1119
1505
  挂在账本盒子上而不是模块级变量:盒子是 useRef 里那个对象,组件卸载即回收,不泄漏。 */
1120
1506
  scanCalls: null, scanCounts: null, scanFirsts: null, scanLen: -1, scanFallback: undefined
1121
1507
  };
1122
- /* 换会话(含首次):整份状态清空。清空后 seen 为空,
1508
+ /* 「中转站」费用倍率指纹:只含 feeMultiplier≠1 的模型。改倍率后必须把总计账本
1509
+ 整份重算一次 —— 否则改倍率前已结算的调用会永久停在旧倍率(用户要求)。
1510
+ 本轮粘性下限不受影响(它只增不减,见 applyTurnFloor)。 */
1511
+ const feeBook = snap.models === null || snap.models === undefined || typeof snap.models !== "object" ? {} : snap.models;
1512
+ const feeFingerprint = JSON.stringify(Object.keys(feeBook).sort()
1513
+ .filter((name) => normalizeFeeMultiplier(feeBook[name].feeMultiplier) !== 1)
1514
+ .map((name) => [name, normalizeFeeMultiplier(feeBook[name].feeMultiplier)]));
1515
+ const feeChanged = sameSession === true && box.feeFingerprint !== feeFingerprint;
1516
+ const fresh = sameSession !== true || feeChanged === true;
1517
+ /* 换会话(含首次)或倍率指纹变化:整份状态清空。清空后 seen 为空,
1123
1518
  下面那段"只结算没见过的调用"自然退化成"结算现有全部调用",不必另写一套初始化。 */
1124
- if (sameSession !== true) {
1519
+ if (fresh === true) {
1125
1520
  box.sessionId = sessionId;
1126
1521
  box.seen = new Map();
1127
1522
  box.cost = 0;
1128
1523
  box.tokens = null;
1129
1524
  box.priced = false;
1130
1525
  box.subCostSettled = 0;
1526
+ box.feeFingerprint = feeFingerprint;
1131
1527
  /* 欠账必须用 **Map** 而不是普通对象:模型名是上游给的任意字符串,
1132
1528
  用 `obj[model] = slot` 时若 model 恰好是 `__proto__`,那是**设置原型**、
1133
1529
  不是加键 —— `Object.keys` 遍历不到它,补价时永远结算不回来,
@@ -1220,7 +1616,7 @@ window.__ModuleLoader__.load({
1220
1616
  /* ---------- ② overflow:只加一次 ---------- */
1221
1617
  /* host 把被 MAX_CALLS 截掉的最老调用按「模型 + 峰谷档」累计好了。它没有逐条时间戳,
1222
1618
  只能在**首次建立账本**那一拍计入一次 —— 之后每拍再加就是旧实现那个重复计费的错。 */
1223
- if (sameSession !== true && snap.overflow !== null && snap.overflow !== undefined
1619
+ if (fresh === true && snap.overflow !== null && snap.overflow !== undefined
1224
1620
  && typeof snap.overflow === "object") {
1225
1621
  Object.keys(snap.overflow).forEach((model) => {
1226
1622
  const byTier = snap.overflow[model];
@@ -1315,6 +1711,17 @@ window.__ModuleLoader__.load({
1315
1711
  output: tierValue(entry.output)
1316
1712
  };
1317
1713
  }
1714
+ /** 价格条目的原始档位(不折算、null 保留);normalizeModels / catalogPriceEntry 共用。 */
1715
+ function rawTierOf(tier) {
1716
+ return tier === null || tier === undefined
1717
+ ? Object.assign({}, EMPTY_TIER)
1718
+ : {
1719
+ input: tier.input === undefined ? null : tier.input,
1720
+ cacheRead: tier.cacheRead === undefined ? null : tier.cacheRead,
1721
+ cacheWrite: tier.cacheWrite === undefined ? null : tier.cacheWrite,
1722
+ output: tier.output === undefined ? null : tier.output
1723
+ };
1724
+ }
1318
1725
  /**
1319
1726
  * 规范化价格库。`defaultCurrency` 是"这条目没写币种时用哪个"——
1320
1727
  * 老配置里币种是**全局**的(`config.currency`),迁移时把它当默认值传给每个条目,
@@ -1338,10 +1745,157 @@ window.__ModuleLoader__.load({
1338
1745
  peak: normalizeTier(price.peak),
1339
1746
  offPeak: normalizeTier(price.offPeak)
1340
1747
  };
1748
+ /* 官方 USD 源表不改;已有 USD 条目在生成价格库时按实时汇率折算成 CNY */
1749
+ const srcUsd = out[names[i]].currency === "USD";
1750
+ const convRate = liveRate();
1751
+ const conv = (v) => (srcUsd === true && v !== null && v !== undefined && Number.isFinite(Number(v))
1752
+ ? Math.round(Number(v) * convRate * 100) / 100
1753
+ : v);
1754
+ const convTier = (t) => ({
1755
+ input: conv(t.input),
1756
+ cacheRead: conv(t.cacheRead),
1757
+ cacheWrite: conv(t.cacheWrite),
1758
+ output: conv(t.output)
1759
+ });
1760
+ if (srcUsd === true) {
1761
+ /* 锚点:转换前的官方 USD 原值(不折算,null 保留),与 catalogPriceEntry 同口径 */
1762
+ const rawPeak = rawTierOf(raw.peak);
1763
+ const rawOffPeak = raw.offPeak === null ? null : rawTierOf(raw.offPeak);
1764
+ out[names[i]].peak = convTier(out[names[i]].peak);
1765
+ out[names[i]].offPeak = out[names[i]].offPeak === null ? null : convTier(out[names[i]].offPeak);
1766
+ out[names[i]].currency = "CNY";
1767
+ out[names[i]].base = { currency: "USD", peak: rawPeak, offPeak: rawOffPeak };
1768
+ }
1769
+ /* 中转站费用倍率:只有 ≠1 才落库(见 normalizeFeeMultiplier);余额查询配置
1770
+ 已从条目搬到「第三方平台」档案(见 normalizePlatforms),条目上只认倍率 */
1771
+ const feeMultiplier = normalizeFeeMultiplier(raw === null || raw === undefined ? undefined : raw.feeMultiplier);
1772
+ const feeConfigured = raw !== null && raw !== undefined && raw.feeConfigured === true;
1773
+ if (feeConfigured === true) {
1774
+ out[names[i]].feeConfigured = true;
1775
+ out[names[i]].feeMultiplier = feeMultiplier;
1776
+ } else if (feeMultiplier !== 1) out[names[i]].feeMultiplier = feeMultiplier;
1777
+ /* 基准价:用条目的原始官方值做锚点(USD 不折算),只有上面的显示值 peak/offPeak 才折算 */
1778
+ const base = normalizeBase(raw === null || raw === undefined ? undefined : raw.base, normalizeCurrency(raw === null || raw === undefined ? undefined : raw.currency));
1779
+ if (base !== null) {
1780
+ out[names[i]].base = base;
1781
+ }
1782
+ /* 官方 USD 条目:仅当老配置缺 base、tiered 与官方一致、且当前 peak/offPeak 与官方 USD
1783
+ 按 liveRate 折算后的值逐字段一致(容差 1e-6)时才用官方原始值重建 base;用户改过任何一项的绝不覆盖。 */
1784
+ const presentation = MODEL_PRESENTATION[names[i]];
1785
+ if (presentation !== undefined && presentation.price !== undefined && presentation.price !== null
1786
+ && normalizeCurrency(presentation.price.currency) === "USD"
1787
+ && out[names[i]].base === undefined) {
1788
+ const priceEntry = presentation.price;
1789
+ const matchRate = liveRate();
1790
+ const convNum = (v) => (v === null || v === undefined || Number.isFinite(Number(v)) !== true
1791
+ ? null
1792
+ : Math.round(Number(v) * matchRate * 100) / 100);
1793
+ const near = (a, b) => ((a === null || a === undefined) && (b === null || b === undefined))
1794
+ ? true
1795
+ : (a !== null && a !== undefined && b !== null && b !== undefined && Math.abs(Number(a) - Number(b)) <= 1e-6);
1796
+ const tierFields = ["input", "cacheRead", "cacheWrite", "output"];
1797
+ const curPeak = out[names[i]].peak === null || out[names[i]].peak === undefined ? {} : out[names[i]].peak;
1798
+ const curOffPeak = out[names[i]].offPeak === null || out[names[i]].offPeak === undefined ? {} : out[names[i]].offPeak;
1799
+ const officialPeak = priceEntry.peak === null || priceEntry.peak === undefined ? {} : priceEntry.peak;
1800
+ const officialOffPeak = priceEntry.tiered === true
1801
+ ? (priceEntry.offPeak === null || priceEntry.offPeak === undefined ? {} : priceEntry.offPeak)
1802
+ : officialPeak;
1803
+ const peakMatches = tierFields.every((k) => near(curPeak[k], convNum(officialPeak[k])) === true);
1804
+ const offPeakMatches = tierFields.every((k) => near(curOffPeak[k], convNum(officialOffPeak[k])) === true);
1805
+ if ((raw.tiered === true) === (priceEntry.tiered === true) && peakMatches === true && offPeakMatches === true) {
1806
+ out[names[i]].base = {
1807
+ currency: "USD",
1808
+ peak: rawTierOf(officialPeak),
1809
+ offPeak: priceEntry.tiered === true ? rawTierOf(officialOffPeak) : rawTierOf(officialPeak)
1810
+ };
1811
+ }
1812
+ }
1341
1813
  }
1342
1814
  return out;
1343
1815
  }
1344
1816
 
1817
+ /**
1818
+ * MODEL_PRESENTATION 的 price → 价格库条目(与旧「目录点选预填」同一套归一化):
1819
+ * tiered 条目两档照抄;单档条目只存 peak、offPeak 记 null;null 字段保持 null。
1820
+ */
1821
+ function catalogPriceEntry(price) {
1822
+ if (price === null || price === undefined || typeof price !== "object") return null;
1823
+ const tiered = price.tiered === true;
1824
+ const srcUsd = normalizeCurrency(price.currency) === "USD";
1825
+ const rate = srcUsd === true ? liveRate() : null;
1826
+ /* 官方 USD 源表不改;生成价格库条目时按实时汇率折算成 CNY(null 保留) */
1827
+ const conv = (v) => (srcUsd === true && v !== null && v !== undefined && Number.isFinite(Number(v))
1828
+ ? Math.round(Number(v) * rate * 100) / 100
1829
+ : v);
1830
+ const tierOf = (tier) => (tier === null || tier === undefined
1831
+ ? Object.assign({}, EMPTY_TIER)
1832
+ : {
1833
+ input: conv(tier.input === undefined ? null : tier.input),
1834
+ cacheRead: conv(tier.cacheRead === undefined ? null : tier.cacheRead),
1835
+ cacheWrite: conv(tier.cacheWrite === undefined ? null : tier.cacheWrite),
1836
+ output: conv(tier.output === undefined ? null : tier.output)
1837
+ });
1838
+ const peakTier = tierOf(price.peak);
1839
+ const offPeakTier = tiered === true ? tierOf(price.offPeak) : Object.assign({}, peakTier);
1840
+ const rawPeakTier = rawTierOf(price.peak);
1841
+ const rawOffPeakTier = tiered === true ? rawTierOf(price.offPeak) : Object.assign({}, rawPeakTier);
1842
+ return {
1843
+ tiered: tiered,
1844
+ currency: srcUsd === true ? "CNY" : normalizeCurrency(price.currency),
1845
+ peak: peakTier,
1846
+ offPeak: tiered === true ? offPeakTier : null,
1847
+ /* 基准价用未折算的官方原始值:USD 源表不改,切币种来回才不漂 */
1848
+ base: { currency: normalizeCurrency(price.currency), peak: rawPeakTier, offPeak: rawOffPeakTier }
1849
+ };
1850
+ }
1851
+ /** 官方目录的全部默认条目(按 MODEL_PRESENTATION 顺序);播种与「恢复默认」共用。 */
1852
+ function officialSeededModels() {
1853
+ const out = {};
1854
+ Object.keys(MODEL_PRESENTATION).forEach((name) => {
1855
+ const entry = catalogPriceEntry(MODEL_PRESENTATION[name].price);
1856
+ if (entry !== null) out[name] = entry;
1857
+ });
1858
+ return out;
1859
+ }
1860
+ /** 内嵌参考价(DeepSeek 两条)规范化成价格库条目,并补上 v7 的 base 锚点。 */
1861
+ function referenceSeedModels(currency) {
1862
+ const out = normalizeModels(referencePrices(currency), currency);
1863
+ Object.keys(out).forEach((name) => {
1864
+ out[name].base = {
1865
+ currency: out[name].currency,
1866
+ peak: out[name].peak,
1867
+ offPeak: out[name].offPeak
1868
+ };
1869
+ });
1870
+ return out;
1871
+ }
1872
+ /** 全新安装 / 空价格库的默认价格书:官方目录全部模型,两条 DeepSeek 沿用内嵌参考价表。 */
1873
+ function officialDefaultModels(currency) {
1874
+ return Object.assign({}, officialSeededModels(), referenceSeedModels(currency));
1875
+ }
1876
+ /**
1877
+ * 每个版本「新增」的官方模型。升级补播只补这些名字,不重播整个目录 ——
1878
+ * 否则用户主动删掉的当前官方模型会在升级时被悄悄加回来(v7→v8 实测问题)。
1879
+ */
1880
+ const PRICE_BACKFILL_ADDED = [
1881
+ { version: 6, names: ["kimi-k3"] },
1882
+ { version: 8, names: ["claude-fable-5.2"] }
1883
+ ];
1884
+ /** 从 fromVersion 升到当前版本时需要补播的官方新模型(只含新增项,已有条目不动)。 */
1885
+ function officialBackfillModels(fromVersion) {
1886
+ const out = {};
1887
+ PRICE_BACKFILL_ADDED.forEach((entry) => {
1888
+ if (fromVersion >= entry.version) return;
1889
+ entry.names.forEach((name) => {
1890
+ const presentation = MODEL_PRESENTATION[name];
1891
+ if (presentation === undefined) return;
1892
+ const priceEntry = catalogPriceEntry(presentation.price);
1893
+ if (priceEntry !== null) out[name] = priceEntry;
1894
+ });
1895
+ });
1896
+ return out;
1897
+ }
1898
+
1345
1899
  /* 节点上"这条记录发生在什么时候"在不同来源里可能叫不同名字:几个都试一遍。
1346
1900
  拿不到就返回 null —— 调用方据此判断"本轮起点未知"(`turnStartMs` 为 null),
1347
1901
  于是本轮不并队友(本轮只能小不能大),总计照旧按整会话并。 */
@@ -1507,11 +2061,25 @@ window.__ModuleLoader__.load({
1507
2061
  tipCreditsRefreshLatest: " · {date} 刷新(最近)",
1508
2062
  tipCreditsExpireLatest: " · {date} 到期(最近)",
1509
2063
  tipCreditsLeft: "剩余 {left} / {total}",
1510
- dragHint: "拖动排序",
2064
+
1511
2065
  secSegments: "统计字段",
1512
2066
  secSegmentsHint: "勾选显示;按住拖动调整顺序。",
1513
2067
  secPrices: "自定义模型价格",
1514
2068
  secPricesHint: "填写你使用的模型单价(每百万 tokens)。",
2069
+ /* 第三方平台(独立区块):平台档案 + 适用模型 + 按模型填费用倍率 */
2070
+ secPlatforms: "第三方平台",
2071
+ secPlatformsBadge: "实验性功能",
2072
+ secPlatformsHint: "按平台分别配置余额接口与费用倍率:填写余额接口地址后即可查询该平台余额,留空则仅按费用倍率计费。",
2073
+ platformNewPh: "平台名称",
2074
+ platformAdd: "添加平台",
2075
+ platformEmpty: "还没有第三方平台。",
2076
+ platformModels: "适用模型",
2077
+ platformModelSelectPh: "请选择模型",
2078
+ platformFeePh: "如 0.02",
2079
+ platformAddModel: "添加模型",
2080
+ platformNameDuplicate: "平台名称已存在。",
2081
+ platformSecretSaved: "已保存,留空保持不变",
2082
+ /* 中转站:费用倍率 + 余额查询。密钥只提交给本机后台,界面上不回显。 */
1515
2083
  segStatusHint: "自动判断当前的峰谷时段。",
1516
2084
  tipWeekTitle: "活跃总览",
1517
2085
  hoverCalls: "API请求次数",
@@ -1531,11 +2099,41 @@ window.__ModuleLoader__.load({
1531
2099
  unitCountSteps: " 步",
1532
2100
  unitCountCalls: " 次",
1533
2101
  unitSpeed: "t/s",
1534
- priceSuggestedHint: "价格库正使用官方参考价。",
2102
+ priceSuggestedHint: "价格库包含已核验的官方 API 报价;缺少明确价格的字段不会自动计费。",
2103
+ /* 费用倍率:只在「第三方平台」区块里按模型填 */
2104
+ priceFeeMultiplier: "费用倍率",
2105
+ priceFeeMultiplierInvalid: "费用倍率必须是 0–1000 之间的数字(留空 = 1)。",
2106
+ /* 中转站余额查询字段(密文只提交不回显) */
2107
+ /* 「请求头」是**用户 ID 的请求头**(New API 的 New-Api-User);令牌请求头固定 authorization + Bearer 前缀,
2108
+ 界面不暴露(见 saveDraft 的 POST)。placeholder 一律是浅色说明文字,不再出现「未配置 / 已配置」。 */
2109
+ priceTokenHeader: "请求头",
2110
+ priceTokenHeaderHint: "如 New-Api-User",
2111
+ priceToken: "令牌",
2112
+ priceTokenHint: "New API 填访问令牌;Sub2API 填登录令牌",
2113
+ priceUserId: "用户 ID",
2114
+ priceUserIdHint: "填写用户 ID",
2115
+ priceEndpoint: "余额查询地址",
2116
+ priceEndpointHint: "余额接口地址,如 https://xxx/api/user/self",
2117
+ priceBalanceField: "余额字段",
2118
+ priceBalanceFieldHint: "如 ¥data.quota / 500000",
2119
+ priceBalanceFieldInvalid: "余额字段格式不对,示例:¥data.quota / 500000。",
2120
+ priceEndpointInvalid: "余额查询地址必须以 http:// 或 https:// 开头。",
2121
+ priceRelaySyncFailed: "第三方平台配置同步失败({reason}),余额查询可能未生效。",
1535
2122
  priceNewModel: "自定义模型",
1536
2123
  priceAdd: "添加",
1537
2124
  priceEmpty: "价格库为空 —— 输入模型名(如 deepseek-flash)后点添加。",
1538
2125
  priceRemove: "删除",
2126
+ priceManufacturerDeepseek: "DeepSeek",
2127
+ priceManufacturerAnthropic: "Anthropic",
2128
+ priceManufacturerZhipu: "智谱",
2129
+ priceManufacturerAlibaba: "阿里云",
2130
+ priceManufacturerMoonshot: "月之暗面",
2131
+ priceManufacturerGoogle: "Google",
2132
+ priceManufacturerXai: "xAI",
2133
+ priceManufacturerXiaomi: "小米",
2134
+ priceManufacturerMuse: "Meta",
2135
+ priceManufacturerOpenai: "OpenAI",
2136
+ priceManufacturerCustom: "自定义模型",
1539
2137
  priceInput: "输入(缓存未命中)",
1540
2138
  priceCacheRead: "输入(缓存命中)",
1541
2139
  priceOutput: "输出",
@@ -1543,13 +2141,8 @@ window.__ModuleLoader__.load({
1543
2141
  priceEdit: "修改",
1544
2142
  priceSave: "保存",
1545
2143
  reset: "恢复默认设置",
1546
- holidayUpdate: "更新节假峰谷",
1547
2144
  starRepo: "GitHub支持",
1548
- starTip: "你的支持是我最大的动力!请帮我点亮Star吧~",
1549
- holidayUpdateBusy: "正在搜索节假安排...",
1550
- holidayUpdateOk: "已写入 {year} 年 {count} 个节假日",
1551
- holidayUpdateFail: "抓取失败({reason}),检查网络后重试",
1552
- holidayUpdateNoRoute: "状态栏后台还是旧版:完全退出并重启 DSH 后再点"
2145
+ starTip: "你的支持是我最大的动力!请帮我点亮Star吧~"
1553
2146
  };
1554
2147
  const en = {
1555
2148
  nav: "Status Bar",
@@ -1640,11 +2233,25 @@ window.__ModuleLoader__.load({
1640
2233
  tipCreditsRefreshLatest: " · refreshes {date} (nearest)",
1641
2234
  tipCreditsExpireLatest: " · expires {date} (nearest)",
1642
2235
  tipCreditsLeft: "{left} / {total} left",
1643
- dragHint: "Drag to reorder",
2236
+
1644
2237
  secSegments: "Stats fields",
1645
2238
  secSegmentsHint: "Select to show; drag to reorder.",
1646
2239
  secPrices: "Custom model prices",
1647
2240
  secPricesHint: "Prices per million tokens.",
2241
+ /* Third-party platforms (separate section): profiles + applicable models + per-model multipliers */
2242
+ secPlatforms: "Third-party platforms",
2243
+ secPlatformsBadge: "Experimental",
2244
+ secPlatformsHint: "Configure the balance endpoint and fee multiplier per platform: enter the balance endpoint to query that platform's balance; leave it blank to bill by the fee multiplier only.",
2245
+ platformNewPh: "Platform name",
2246
+ platformAdd: "Add platform",
2247
+ platformEmpty: "No third-party platforms yet.",
2248
+ platformModels: "Applicable models",
2249
+ platformModelSelectPh: "Select a model",
2250
+ platformFeePh: "e.g. 0.02",
2251
+ platformAddModel: "Add model",
2252
+ platformNameDuplicate: "This platform name already exists.",
2253
+ platformSecretSaved: "Saved — leave blank to keep it",
2254
+ /* Relay: fee multiplier + balance query. Secrets are only sent to the local backend. */
1648
2255
  segStatusHint: "Automatically determines the current peak / off-peak window.",
1649
2256
  tipWeekTitle: "Activity overview",
1650
2257
  hoverCalls: "API calls",
@@ -1664,12 +2271,41 @@ window.__ModuleLoader__.load({
1664
2271
  unitCountSteps: " steps",
1665
2272
  unitCountCalls: " calls",
1666
2273
  unitSpeed: "t/s",
1667
- priceSuggestedHint: "The price book uses the DeepSeek reference prices.",
2274
+ priceSuggestedHint: "The price book includes verified official API rates; fields without a confirmed price are excluded from automatic cost.",
2275
+ /* Fee multipliers are set per model inside the third-party platform section */
2276
+ priceFeeMultiplier: "Fee multiplier",
2277
+ priceFeeMultiplierInvalid: "Fee multiplier must be a number between 0 and 1000 (blank = 1).",
2278
+ /* "Header" is the **user ID header** (New API: New-Api-User); the token header is fixed to
2279
+ authorization + Bearer and is not exposed in the UI. */
2280
+ priceTokenHeader: "Header",
2281
+ priceTokenHeaderHint: "e.g. New-Api-User",
2282
+ priceToken: "Token",
2283
+ priceTokenHint: "New API: access token; Sub2API: login token",
2284
+ priceUserId: "User ID",
2285
+ priceUserIdHint: "Enter the user ID",
2286
+ priceEndpoint: "Balance endpoint",
2287
+ priceEndpointHint: "Balance endpoint, e.g. https://xxx/api/user/self",
2288
+ priceBalanceField: "Balance field",
2289
+ priceBalanceFieldHint: "e.g. ¥data.quota / 500000",
2290
+ priceBalanceFieldInvalid: "Invalid balance field, e.g. ¥data.quota / 500000.",
2291
+ priceEndpointInvalid: "Balance endpoint must start with http:// or https://.",
2292
+ priceRelaySyncFailed: "Third-party platform config sync failed ({reason}); balance query may not work.",
1668
2293
  f_balanceDash: "Balance {symbol}-",
1669
2294
  priceNewModel: "Custom model",
1670
2295
  priceAdd: "Add",
1671
2296
  priceEmpty: "Price book is empty — type a model name (e.g. deepseek-flash) and click Add.",
1672
2297
  priceRemove: "Remove",
2298
+ priceManufacturerDeepseek: "DeepSeek",
2299
+ priceManufacturerAnthropic: "Anthropic",
2300
+ priceManufacturerZhipu: "Zhipu",
2301
+ priceManufacturerAlibaba: "Alibaba",
2302
+ priceManufacturerMoonshot: "Moonshot",
2303
+ priceManufacturerGoogle: "Google",
2304
+ priceManufacturerXai: "xAI",
2305
+ priceManufacturerXiaomi: "Xiaomi",
2306
+ priceManufacturerMuse: "Meta",
2307
+ priceManufacturerOpenai: "OpenAI",
2308
+ priceManufacturerCustom: "Custom models",
1673
2309
  priceInput: "Input (cache miss)",
1674
2310
  priceCacheRead: "Input (cache hit)",
1675
2311
  priceOutput: "Output",
@@ -1677,13 +2313,962 @@ window.__ModuleLoader__.load({
1677
2313
  priceEdit: "Edit",
1678
2314
  priceSave: "Save",
1679
2315
  reset: "Reset settings",
1680
- holidayUpdate: "Update holidays",
1681
2316
  starRepo: "Support on GitHub",
1682
- starTip: "Your support means a lot to me — please give it a star!",
1683
- holidayUpdateBusy: "Searching the holiday schedule...",
1684
- holidayUpdateOk: "Wrote {count} holidays for {year}",
1685
- holidayUpdateFail: "Fetch failed ({reason}); check the network and retry",
1686
- holidayUpdateNoRoute: "The status bar backend is still the old build — fully quit and restart DSH, then try again"
2317
+ starTip: "Your support means a lot to me — please give it a star!"
2318
+ };
2319
+ const ja = {
2320
+ "nav": "ステータスバー",
2321
+ "updatePill": "アップデートあり",
2322
+ "updateTo": "{version} に更新",
2323
+ "updateRunning": "更新中",
2324
+ "updateFailed": "更新に失敗しました",
2325
+ "updateDone": "更新が完了しました — 反映するには DSH を再起動してください",
2326
+ "updateErrorTruncated": "(出力が長いため、末尾 {limit} 文字を表示しています — 全文はログを参照してください)",
2327
+ "updateErrorCopy": "コピー",
2328
+ "updateErrorCopied": "コピーしました",
2329
+ "devModeBadge": "開発モード",
2330
+ "devModeHint": "開発モード:更新ボタンは状態をシミュレートするだけで、何もインストールされません",
2331
+ "sectionTitle": "ステータスバー設定",
2332
+ "intro": "メッセージ入力欄の下の統計行を置き換えます。表示する項目の選択、ドラッグでの並べ替え、モデル価格の設定ができます。",
2333
+ "segContext": "コンテキスト使用量",
2334
+ "segContextHint": "コンテキスト占有の内訳と圧縮のしきい値。",
2335
+ "segStatus": "ピーク/オフピーク判定",
2336
+ "segCounts": "ターン数とステップ数",
2337
+ "segTtft": "初回トークンまでの時間",
2338
+ "segCacheHit": "キャッシュヒット率",
2339
+ "segTps": "毎秒トークン数",
2340
+ "segSessionTime": "実行時間",
2341
+ "segCost": "セッション費用",
2342
+ "segLastCost": "今回のターン費用",
2343
+ "segBalance": "残高",
2344
+ "tipEmptyTitle": "{label}",
2345
+ "tipEmptyBody": "この項目には現在データがありません。開発モードでは、開くと次のフィクスチャシーンに進み、ここで止まることはありません。",
2346
+ "f_peak": "ピーク",
2347
+ "f_valley": "オフピーク",
2348
+ "f_counts": "{turns} ターン · {steps} ステップ",
2349
+ "f_ttft": "TTFT {duration}",
2350
+ "f_cacheHit": "合計ヒット {percent}%",
2351
+ "f_tokensHit": "入力(キャッシュヒット)",
2352
+ "f_tokensMiss": "入力(キャッシュミス)",
2353
+ "f_tokensOut": "出力",
2354
+ "f_tokensTotal": "合計使用量",
2355
+ "f_tokensTurn": "今回のターン使用量",
2356
+ "tipModelTime": "モデル時間",
2357
+ "tipWaitTime": "待機時間",
2358
+ "tipToolTime": "ツール呼び出し",
2359
+ "tipTtftTurn": "今回のターンの平均 TTFT",
2360
+ "tipTtftFast": "最速 TTFT",
2361
+ "tipTtftSlow": "最遅 TTFT",
2362
+ "tipTpsTurn": "今回のターンの平均 TPS",
2363
+ "tipTpsFast": "最速 TPS",
2364
+ "tipTpsSlow": "最遅 TPS",
2365
+ "tipTopUp": "チャージ残高",
2366
+ "tipGranted": "付与残高",
2367
+ "tipQuotaLeft": "残りクォータ",
2368
+ "tipHitTurn": "今回のターンのヒット率",
2369
+ "tipHitHigh": "最高ヒット率",
2370
+ "tipHitLow": "最低ヒット率",
2371
+ "tipCountsTitle": "セッションデータ",
2372
+ "tipCountsSkills": "インジェクト済みスキル",
2373
+ "tipCountsCompactAt": "コンテキスト圧縮回数",
2374
+ "tipCountsToolCalls": "ツール呼び出し",
2375
+ "tipManual": "手動呼び出し",
2376
+ "tipSub": "サブスキル",
2377
+ "tipCompactItem": "圧縮 {index}",
2378
+ "tipCompactWhere": "ターン {turn}·ステップ {step}",
2379
+ "tipCompactTurnOnly": "ターン {turn}",
2380
+ "tipCompactAfter": "ターン {turn} の後",
2381
+ "contextAria": "コンテキストの {percent} を使用",
2382
+ "contextSystem": "システムプロンプト",
2383
+ "contextTools": "ツール定義",
2384
+ "contextMessages": "メッセージ",
2385
+ "f_speed": "TPS {throughput}t/s",
2386
+ "f_sessionTime": "時間 {duration}",
2387
+ "f_cost": "合計 {symbol}{cost}",
2388
+ "priceTierPeak": "ピーク",
2389
+ "priceTierOffPeak": "オフピーク",
2390
+ "priceTierAllDay": "終日",
2391
+ "f_lastCost": "今回 {symbol}{cost}",
2392
+ "f_balance": "残高 {symbol}{amount}",
2393
+ "f_balanceSubCent": "残高 <{symbol}0.01",
2394
+ "tipCreditsTitle": "ポイントパッケージ",
2395
+ "tipCreditsMonthly": "(月額)",
2396
+ "tipCreditsRefresh": " · {date} 更新",
2397
+ "tipCreditsExpire": " · {date} 期限",
2398
+ "tipCreditsRefreshLatest": " · {date} 更新(直近)",
2399
+ "tipCreditsExpireLatest": " · {date} 期限(直近)",
2400
+ "tipCreditsLeft": "残り {left} / {total}",
2401
+ "secSegments": "統計項目",
2402
+ "secSegmentsHint": "選択して表示、ドラッグで並べ替え。",
2403
+ "secPrices": "カスタムモデル価格",
2404
+ "secPricesHint": "100 万トークンあたりの価格。",
2405
+ "secPlatforms": "サードパーティプラットフォーム",
2406
+ "secPlatformsBadge": "試験的",
2407
+ "secPlatformsHint": "プラットフォームごとに残高エンドポイントと料率倍率を設定します:残高エンドポイントを入力すると残高を照会でき、空欄の場合は料率倍率のみで計算します。",
2408
+ "platformNewPh": "プラットフォーム名",
2409
+ "platformAdd": "プラットフォームを追加",
2410
+ "platformEmpty": "サードパーティプラットフォームはまだありません。",
2411
+ "platformModels": "対象モデル",
2412
+ "platformModelSelectPh": "モデルを選択",
2413
+ "platformFeePh": "例:0.02",
2414
+ "platformAddModel": "モデルを追加",
2415
+ "platformNameDuplicate": "このプラットフォーム名は既に存在します。",
2416
+ "platformSecretSaved": "保存済み — 変更しない場合は空欄のままにしてください",
2417
+ "segStatusHint": "現在のピーク/オフピーク時間帯を自動判定します。",
2418
+ "tipWeekTitle": "アクティビティ概要",
2419
+ "hoverCalls": "API 呼び出し",
2420
+ "hoverCost": "費用",
2421
+ "hoverYearAll": "通年",
2422
+ "segCountsHint": "現在のセッションの合計ターン数と実行ステップ数。",
2423
+ "segTtftHint": "初回トークンまでの平均時間。",
2424
+ "segCacheHitHint": "現在のセッションの平均キャッシュヒット率。",
2425
+ "segTpsHint": "平均出力速度(毎秒トークン数)。",
2426
+ "segSessionTimeHint": "現在のセッションの合計実行時間。",
2427
+ "segCostHint": "メインモデル、サブエージェント、補助呼び出しを含むセッション費用の推定値。",
2428
+ "segLastCostHint": "メインモデル、サブエージェント、補助呼び出しを含む、現在または直近のターン費用の推定値。",
2429
+ "segBalanceHint": "アカウント残高(1 分ごとに更新)。",
2430
+ "priceCurrent": "現在のセッション:",
2431
+ "modelUnknown": "不明",
2432
+ "unitCountTurns": " ターン",
2433
+ "unitCountSteps": " ステップ",
2434
+ "unitCountCalls": " 回",
2435
+ "unitSpeed": "t/s",
2436
+ "priceSuggestedHint": "価格表には検証済みの公式 API 料金が含まれています。確定価格のない項目は自動費用計算から除外されます。",
2437
+ "priceFeeMultiplier": "料率倍率",
2438
+ "priceFeeMultiplierInvalid": "料率倍率は 0〜1000 の数値で入力してください(空欄=1)。",
2439
+ "priceTokenHeader": "ヘッダー",
2440
+ "priceTokenHeaderHint": "例:New-Api-User",
2441
+ "priceToken": "Token",
2442
+ "priceTokenHint": "New API:アクセストークン、Sub2API:ログイントークン",
2443
+ "priceUserId": "ユーザー ID",
2444
+ "priceUserIdHint": "ユーザー ID を入力",
2445
+ "priceEndpoint": "残高エンドポイント",
2446
+ "priceEndpointHint": "残高エンドポイント(例:https://xxx/api/user/self)",
2447
+ "priceBalanceField": "残高フィールド",
2448
+ "priceBalanceFieldHint": "例:¥data.quota / 500000",
2449
+ "priceBalanceFieldInvalid": "残高フィールドが無効です(例:¥data.quota / 500000)。",
2450
+ "priceEndpointInvalid": "残高エンドポイントは http:// または https:// で始まる必要があります。",
2451
+ "priceRelaySyncFailed": "サードパーティプラットフォーム設定の同期に失敗しました({reason})。残高照会が機能しない可能性があります。",
2452
+ "f_balanceDash": "残高 {symbol}-",
2453
+ "priceNewModel": "カスタムモデル",
2454
+ "priceAdd": "追加",
2455
+ "priceEmpty": "価格表は空です — モデル名(例:deepseek-flash)を入力して「追加」をクリックしてください。",
2456
+ "priceRemove": "削除",
2457
+ "priceManufacturerDeepseek": "DeepSeek",
2458
+ "priceManufacturerAnthropic": "Anthropic",
2459
+ "priceManufacturerZhipu": "Zhipu",
2460
+ "priceManufacturerAlibaba": "Alibaba",
2461
+ "priceManufacturerMoonshot": "Moonshot",
2462
+ "priceManufacturerGoogle": "Google",
2463
+ "priceManufacturerXai": "xAI",
2464
+ "priceManufacturerXiaomi": "Xiaomi",
2465
+ "priceManufacturerMuse": "Meta",
2466
+ "priceManufacturerOpenai": "OpenAI",
2467
+ "priceManufacturerCustom": "カスタムモデル",
2468
+ "priceInput": "入力(キャッシュミス)",
2469
+ "priceCacheRead": "入力(キャッシュヒット)",
2470
+ "priceOutput": "出力",
2471
+ "priceTiered": "ピーク/オフピーク料金",
2472
+ "priceEdit": "編集",
2473
+ "priceSave": "保存",
2474
+ "reset": "設定をリセット",
2475
+ "starRepo": "GitHub で応援",
2476
+ "starTip": "応援がとても励みになります — ぜひスターをお願いします!"
2477
+ };
2478
+ const es = {
2479
+ "nav": "Barra de estado",
2480
+ "updatePill": "Actualización disponible",
2481
+ "updateTo": "Actualizar a {version}",
2482
+ "updateRunning": "Actualizando",
2483
+ "updateFailed": "Error de actualización",
2484
+ "updateDone": "Actualización completada: reinicia DSH para aplicarla",
2485
+ "updateErrorTruncated": "(la salida es extensa; se muestran los últimos {limit} caracteres; consulta el registro para ver el texto completo)",
2486
+ "updateErrorCopy": "Copiar",
2487
+ "updateErrorCopied": "Copiado",
2488
+ "devModeBadge": "Modo desarrollador",
2489
+ "devModeHint": "Modo desarrollador: el botón de actualización solo simula estados; no se instala nada",
2490
+ "sectionTitle": "Ajustes de la barra de estado",
2491
+ "intro": "Sustituye la línea de estadísticas bajo el campo de mensaje. Selecciona los campos que quieres mostrar, arrástralos para reordenarlos o configura los precios de los modelos.",
2492
+ "segContext": "Uso de contexto",
2493
+ "segContextHint": "Desglose de la ocupación del contexto y umbral de compactación.",
2494
+ "segStatus": "Comprobación de horas punta y valle",
2495
+ "segCounts": "Turnos y pasos",
2496
+ "segTtft": "Tiempo hasta el primer token",
2497
+ "segCacheHit": "Tasa de aciertos de caché",
2498
+ "segTps": "Tokens por segundo",
2499
+ "segSessionTime": "Tiempo de ejecución",
2500
+ "segCost": "Coste de la sesión",
2501
+ "segLastCost": "Coste de este turno",
2502
+ "segBalance": "Saldo",
2503
+ "tipEmptyTitle": "{label}",
2504
+ "tipEmptyBody": "Este campo no tiene datos en este momento. En modo desarrollador, al abrirlo se pasa a la siguiente escena de prueba en lugar de quedarse aquí.",
2505
+ "f_peak": "Punta",
2506
+ "f_valley": "Valle",
2507
+ "f_counts": "{turns} turnos · {steps} pasos",
2508
+ "f_ttft": "TTFT {duration}",
2509
+ "f_cacheHit": "Aciertos combinados {percent}%",
2510
+ "f_tokensHit": "entrada (acierto de caché)",
2511
+ "f_tokensMiss": "entrada (fallo de caché)",
2512
+ "f_tokensOut": "salida",
2513
+ "f_tokensTotal": "Uso total",
2514
+ "f_tokensTurn": "Uso de este turno",
2515
+ "tipModelTime": "Tiempo del modelo",
2516
+ "tipWaitTime": "Tiempo de espera",
2517
+ "tipToolTime": "Llamadas a herramientas",
2518
+ "tipTtftTurn": "TTFT medio de este turno",
2519
+ "tipTtftFast": "TTFT más rápido",
2520
+ "tipTtftSlow": "TTFT más lento",
2521
+ "tipTpsTurn": "TPS medio de este turno",
2522
+ "tipTpsFast": "TPS más alto",
2523
+ "tipTpsSlow": "TPS más bajo",
2524
+ "tipTopUp": "Saldo recargado",
2525
+ "tipGranted": "Saldo otorgado",
2526
+ "tipQuotaLeft": "Cuota restante",
2527
+ "tipHitTurn": "Tasa de aciertos de este turno",
2528
+ "tipHitHigh": "Tasa de aciertos más alta",
2529
+ "tipHitLow": "Tasa de aciertos más baja",
2530
+ "tipCountsTitle": "Datos de la sesión",
2531
+ "tipCountsSkills": "Skills inyectadas",
2532
+ "tipCountsCompactAt": "Compactaciones de contexto",
2533
+ "tipCountsToolCalls": "Llamadas a herramientas",
2534
+ "tipManual": "Invocada manualmente",
2535
+ "tipSub": "Subskill",
2536
+ "tipCompactItem": "Compactación {index}",
2537
+ "tipCompactWhere": "Turno {turn}·Paso {step}",
2538
+ "tipCompactTurnOnly": "Turno {turn}",
2539
+ "tipCompactAfter": "Tras el turno {turn}",
2540
+ "contextAria": "{percent} de contexto usado",
2541
+ "contextSystem": "Prompt del sistema",
2542
+ "contextTools": "Definiciones de herramientas",
2543
+ "contextMessages": "Mensajes",
2544
+ "f_speed": "TPS {throughput}t/s",
2545
+ "f_sessionTime": "Tiempo {duration}",
2546
+ "f_cost": "Total {symbol}{cost}",
2547
+ "priceTierPeak": "Punta",
2548
+ "priceTierOffPeak": "Valle",
2549
+ "priceTierAllDay": "Todo el día",
2550
+ "f_lastCost": "Este turno {symbol}{cost}",
2551
+ "f_balance": "Saldo {symbol}{amount}",
2552
+ "f_balanceSubCent": "Saldo <{symbol}0.01",
2553
+ "tipCreditsTitle": "Paquetes de puntos",
2554
+ "tipCreditsMonthly": " (mensual)",
2555
+ "tipCreditsRefresh": " · se renueva {date}",
2556
+ "tipCreditsExpire": " · caduca {date}",
2557
+ "tipCreditsRefreshLatest": " · se renueva {date} (próxima)",
2558
+ "tipCreditsExpireLatest": " · caduca {date} (próxima)",
2559
+ "tipCreditsLeft": "Quedan {left} / {total}",
2560
+ "secSegments": "Campos de estadísticas",
2561
+ "secSegmentsHint": "Marca para mostrar; arrastra para reordenar.",
2562
+ "secPrices": "Precios personalizados de modelos",
2563
+ "secPricesHint": "Precios por millón de tokens.",
2564
+ "secPlatforms": "Plataformas de terceros",
2565
+ "secPlatformsBadge": "Experimental",
2566
+ "secPlatformsHint": "Configure por plataforma el endpoint de saldo y el multiplicador de tarifa: al introducir el endpoint se consulta el saldo; si se deja vacío, solo se aplica el multiplicador.",
2567
+ "platformNewPh": "Nombre de la plataforma",
2568
+ "platformAdd": "Añadir plataforma",
2569
+ "platformEmpty": "Aún no hay plataformas de terceros.",
2570
+ "platformModels": "Modelos aplicables",
2571
+ "platformModelSelectPh": "Selecciona un modelo",
2572
+ "platformFeePh": "p. ej. 0.02",
2573
+ "platformAddModel": "Añadir modelo",
2574
+ "platformNameDuplicate": "Este nombre de plataforma ya existe.",
2575
+ "platformSecretSaved": "Guardado: déjalo en blanco para conservarlo",
2576
+ "segStatusHint": "Determina automáticamente la franja actual de punta o valle.",
2577
+ "tipWeekTitle": "Resumen de actividad",
2578
+ "hoverCalls": "Llamadas a la API",
2579
+ "hoverCost": "Coste",
2580
+ "hoverYearAll": "año completo",
2581
+ "segCountsHint": "Número total de turnos y pasos ejecutados de la sesión actual.",
2582
+ "segTtftHint": "Tiempo medio hasta el primer token.",
2583
+ "segCacheHitHint": "Tasa media de aciertos de caché de la sesión actual.",
2584
+ "segTpsHint": "Tasa media de salida, en tokens por segundo.",
2585
+ "segSessionTimeHint": "Tiempo total de ejecución de la sesión actual.",
2586
+ "segCostHint": "Coste estimado de la sesión, incluidos el modelo principal, los subagentes y las llamadas auxiliares.",
2587
+ "segLastCostHint": "Coste estimado del turno actual o del más reciente, incluidos el modelo principal, los subagentes y las llamadas auxiliares.",
2588
+ "segBalanceHint": "Saldo de la cuenta, actualizado cada minuto.",
2589
+ "priceCurrent": "Sesión actual:",
2590
+ "modelUnknown": "desconocido",
2591
+ "unitCountTurns": " turnos",
2592
+ "unitCountSteps": " pasos",
2593
+ "unitCountCalls": " llamadas",
2594
+ "unitSpeed": "t/s",
2595
+ "priceSuggestedHint": "La lista de precios incluye tarifas oficiales de la API verificadas; los campos sin un precio confirmado se excluyen del coste automático.",
2596
+ "priceFeeMultiplier": "Multiplicador de tarifa",
2597
+ "priceFeeMultiplierInvalid": "El multiplicador de tarifa debe ser un número entre 0 y 1000 (en blanco = 1).",
2598
+ "priceTokenHeader": "Encabezado",
2599
+ "priceTokenHeaderHint": "p. ej. New-Api-User",
2600
+ "priceToken": "Token",
2601
+ "priceTokenHint": "New API: token de acceso; Sub2API: token de inicio de sesión",
2602
+ "priceUserId": "ID de usuario",
2603
+ "priceUserIdHint": "Introduce el ID de usuario",
2604
+ "priceEndpoint": "Endpoint de saldo",
2605
+ "priceEndpointHint": "Endpoint de saldo, p. ej. https://xxx/api/user/self",
2606
+ "priceBalanceField": "Campo de saldo",
2607
+ "priceBalanceFieldHint": "p. ej. ¥data.quota / 500000",
2608
+ "priceBalanceFieldInvalid": "Campo de saldo no válido, p. ej. ¥data.quota / 500000.",
2609
+ "priceEndpointInvalid": "El endpoint de saldo debe empezar por http:// o https://.",
2610
+ "priceRelaySyncFailed": "Error al sincronizar la configuración de la plataforma de terceros ({reason}); es posible que la consulta de saldo no funcione.",
2611
+ "f_balanceDash": "Saldo {symbol}-",
2612
+ "priceNewModel": "Modelo personalizado",
2613
+ "priceAdd": "Añadir",
2614
+ "priceEmpty": "La lista de precios está vacía: escribe un nombre de modelo (p. ej. deepseek-flash) y haz clic en Añadir.",
2615
+ "priceRemove": "Quitar",
2616
+ "priceManufacturerDeepseek": "DeepSeek",
2617
+ "priceManufacturerAnthropic": "Anthropic",
2618
+ "priceManufacturerZhipu": "Zhipu",
2619
+ "priceManufacturerAlibaba": "Alibaba",
2620
+ "priceManufacturerMoonshot": "Moonshot",
2621
+ "priceManufacturerGoogle": "Google",
2622
+ "priceManufacturerXai": "xAI",
2623
+ "priceManufacturerXiaomi": "Xiaomi",
2624
+ "priceManufacturerMuse": "Meta",
2625
+ "priceManufacturerOpenai": "OpenAI",
2626
+ "priceManufacturerCustom": "Modelos personalizados",
2627
+ "priceInput": "Entrada (fallo de caché)",
2628
+ "priceCacheRead": "Entrada (acierto de caché)",
2629
+ "priceOutput": "Salida",
2630
+ "priceTiered": "Precios de punta y valle",
2631
+ "priceEdit": "Editar",
2632
+ "priceSave": "Guardar",
2633
+ "reset": "Restablecer ajustes",
2634
+ "starRepo": "Apóyanos en GitHub",
2635
+ "starTip": "Tu apoyo significa mucho para mí: ¡dale una estrella!"
2636
+ };
2637
+ const fr = {
2638
+ "nav": "Barre d'état",
2639
+ "updatePill": "Mise à jour disponible",
2640
+ "updateTo": "Mettre à jour vers {version}",
2641
+ "updateRunning": "Mise à jour en cours",
2642
+ "updateFailed": "Échec de la mise à jour",
2643
+ "updateDone": "Mise à jour réussie — redémarrez DSH pour l'appliquer",
2644
+ "updateErrorTruncated": "(sortie longue ; affichage des {limit} derniers caractères — consultez le journal pour le texte complet)",
2645
+ "updateErrorCopy": "Copier",
2646
+ "updateErrorCopied": "Copié",
2647
+ "devModeBadge": "Mode dev",
2648
+ "devModeHint": "Mode dev : le bouton de mise à jour ne fait que simuler des états — rien n'est installé",
2649
+ "sectionTitle": "Paramètres de la barre d'état",
2650
+ "intro": "Remplace la ligne de statistiques sous le champ de saisie. Sélectionnez les champs à afficher, faites-les glisser pour les réorganiser ou définissez le prix des modèles.",
2651
+ "segContext": "Utilisation du contexte",
2652
+ "segContextHint": "Détail de l'occupation du contexte et seuil de compactage.",
2653
+ "segStatus": "Vérification heures pleines / creuses",
2654
+ "segCounts": "Tours et étapes",
2655
+ "segTtft": "Délai avant le premier token",
2656
+ "segCacheHit": "Taux de cache",
2657
+ "segTps": "Tokens par seconde",
2658
+ "segSessionTime": "Durée d'exécution",
2659
+ "segCost": "Coût de la session",
2660
+ "segLastCost": "Coût de ce tour",
2661
+ "segBalance": "Solde",
2662
+ "tipEmptyTitle": "{label}",
2663
+ "tipEmptyBody": "Ce champ n'a aucune donnée pour le moment. En mode dev, l'ouvrir passe à la scène de test suivante au lieu de vous bloquer ici.",
2664
+ "f_peak": "Heures pleines",
2665
+ "f_valley": "Heures creuses",
2666
+ "f_counts": "{turns} tours · {steps} étapes",
2667
+ "f_ttft": "TTFT {duration}",
2668
+ "f_cacheHit": "Cache combiné {percent} %",
2669
+ "f_tokensHit": "entrée (cache)",
2670
+ "f_tokensMiss": "entrée (sans cache)",
2671
+ "f_tokensOut": "sortie",
2672
+ "f_tokensTotal": "Utilisation totale",
2673
+ "f_tokensTurn": "Utilisation de ce tour",
2674
+ "tipModelTime": "Temps du modèle",
2675
+ "tipWaitTime": "Temps d'attente",
2676
+ "tipToolTime": "Appels d'outils",
2677
+ "tipTtftTurn": "TTFT moyen de ce tour",
2678
+ "tipTtftFast": "TTFT le plus rapide",
2679
+ "tipTtftSlow": "TTFT le plus lent",
2680
+ "tipTpsTurn": "TPS moyen de ce tour",
2681
+ "tipTpsFast": "TPS le plus rapide",
2682
+ "tipTpsSlow": "TPS le plus lent",
2683
+ "tipTopUp": "Solde rechargé",
2684
+ "tipGranted": "Solde offert",
2685
+ "tipQuotaLeft": "Quota restant",
2686
+ "tipHitTurn": "Taux de cache de ce tour",
2687
+ "tipHitHigh": "Taux de cache le plus élevé",
2688
+ "tipHitLow": "Taux de cache le plus bas",
2689
+ "tipCountsTitle": "Données de la session",
2690
+ "tipCountsSkills": "Skills injectés",
2691
+ "tipCountsCompactAt": "Compactages du contexte",
2692
+ "tipCountsToolCalls": "Appels d'outils",
2693
+ "tipManual": "Invoqué manuellement",
2694
+ "tipSub": "Sous-skill",
2695
+ "tipCompactItem": "Compactage {index}",
2696
+ "tipCompactWhere": "Tour {turn}·Étape {step}",
2697
+ "tipCompactTurnOnly": "Tour {turn}",
2698
+ "tipCompactAfter": "Après le tour {turn}",
2699
+ "contextAria": "{percent} du contexte utilisé",
2700
+ "contextSystem": "Prompt système",
2701
+ "contextTools": "Définitions d'outils",
2702
+ "contextMessages": "Messages",
2703
+ "f_speed": "TPS {throughput} t/s",
2704
+ "f_sessionTime": "Durée {duration}",
2705
+ "f_cost": "Total {symbol}{cost}",
2706
+ "priceTierPeak": "Heures pleines",
2707
+ "priceTierOffPeak": "Heures creuses",
2708
+ "priceTierAllDay": "Toute la journée",
2709
+ "f_lastCost": "Ce tour {symbol}{cost}",
2710
+ "f_balance": "Solde {symbol}{amount}",
2711
+ "f_balanceSubCent": "Solde <{symbol}0.01",
2712
+ "tipCreditsTitle": "Forfaits de points",
2713
+ "tipCreditsMonthly": " (mensuel)",
2714
+ "tipCreditsRefresh": " · renouvelé le {date}",
2715
+ "tipCreditsExpire": " · expire le {date}",
2716
+ "tipCreditsRefreshLatest": " · renouvelé le {date} (le plus proche)",
2717
+ "tipCreditsExpireLatest": " · expire le {date} (le plus proche)",
2718
+ "tipCreditsLeft": "{left} / {total} restants",
2719
+ "secSegments": "Champs de statistiques",
2720
+ "secSegmentsHint": "Sélectionnez pour afficher ; faites glisser pour réorganiser.",
2721
+ "secPrices": "Prix des modèles personnalisés",
2722
+ "secPricesHint": "Prix par million de tokens.",
2723
+ "secPlatforms": "Plateformes tierces",
2724
+ "secPlatformsBadge": "Expérimental",
2725
+ "secPlatformsHint": "Configurez par plateforme l'URL de solde et le multiplicateur de frais : renseignez l'URL pour consulter le solde ; laissez-la vide pour n'appliquer que le multiplicateur.",
2726
+ "platformNewPh": "Nom de la plateforme",
2727
+ "platformAdd": "Ajouter une plateforme",
2728
+ "platformEmpty": "Aucune plateforme tierce pour le moment.",
2729
+ "platformModels": "Modèles applicables",
2730
+ "platformModelSelectPh": "Sélectionner un modèle",
2731
+ "platformFeePh": "ex. 0.02",
2732
+ "platformAddModel": "Ajouter un modèle",
2733
+ "platformNameDuplicate": "Ce nom de plateforme existe déjà.",
2734
+ "platformSecretSaved": "Enregistré — laissez vide pour le conserver",
2735
+ "segStatusHint": "Détermine automatiquement la plage heures pleines / creuses actuelle.",
2736
+ "tipWeekTitle": "Aperçu de l'activité",
2737
+ "hoverCalls": "Appels API",
2738
+ "hoverCost": "Coût",
2739
+ "hoverYearAll": "année entière",
2740
+ "segCountsHint": "Nombre total de tours et d'étapes exécutées de la session actuelle.",
2741
+ "segTtftHint": "Délai moyen avant le premier token.",
2742
+ "segCacheHitHint": "Taux de cache moyen de la session actuelle.",
2743
+ "segTpsHint": "Débit de sortie moyen, en tokens par seconde.",
2744
+ "segSessionTimeHint": "Durée d'exécution totale de la session actuelle.",
2745
+ "segCostHint": "Coût estimé de la session, incluant le modèle principal, les sous-agents et les appels auxiliaires.",
2746
+ "segLastCostHint": "Coût estimé du tour actuel ou le plus récent, incluant le modèle principal, les sous-agents et les appels auxiliaires.",
2747
+ "segBalanceHint": "Solde du compte, actualisé chaque minute.",
2748
+ "priceCurrent": "Session actuelle :",
2749
+ "modelUnknown": "inconnu",
2750
+ "unitCountTurns": " tours",
2751
+ "unitCountSteps": " étapes",
2752
+ "unitCountCalls": " appels",
2753
+ "unitSpeed": "t/s",
2754
+ "priceSuggestedHint": "Le catalogue de prix inclut des tarifs API officiels vérifiés ; les champs sans prix confirmé sont exclus du calcul automatique des coûts.",
2755
+ "priceFeeMultiplier": "Multiplicateur de frais",
2756
+ "priceFeeMultiplierInvalid": "Le multiplicateur de frais doit être un nombre entre 0 et 1000 (vide = 1).",
2757
+ "priceTokenHeader": "En-tête",
2758
+ "priceTokenHeaderHint": "ex. New-Api-User",
2759
+ "priceToken": "Token",
2760
+ "priceTokenHint": "New API : token d'accès ; Sub2API : token de connexion",
2761
+ "priceUserId": "ID utilisateur",
2762
+ "priceUserIdHint": "Saisissez l'ID utilisateur",
2763
+ "priceEndpoint": "Endpoint de solde",
2764
+ "priceEndpointHint": "Endpoint de solde, ex. https://xxx/api/user/self",
2765
+ "priceBalanceField": "Champ de solde",
2766
+ "priceBalanceFieldHint": "ex. ¥data.quota / 500000",
2767
+ "priceBalanceFieldInvalid": "Champ de solde invalide, ex. ¥data.quota / 500000.",
2768
+ "priceEndpointInvalid": "L'endpoint de solde doit commencer par http:// ou https://.",
2769
+ "priceRelaySyncFailed": "Échec de la synchronisation de la config de la plateforme tierce ({reason}) ; la requête de solde peut ne pas fonctionner.",
2770
+ "f_balanceDash": "Solde {symbol}-",
2771
+ "priceNewModel": "Modèle personnalisé",
2772
+ "priceAdd": "Ajouter",
2773
+ "priceEmpty": "Le catalogue de prix est vide — saisissez un nom de modèle (ex. deepseek-flash) et cliquez sur Ajouter.",
2774
+ "priceRemove": "Supprimer",
2775
+ "priceManufacturerDeepseek": "DeepSeek",
2776
+ "priceManufacturerAnthropic": "Anthropic",
2777
+ "priceManufacturerZhipu": "Zhipu",
2778
+ "priceManufacturerAlibaba": "Alibaba",
2779
+ "priceManufacturerMoonshot": "Moonshot",
2780
+ "priceManufacturerGoogle": "Google",
2781
+ "priceManufacturerXai": "xAI",
2782
+ "priceManufacturerXiaomi": "Xiaomi",
2783
+ "priceManufacturerMuse": "Meta",
2784
+ "priceManufacturerOpenai": "OpenAI",
2785
+ "priceManufacturerCustom": "Modèles personnalisés",
2786
+ "priceInput": "Entrée (sans cache)",
2787
+ "priceCacheRead": "Entrée (cache)",
2788
+ "priceOutput": "Sortie",
2789
+ "priceTiered": "Tarification heures pleines / creuses",
2790
+ "priceEdit": "Modifier",
2791
+ "priceSave": "Enregistrer",
2792
+ "reset": "Réinitialiser les paramètres",
2793
+ "starRepo": "Soutenir sur GitHub",
2794
+ "starTip": "Votre soutien compte beaucoup pour moi — n'hésitez pas à mettre une étoile !"
2795
+ };
2796
+ const de = {
2797
+ "nav": "Statusleiste",
2798
+ "updatePill": "Update verfügbar",
2799
+ "updateTo": "Auf {version} aktualisieren",
2800
+ "updateRunning": "Wird aktualisiert",
2801
+ "updateFailed": "Update fehlgeschlagen",
2802
+ "updateDone": "Update erfolgreich – DSH neu starten, um es anzuwenden",
2803
+ "updateErrorTruncated": "(Ausgabe ist lang; es werden die letzten {limit} Zeichen angezeigt – den vollständigen Text siehst du im Protokoll)",
2804
+ "updateErrorCopy": "Kopieren",
2805
+ "updateErrorCopied": "Kopiert",
2806
+ "devModeBadge": "Dev-Modus",
2807
+ "devModeHint": "Dev-Modus: Die Update-Schaltfläche simuliert nur Zustände – es wird nichts installiert",
2808
+ "sectionTitle": "Einstellungen der Statusleiste",
2809
+ "intro": "Ersetzt die Statistikzeile unter der Eingabe. Felder zum Anzeigen auswählen, per Ziehen sortieren oder Modellpreise festlegen.",
2810
+ "segContext": "Kontextauslastung",
2811
+ "segContextHint": "Aufschlüsselung der Kontextbelegung und Komprimierungsschwelle.",
2812
+ "segStatus": "Spitzen-/Nebenzeiten-Anzeige",
2813
+ "segCounts": "Turns & Schritte",
2814
+ "segTtft": "Zeit bis zum ersten Token",
2815
+ "segCacheHit": "Cache-Trefferquote",
2816
+ "segTps": "Token pro Sekunde",
2817
+ "segSessionTime": "Laufzeit",
2818
+ "segCost": "Sitzungskosten",
2819
+ "segLastCost": "Kosten dieses Turns",
2820
+ "segBalance": "Guthaben",
2821
+ "tipEmptyTitle": "{label}",
2822
+ "tipEmptyBody": "Für dieses Feld liegen gerade keine Daten vor. Im Dev-Modus wechselt das Öffnen zur nächsten Testszene, statt dich hier festzuhalten.",
2823
+ "f_peak": "Spitze",
2824
+ "f_valley": "Nebenzeiten",
2825
+ "f_counts": "{turns} Turns · {steps} Schritte",
2826
+ "f_ttft": "TTFT {duration}",
2827
+ "f_cacheHit": "Treffer gesamt {percent} %",
2828
+ "f_tokensHit": "Eingabe (Cache-Treffer)",
2829
+ "f_tokensMiss": "Eingabe (Cache-Fehltreffer)",
2830
+ "f_tokensOut": "Ausgabe",
2831
+ "f_tokensTotal": "Nutzung gesamt",
2832
+ "f_tokensTurn": "Nutzung dieses Turns",
2833
+ "tipModelTime": "Modellzeit",
2834
+ "tipWaitTime": "Wartezeit",
2835
+ "tipToolTime": "Tool-Aufrufe",
2836
+ "tipTtftTurn": "Durchschnittliche TTFT dieses Turns",
2837
+ "tipTtftFast": "Schnellste TTFT",
2838
+ "tipTtftSlow": "Langsamste TTFT",
2839
+ "tipTpsTurn": "Durchschnittliche TPS dieses Turns",
2840
+ "tipTpsFast": "Höchste TPS",
2841
+ "tipTpsSlow": "Niedrigste TPS",
2842
+ "tipTopUp": "Aufgeladenes Guthaben",
2843
+ "tipGranted": "Gewährtes Guthaben",
2844
+ "tipQuotaLeft": "Verbleibendes Kontingent",
2845
+ "tipHitTurn": "Trefferquote dieses Turns",
2846
+ "tipHitHigh": "Höchste Trefferquote",
2847
+ "tipHitLow": "Niedrigste Trefferquote",
2848
+ "tipCountsTitle": "Sitzungsdaten",
2849
+ "tipCountsSkills": "Injizierte Skills",
2850
+ "tipCountsCompactAt": "Kontextkomprimierungen",
2851
+ "tipCountsToolCalls": "Tool-Aufrufe",
2852
+ "tipManual": "Manuell aufgerufen",
2853
+ "tipSub": "Unter-Skill",
2854
+ "tipCompactItem": "Komprimierung {index}",
2855
+ "tipCompactWhere": "Turn {turn} · Schritt {step}",
2856
+ "tipCompactTurnOnly": "Turn {turn}",
2857
+ "tipCompactAfter": "Nach Turn {turn}",
2858
+ "contextAria": "{percent} des Kontexts belegt",
2859
+ "contextSystem": "System-Prompt",
2860
+ "contextTools": "Tool-Definitionen",
2861
+ "contextMessages": "Nachrichten",
2862
+ "f_speed": "TPS {throughput} t/s",
2863
+ "f_sessionTime": "Zeit {duration}",
2864
+ "f_cost": "Gesamt {symbol}{cost}",
2865
+ "priceTierPeak": "Spitze",
2866
+ "priceTierOffPeak": "Nebenzeiten",
2867
+ "priceTierAllDay": "Ganztags",
2868
+ "f_lastCost": "Dieser Turn {symbol}{cost}",
2869
+ "f_balance": "Guthaben {symbol}{amount}",
2870
+ "f_balanceSubCent": "Guthaben <{symbol}0.01",
2871
+ "tipCreditsTitle": "Punktepakete",
2872
+ "tipCreditsMonthly": " (monatlich)",
2873
+ "tipCreditsRefresh": " · erneuert sich {date}",
2874
+ "tipCreditsExpire": " · verfällt {date}",
2875
+ "tipCreditsRefreshLatest": " · erneuert sich {date} (nächste)",
2876
+ "tipCreditsExpireLatest": " · verfällt {date} (nächste)",
2877
+ "tipCreditsLeft": "{left} / {total} übrig",
2878
+ "secSegments": "Statistikfelder",
2879
+ "secSegmentsHint": "Zum Anzeigen auswählen; per Ziehen sortieren.",
2880
+ "secPrices": "Eigene Modellpreise",
2881
+ "secPricesHint": "Preise pro Million Token.",
2882
+ "secPlatforms": "Drittanbieter-Plattformen",
2883
+ "secPlatformsBadge": "Experimentell",
2884
+ "secPlatformsHint": "Konfigurieren Sie pro Plattform Guthaben-Endpoint und Gebührenfaktor: Mit Endpoint wird das Guthaben abgefragt; leer = nur Faktor.",
2885
+ "platformNewPh": "Plattformname",
2886
+ "platformAdd": "Plattform hinzufügen",
2887
+ "platformEmpty": "Noch keine Drittanbieter-Plattformen.",
2888
+ "platformModels": "Passende Modelle",
2889
+ "platformModelSelectPh": "Modell auswählen",
2890
+ "platformFeePh": "z. B. 0.02",
2891
+ "platformAddModel": "Modell hinzufügen",
2892
+ "platformNameDuplicate": "Dieser Plattformname existiert bereits.",
2893
+ "platformSecretSaved": "Gespeichert – leer lassen, um ihn zu behalten",
2894
+ "segStatusHint": "Ermittelt automatisch das aktuelle Spitzen-/Nebenzeiten-Fenster.",
2895
+ "tipWeekTitle": "Aktivitätsübersicht",
2896
+ "hoverCalls": "API-Aufrufe",
2897
+ "hoverCost": "Kosten",
2898
+ "hoverYearAll": "ganzes Jahr",
2899
+ "segCountsHint": "Gesamte Turns und ausgeführte Schritte der aktuellen Sitzung.",
2900
+ "segTtftHint": "Durchschnittliche Zeit bis zum ersten Token.",
2901
+ "segCacheHitHint": "Durchschnittliche Cache-Trefferquote der aktuellen Sitzung.",
2902
+ "segTpsHint": "Durchschnittliche Ausgaberate in Token pro Sekunde.",
2903
+ "segSessionTimeHint": "Gesamte Laufzeit der aktuellen Sitzung.",
2904
+ "segCostHint": "Geschätzte Sitzungskosten inklusive Hauptmodell, Subagenten und Hilfsaufrufen.",
2905
+ "segLastCostHint": "Geschätzte Kosten des aktuellen oder letzten Turns inklusive Hauptmodell, Subagenten und Hilfsaufrufen.",
2906
+ "segBalanceHint": "Kontoguthaben, jede Minute aktualisiert.",
2907
+ "priceCurrent": "Aktuelle Sitzung:",
2908
+ "modelUnknown": "unbekannt",
2909
+ "unitCountTurns": " Turns",
2910
+ "unitCountSteps": " Schritte",
2911
+ "unitCountCalls": " Aufrufe",
2912
+ "unitSpeed": "t/s",
2913
+ "priceSuggestedHint": "Das Preisverzeichnis enthält geprüfte offizielle API-Tarife; Felder ohne bestätigten Preis werden bei den automatischen Kosten ausgeschlossen.",
2914
+ "priceFeeMultiplier": "Gebührenfaktor",
2915
+ "priceFeeMultiplierInvalid": "Der Gebührenfaktor muss eine Zahl zwischen 0 und 1000 sein (leer = 1).",
2916
+ "priceTokenHeader": "Header",
2917
+ "priceTokenHeaderHint": "z. B. New-Api-User",
2918
+ "priceToken": "Token",
2919
+ "priceTokenHint": "New API: Access-Token; Sub2API: Login-Token",
2920
+ "priceUserId": "Benutzer-ID",
2921
+ "priceUserIdHint": "Benutzer-ID eingeben",
2922
+ "priceEndpoint": "Guthaben-Endpoint",
2923
+ "priceEndpointHint": "Guthaben-Endpoint, z. B. https://xxx/api/user/self",
2924
+ "priceBalanceField": "Guthaben-Feld",
2925
+ "priceBalanceFieldHint": "z. B. ¥data.quota / 500000",
2926
+ "priceBalanceFieldInvalid": "Ungültiges Guthaben-Feld, z. B. ¥data.quota / 500000.",
2927
+ "priceEndpointInvalid": "Der Guthaben-Endpoint muss mit http:// oder https:// beginnen.",
2928
+ "priceRelaySyncFailed": "Synchronisierung der Drittanbieter-Konfiguration fehlgeschlagen ({reason}); die Guthabenabfrage funktioniert möglicherweise nicht.",
2929
+ "f_balanceDash": "Guthaben {symbol}-",
2930
+ "priceNewModel": "Eigenes Modell",
2931
+ "priceAdd": "Hinzufügen",
2932
+ "priceEmpty": "Preisverzeichnis ist leer – einen Modellnamen eingeben (z. B. deepseek-flash) und auf Hinzufügen klicken.",
2933
+ "priceRemove": "Entfernen",
2934
+ "priceManufacturerDeepseek": "DeepSeek",
2935
+ "priceManufacturerAnthropic": "Anthropic",
2936
+ "priceManufacturerZhipu": "Zhipu",
2937
+ "priceManufacturerAlibaba": "Alibaba",
2938
+ "priceManufacturerMoonshot": "Moonshot",
2939
+ "priceManufacturerGoogle": "Google",
2940
+ "priceManufacturerXai": "xAI",
2941
+ "priceManufacturerXiaomi": "Xiaomi",
2942
+ "priceManufacturerMuse": "Meta",
2943
+ "priceManufacturerOpenai": "OpenAI",
2944
+ "priceManufacturerCustom": "Eigene Modelle",
2945
+ "priceInput": "Eingabe (Cache-Fehltreffer)",
2946
+ "priceCacheRead": "Eingabe (Cache-Treffer)",
2947
+ "priceOutput": "Ausgabe",
2948
+ "priceTiered": "Spitzen-/Nebenzeiten-Preise",
2949
+ "priceEdit": "Bearbeiten",
2950
+ "priceSave": "Speichern",
2951
+ "reset": "Einstellungen zurücksetzen",
2952
+ "starRepo": "Auf GitHub unterstützen",
2953
+ "starTip": "Deine Unterstützung bedeutet mir viel – gib dem Projekt bitte einen Stern!"
2954
+ };
2955
+ const ru = {
2956
+ "nav": "Строка состояния",
2957
+ "updatePill": "Доступно обновление",
2958
+ "updateTo": "Обновить до {version}",
2959
+ "updateRunning": "Обновление…",
2960
+ "updateFailed": "Не удалось обновить",
2961
+ "updateDone": "Обновление установлено — перезапустите DSH, чтобы применить",
2962
+ "updateErrorTruncated": "(вывод слишком длинный; показаны последние {limit} символов — полный текст см. в журнале)",
2963
+ "updateErrorCopy": "Копировать",
2964
+ "updateErrorCopied": "Скопировано",
2965
+ "devModeBadge": "Режим разработки",
2966
+ "devModeHint": "Режим разработки: кнопка обновления только имитирует состояния — ничего не устанавливается",
2967
+ "sectionTitle": "Настройки строки состояния",
2968
+ "intro": "Заменяет строку статистики под полем ввода. Выберите отображаемые поля, перетаскивайте для изменения порядка или задайте цены моделей.",
2969
+ "segContext": "Использование контекста",
2970
+ "segContextHint": "Разбивка заполнения контекста и порог сжатия.",
2971
+ "segStatus": "Пиковый / непиковый период",
2972
+ "segCounts": "Ходы и шаги",
2973
+ "segTtft": "Время до первого токена",
2974
+ "segCacheHit": "Доля попаданий в кэш",
2975
+ "segTps": "Токенов в секунду",
2976
+ "segSessionTime": "Время работы",
2977
+ "segCost": "Стоимость сеанса",
2978
+ "segLastCost": "Стоимость этого хода",
2979
+ "segBalance": "Баланс",
2980
+ "tipEmptyTitle": "{label}",
2981
+ "tipEmptyBody": "Сейчас у этого поля нет данных. В режиме разработки открытие переключает на следующую тестовую сцену, а не оставляет вас здесь.",
2982
+ "f_peak": "Пик",
2983
+ "f_valley": "Непик",
2984
+ "f_counts": "{turns} ходов · {steps} шагов",
2985
+ "f_ttft": "TTFT {duration}",
2986
+ "f_cacheHit": "Общее попадание {percent}%",
2987
+ "f_tokensHit": "ввод (из кэша)",
2988
+ "f_tokensMiss": "ввод (без кэша)",
2989
+ "f_tokensOut": "вывод",
2990
+ "f_tokensTotal": "Всего использовано",
2991
+ "f_tokensTurn": "Использовано за ход",
2992
+ "tipModelTime": "Время модели",
2993
+ "tipWaitTime": "Время ожидания",
2994
+ "tipToolTime": "Вызовы инструментов",
2995
+ "tipTtftTurn": "Средний TTFT за ход",
2996
+ "tipTtftFast": "Самый быстрый TTFT",
2997
+ "tipTtftSlow": "Самый медленный TTFT",
2998
+ "tipTpsTurn": "Средний TPS за ход",
2999
+ "tipTpsFast": "Максимальный TPS",
3000
+ "tipTpsSlow": "Минимальный TPS",
3001
+ "tipTopUp": "Баланс пополнений",
3002
+ "tipGranted": "Начисленный баланс",
3003
+ "tipQuotaLeft": "Остаток квоты",
3004
+ "tipHitTurn": "Доля попаданий за ход",
3005
+ "tipHitHigh": "Наибольшая доля попаданий",
3006
+ "tipHitLow": "Наименьшая доля попаданий",
3007
+ "tipCountsTitle": "Данные сеанса",
3008
+ "tipCountsSkills": "Внедрено навыков",
3009
+ "tipCountsCompactAt": "Сжатия контекста",
3010
+ "tipCountsToolCalls": "Вызовы инструментов",
3011
+ "tipManual": "Вызвано вручную",
3012
+ "tipSub": "Поднавык",
3013
+ "tipCompactItem": "Сжатие {index}",
3014
+ "tipCompactWhere": "Ход {turn}·Шаг {step}",
3015
+ "tipCompactTurnOnly": "Ход {turn}",
3016
+ "tipCompactAfter": "После хода {turn}",
3017
+ "contextAria": "Использовано {percent} контекста",
3018
+ "contextSystem": "Системный промпт",
3019
+ "contextTools": "Определения инструментов",
3020
+ "contextMessages": "Сообщения",
3021
+ "f_speed": "TPS {throughput}t/s",
3022
+ "f_sessionTime": "Время {duration}",
3023
+ "f_cost": "Всего {symbol}{cost}",
3024
+ "priceTierPeak": "Пик",
3025
+ "priceTierOffPeak": "Непик",
3026
+ "priceTierAllDay": "Весь день",
3027
+ "f_lastCost": "За ход {symbol}{cost}",
3028
+ "f_balance": "Баланс {symbol}{amount}",
3029
+ "f_balanceSubCent": "Баланс <{symbol}0.01",
3030
+ "tipCreditsTitle": "Пакеты баллов",
3031
+ "tipCreditsMonthly": " (ежемесячно)",
3032
+ "tipCreditsRefresh": " · обновление {date}",
3033
+ "tipCreditsExpire": " · истекает {date}",
3034
+ "tipCreditsRefreshLatest": " · обновление {date} (ближайшее)",
3035
+ "tipCreditsExpireLatest": " · истекает {date} (ближайшее)",
3036
+ "tipCreditsLeft": "осталось {left} / {total}",
3037
+ "secSegments": "Поля статистики",
3038
+ "secSegmentsHint": "Выберите для показа; перетащите для порядка.",
3039
+ "secPrices": "Свои цены моделей",
3040
+ "secPricesHint": "Цены за миллион токенов.",
3041
+ "secPlatforms": "Сторонние платформы",
3042
+ "secPlatformsBadge": "Экспериментально",
3043
+ "secPlatformsHint": "Настройте для каждой платформы адрес баланса и множитель комиссии: укажите адрес для запроса баланса; пусто — только множитель.",
3044
+ "platformNewPh": "Название платформы",
3045
+ "platformAdd": "Добавить платформу",
3046
+ "platformEmpty": "Сторонних платформ пока нет.",
3047
+ "platformModels": "Подходящие модели",
3048
+ "platformModelSelectPh": "Выберите модель",
3049
+ "platformFeePh": "напр. 0.02",
3050
+ "platformAddModel": "Добавить модель",
3051
+ "platformNameDuplicate": "Такое название платформы уже есть.",
3052
+ "platformSecretSaved": "Сохранено — оставьте пустым, чтобы сохранить",
3053
+ "segStatusHint": "Автоматически определяет текущий пиковый / непиковый период.",
3054
+ "tipWeekTitle": "Обзор активности",
3055
+ "hoverCalls": "Вызовы API",
3056
+ "hoverCost": "Стоимость",
3057
+ "hoverYearAll": "весь год",
3058
+ "segCountsHint": "Всего ходов и выполненных шагов в текущем сеансе.",
3059
+ "segTtftHint": "Среднее время до первого токена.",
3060
+ "segCacheHitHint": "Средняя доля попаданий в кэш за текущий сеанс.",
3061
+ "segTpsHint": "Средняя скорость вывода в токенах в секунду.",
3062
+ "segSessionTimeHint": "Общее время работы текущего сеанса.",
3063
+ "segCostHint": "Оценочная стоимость сеанса, включая основную модель, субагентов и вспомогательные вызовы.",
3064
+ "segLastCostHint": "Оценочная стоимость текущего или последнего хода, включая основную модель, субагентов и вспомогательные вызовы.",
3065
+ "segBalanceHint": "Баланс аккаунта, обновляется каждую минуту.",
3066
+ "priceCurrent": "Текущий сеанс:",
3067
+ "modelUnknown": "неизвестно",
3068
+ "unitCountTurns": " ходов",
3069
+ "unitCountSteps": " шагов",
3070
+ "unitCountCalls": " вызовов",
3071
+ "unitSpeed": "t/s",
3072
+ "priceSuggestedHint": "В прайс-листе есть проверенные официальные тарифы API; поля без подтверждённой цены исключаются из автоматического расчёта стоимости.",
3073
+ "priceFeeMultiplier": "Множитель комиссии",
3074
+ "priceFeeMultiplierInvalid": "Множитель комиссии должен быть числом от 0 до 1000 (пусто = 1).",
3075
+ "priceTokenHeader": "Заголовок",
3076
+ "priceTokenHeaderHint": "напр. New-Api-User",
3077
+ "priceToken": "Token",
3078
+ "priceTokenHint": "New API: access token; Sub2API: login token",
3079
+ "priceUserId": "ID пользователя",
3080
+ "priceUserIdHint": "Введите ID пользователя",
3081
+ "priceEndpoint": "Адрес баланса",
3082
+ "priceEndpointHint": "Адрес баланса, напр. https://xxx/api/user/self",
3083
+ "priceBalanceField": "Поле баланса",
3084
+ "priceBalanceFieldHint": "напр. ¥data.quota / 500000",
3085
+ "priceBalanceFieldInvalid": "Неверное поле баланса, напр. ¥data.quota / 500000.",
3086
+ "priceEndpointInvalid": "Адрес баланса должен начинаться с http:// или https://.",
3087
+ "priceRelaySyncFailed": "Не удалось синхронизировать настройки сторонних платформ ({reason}); запрос баланса может не работать.",
3088
+ "f_balanceDash": "Баланс {symbol}-",
3089
+ "priceNewModel": "Своя модель",
3090
+ "priceAdd": "Добавить",
3091
+ "priceEmpty": "Прайс-лист пуст — введите название модели (напр. deepseek-flash) и нажмите «Добавить».",
3092
+ "priceRemove": "Удалить",
3093
+ "priceManufacturerDeepseek": "DeepSeek",
3094
+ "priceManufacturerAnthropic": "Anthropic",
3095
+ "priceManufacturerZhipu": "Zhipu",
3096
+ "priceManufacturerAlibaba": "Alibaba",
3097
+ "priceManufacturerMoonshot": "Moonshot",
3098
+ "priceManufacturerGoogle": "Google",
3099
+ "priceManufacturerXai": "xAI",
3100
+ "priceManufacturerXiaomi": "Xiaomi",
3101
+ "priceManufacturerMuse": "Meta",
3102
+ "priceManufacturerOpenai": "OpenAI",
3103
+ "priceManufacturerCustom": "Свои модели",
3104
+ "priceInput": "Ввод (без кэша)",
3105
+ "priceCacheRead": "Ввод (из кэша)",
3106
+ "priceOutput": "Вывод",
3107
+ "priceTiered": "Цены по пиковому / непиковому тарифу",
3108
+ "priceEdit": "Изменить",
3109
+ "priceSave": "Сохранить",
3110
+ "reset": "Сбросить настройки",
3111
+ "starRepo": "Поддержать на GitHub",
3112
+ "starTip": "Ваша поддержка очень важна — поставьте звезду!"
3113
+ };
3114
+ const pt = {
3115
+ "nav": "Barra de Estado",
3116
+ "updatePill": "Atualização disponível",
3117
+ "updateTo": "Atualizar para {version}",
3118
+ "updateRunning": "A atualizar",
3119
+ "updateFailed": "Falha na atualização",
3120
+ "updateDone": "Atualização concluída — reinicie o DSH para aplicar",
3121
+ "updateErrorTruncated": "(a saída é extensa; a mostrar os últimos {limit} caracteres — consulte o registo para o texto completo)",
3122
+ "updateErrorCopy": "Copiar",
3123
+ "updateErrorCopied": "Copiado",
3124
+ "devModeBadge": "Modo de desenvolvimento",
3125
+ "devModeHint": "Modo de desenvolvimento: o botão de atualização apenas simula estados — nada é instalado",
3126
+ "sectionTitle": "Definições da Barra de Estado",
3127
+ "intro": "Substitui a linha de estatísticas por baixo da caixa de mensagem. Selecione os campos a mostrar, arraste para reordenar ou defina os preços dos modelos.",
3128
+ "segContext": "Utilização do contexto",
3129
+ "segContextHint": "Distribuição da ocupação do contexto e limite de compactação.",
3130
+ "segStatus": "Verificação de ponta / fora de ponta",
3131
+ "segCounts": "Turnos e passos",
3132
+ "segTtft": "Tempo até ao primeiro token",
3133
+ "segCacheHit": "Taxa de acerto da cache",
3134
+ "segTps": "Tokens por segundo",
3135
+ "segSessionTime": "Tempo de execução",
3136
+ "segCost": "Custo da sessão",
3137
+ "segLastCost": "Custo deste turno",
3138
+ "segBalance": "Saldo",
3139
+ "tipEmptyTitle": "{label}",
3140
+ "tipEmptyBody": "Este campo não tem dados neste momento. No modo de desenvolvimento, abri-lo avança para a cena de exemplo seguinte em vez de o deixar aqui preso.",
3141
+ "f_peak": "Ponta",
3142
+ "f_valley": "Fora de ponta",
3143
+ "f_counts": "{turns} turnos · {steps} passos",
3144
+ "f_ttft": "TTFT {duration}",
3145
+ "f_cacheHit": "Acerto combinado {percent}%",
3146
+ "f_tokensHit": "entrada (acerto de cache)",
3147
+ "f_tokensMiss": "entrada (falha de cache)",
3148
+ "f_tokensOut": "saída",
3149
+ "f_tokensTotal": "Utilização total",
3150
+ "f_tokensTurn": "Utilização deste turno",
3151
+ "tipModelTime": "Tempo do modelo",
3152
+ "tipWaitTime": "Tempo de espera",
3153
+ "tipToolTime": "Chamadas de ferramentas",
3154
+ "tipTtftTurn": "TTFT médio deste turno",
3155
+ "tipTtftFast": "TTFT mais rápido",
3156
+ "tipTtftSlow": "TTFT mais lento",
3157
+ "tipTpsTurn": "TPS médio deste turno",
3158
+ "tipTpsFast": "TPS mais rápido",
3159
+ "tipTpsSlow": "TPS mais lento",
3160
+ "tipTopUp": "Saldo recarregado",
3161
+ "tipGranted": "Saldo oferecido",
3162
+ "tipQuotaLeft": "Quota restante",
3163
+ "tipHitTurn": "Taxa de acerto deste turno",
3164
+ "tipHitHigh": "Taxa de acerto mais alta",
3165
+ "tipHitLow": "Taxa de acerto mais baixa",
3166
+ "tipCountsTitle": "Dados da sessão",
3167
+ "tipCountsSkills": "Habilidades injetadas",
3168
+ "tipCountsCompactAt": "Compactações de contexto",
3169
+ "tipCountsToolCalls": "Chamadas de ferramentas",
3170
+ "tipManual": "Invocada manualmente",
3171
+ "tipSub": "Sub-habilidade",
3172
+ "tipCompactItem": "Compactação {index}",
3173
+ "tipCompactWhere": "Turno {turn}·Passo {step}",
3174
+ "tipCompactTurnOnly": "Turno {turn}",
3175
+ "tipCompactAfter": "Após o turno {turn}",
3176
+ "contextAria": "{percent} do contexto utilizado",
3177
+ "contextSystem": "Prompt de sistema",
3178
+ "contextTools": "Definições de ferramentas",
3179
+ "contextMessages": "Mensagens",
3180
+ "f_speed": "TPS {throughput}t/s",
3181
+ "f_sessionTime": "Tempo {duration}",
3182
+ "f_cost": "Total {symbol}{cost}",
3183
+ "priceTierPeak": "Ponta",
3184
+ "priceTierOffPeak": "Fora de ponta",
3185
+ "priceTierAllDay": "Todo o dia",
3186
+ "f_lastCost": "Este turno {symbol}{cost}",
3187
+ "f_balance": "Saldo {symbol}{amount}",
3188
+ "f_balanceSubCent": "Saldo <{symbol}0.01",
3189
+ "tipCreditsTitle": "Pacotes de pontos",
3190
+ "tipCreditsMonthly": " (mensal)",
3191
+ "tipCreditsRefresh": " · renova a {date}",
3192
+ "tipCreditsExpire": " · expira a {date}",
3193
+ "tipCreditsRefreshLatest": " · renova a {date} (mais próxima)",
3194
+ "tipCreditsExpireLatest": " · expira a {date} (mais próxima)",
3195
+ "tipCreditsLeft": "{left} / {total} restantes",
3196
+ "secSegments": "Campos de estatísticas",
3197
+ "secSegmentsHint": "Selecione para mostrar; arraste para reordenar.",
3198
+ "secPrices": "Preços de modelos personalizados",
3199
+ "secPricesHint": "Preços por milhão de tokens.",
3200
+ "secPlatforms": "Plataformas de terceiros",
3201
+ "secPlatformsBadge": "Experimental",
3202
+ "secPlatformsHint": "Configure por plataforma o endpoint de saldo e o multiplicador de taxa: informe o endpoint para consultar o saldo; vazio, apenas o multiplicador.",
3203
+ "platformNewPh": "Nome da plataforma",
3204
+ "platformAdd": "Adicionar plataforma",
3205
+ "platformEmpty": "Ainda não há plataformas de terceiros.",
3206
+ "platformModels": "Modelos aplicáveis",
3207
+ "platformModelSelectPh": "Selecionar um modelo",
3208
+ "platformFeePh": "ex.: 0.02",
3209
+ "platformAddModel": "Adicionar modelo",
3210
+ "platformNameDuplicate": "Este nome de plataforma já existe.",
3211
+ "platformSecretSaved": "Guardado — deixe em branco para manter",
3212
+ "segStatusHint": "Determina automaticamente a janela de ponta / fora de ponta atual.",
3213
+ "tipWeekTitle": "Visão geral da atividade",
3214
+ "hoverCalls": "Chamadas à API",
3215
+ "hoverCost": "Custo",
3216
+ "hoverYearAll": "ano completo",
3217
+ "segCountsHint": "Total de turnos e passos executados da sessão atual.",
3218
+ "segTtftHint": "Tempo médio até ao primeiro token.",
3219
+ "segCacheHitHint": "Taxa média de acerto da cache da sessão atual.",
3220
+ "segTpsHint": "Taxa média de saída, em tokens por segundo.",
3221
+ "segSessionTimeHint": "Tempo total de execução da sessão atual.",
3222
+ "segCostHint": "Custo estimado da sessão, incluindo o modelo principal, subagentes e chamadas auxiliares.",
3223
+ "segLastCostHint": "Custo estimado do turno atual ou mais recente, incluindo o modelo principal, subagentes e chamadas auxiliares.",
3224
+ "segBalanceHint": "Saldo da conta, atualizado a cada minuto.",
3225
+ "priceCurrent": "Sessão atual:",
3226
+ "modelUnknown": "desconhecido",
3227
+ "unitCountTurns": " turnos",
3228
+ "unitCountSteps": " passos",
3229
+ "unitCountCalls": " chamadas",
3230
+ "unitSpeed": "t/s",
3231
+ "priceSuggestedHint": "A tabela de preços inclui tarifas oficiais da API verificadas; os campos sem preço confirmado ficam excluídos do custo automático.",
3232
+ "priceFeeMultiplier": "Multiplicador de taxa",
3233
+ "priceFeeMultiplierInvalid": "O multiplicador de taxa deve ser um número entre 0 e 1000 (em branco = 1).",
3234
+ "priceTokenHeader": "Cabeçalho",
3235
+ "priceTokenHeaderHint": "ex.: New-Api-User",
3236
+ "priceToken": "Token",
3237
+ "priceTokenHint": "New API: token de acesso; Sub2API: token de início de sessão",
3238
+ "priceUserId": "ID do utilizador",
3239
+ "priceUserIdHint": "Introduza o ID do utilizador",
3240
+ "priceEndpoint": "Endpoint de saldo",
3241
+ "priceEndpointHint": "Endpoint de saldo, ex.: https://xxx/api/user/self",
3242
+ "priceBalanceField": "Campo de saldo",
3243
+ "priceBalanceFieldHint": "ex.: ¥data.quota / 500000",
3244
+ "priceBalanceFieldInvalid": "Campo de saldo inválido, ex.: ¥data.quota / 500000.",
3245
+ "priceEndpointInvalid": "O endpoint de saldo deve começar por http:// ou https://.",
3246
+ "priceRelaySyncFailed": "Falha ao sincronizar a configuração da plataforma de terceiros ({reason}); a consulta de saldo pode não funcionar.",
3247
+ "f_balanceDash": "Saldo {symbol}-",
3248
+ "priceNewModel": "Modelo personalizado",
3249
+ "priceAdd": "Adicionar",
3250
+ "priceEmpty": "A tabela de preços está vazia — escreva o nome de um modelo (ex.: deepseek-flash) e clique em Adicionar.",
3251
+ "priceRemove": "Remover",
3252
+ "priceManufacturerDeepseek": "DeepSeek",
3253
+ "priceManufacturerAnthropic": "Anthropic",
3254
+ "priceManufacturerZhipu": "Zhipu",
3255
+ "priceManufacturerAlibaba": "Alibaba",
3256
+ "priceManufacturerMoonshot": "Moonshot",
3257
+ "priceManufacturerGoogle": "Google",
3258
+ "priceManufacturerXai": "xAI",
3259
+ "priceManufacturerXiaomi": "Xiaomi",
3260
+ "priceManufacturerMuse": "Meta",
3261
+ "priceManufacturerOpenai": "OpenAI",
3262
+ "priceManufacturerCustom": "Modelos personalizados",
3263
+ "priceInput": "Entrada (falha de cache)",
3264
+ "priceCacheRead": "Entrada (acerto de cache)",
3265
+ "priceOutput": "Saída",
3266
+ "priceTiered": "Preços de ponta / fora de ponta",
3267
+ "priceEdit": "Editar",
3268
+ "priceSave": "Guardar",
3269
+ "reset": "Repor definições",
3270
+ "starRepo": "Apoiar no GitHub",
3271
+ "starTip": "O seu apoio significa muito para mim — dê uma estrela!"
1687
3272
  };
1688
3273
 
1689
3274
  /* --------------------------------------------------------------- 段定义
@@ -1700,6 +3285,8 @@ window.__ModuleLoader__.load({
1700
3285
  { id: "cost", label: "segCost", hint: "segCostHint", def: true, short: { zh: "总计", en: "Total" } },
1701
3286
  { id: "balance", label: "segBalance", hint: "segBalanceHint", def: true, short: { zh: "余额", en: "Balance" } }
1702
3287
  ];
3288
+ const SEGMENT_SHORT_I18N = { ja: {"status":"期間","counts":"ターン数","cacheHit":"ヒット率","tps":"TPS","ttft":"TTFT","sessionTime":"時間","lastCost":"今回","cost":"合計","balance":"残高"}, es: {"status":"Periodo","counts":"Turnos/pasos","cacheHit":"Aciertos comb.","tps":"TPS","ttft":"TTFT","sessionTime":"Tiempo","lastCost":"Este turno","cost":"Total","balance":"Saldo"}, fr: {"status":"Période","counts":"Tours/étapes","cacheHit":"Cache combiné","tps":"TPS","ttft":"TTFT","sessionTime":"Durée","lastCost":"Ce tour","cost":"Total","balance":"Solde"}, de: {"status":"Zeitraum","counts":"Turns/Schritte","cacheHit":"Treffer gesamt","tps":"TPS","ttft":"TTFT","sessionTime":"Zeit","lastCost":"Dieser Turn","cost":"Gesamt","balance":"Guthaben"}, ru: {"status":"Период","counts":"Ходы/шаги","cacheHit":"Общий кэш","tps":"TPS","ttft":"TTFT","sessionTime":"Время","lastCost":"За ход","cost":"Всего","balance":"Баланс"}, pt: {"status":"Período","counts":"Turnos/passos","cacheHit":"Acerto combinado","tps":"TPS","ttft":"TTFT","sessionTime":"Tempo","lastCost":"Este turno","cost":"Total","balance":"Saldo"} };
3289
+ SEGMENTS.forEach((s) => { Object.keys(SEGMENT_SHORT_I18N).forEach((code) => { const m = SEGMENT_SHORT_I18N[code]; if (m && typeof m[s.id] === "string") s.short[code] = m[s.id]; }); });
1703
3290
  const KNOWN = {};
1704
3291
  SEGMENTS.forEach((s) => { KNOWN[s.id] = true; });
1705
3292
  /** 出厂默认:全部段,顺序 = 上方 SEGMENTS 声明顺序。 */
@@ -1718,14 +3305,20 @@ window.__ModuleLoader__.load({
1718
3305
  function loadConfig() {
1719
3306
  const fallback = {
1720
3307
  version: CONFIG_VERSION,
1721
- priceConfigured: false,
3308
+ priceConfigured: false,
1722
3309
  contextMeter: true,
1723
3310
  segments: DEFAULT_SEGMENTS.slice(),
1724
3311
  hidden: [],
1725
3312
  currency: "CNY",
1726
- models: normalizeModels(DEFAULT_PRICES, "CNY"),
1727
- modelOrder: Object.keys(DEFAULT_PRICES),
1728
- holidayDays: []
3313
+ /* 全新安装(没有 localStorage)走内嵌参考价;官方目录的其余模型由「恢复默认」
3314
+ 一次性加回(见 resetPriceBook)。已有配置的迁移在下面按 v4 播种。 */
3315
+ models: normalizeModels(officialDefaultModels("CNY"), "CNY"),
3316
+ modelOrder: Object.keys(officialDefaultModels("CNY")),
3317
+ priceVersion: PRICE_VERSION,
3318
+ holidayDays: [],
3319
+ /* 第三方平台档案(非密):平台名 → { endpoint, userIdHeader, balancePath, currency, balanceDivisor, models } */
3320
+ relayPlatforms: {},
3321
+ catalogOrder: DEFAULT_CATALOG_ORDER.slice()
1729
3322
  };
1730
3323
  try {
1731
3324
  const raw = readStored();
@@ -1752,22 +3345,80 @@ window.__ModuleLoader__.load({
1752
3345
  if (stored.indexOf(id) === -1) stored.push(id);
1753
3346
  });
1754
3347
  const hidden = hiddenStored.filter((id) => stored.indexOf(id) !== -1);
3348
+ /* 价格目录厂商顺序:旧配置没有就按默认补齐;未知项丢弃、重复项去掉。 */
3349
+ const catalogOrder = normalizeCatalogOrder(parsed.catalogOrder);
1755
3350
  /* 计价单位:只认 CNY / USD,其它值一律当人民币。
1756
3351
  迁移后它只是"**新增条目的默认币种**"—— 已有条目各自带币种
1757
3352
  (`models[name].currency`),任何选择器都不许再改写它们。 */
1758
- const currency = parsed.currency === "USD" ? "USD" : "CNY";
3353
+ const currency = "CNY";
1759
3354
  const reference = referencePrices(currency);
1760
3355
  /* 价格库落后于参考价版本时并入官方价;用户自己改过的条目不覆盖 */
1761
3356
  /* 价格库为空或全 0 时直接用内嵌官方价(自愈,无需手动填) */
1762
- if (pricesMissing(normalizeModels(parsed.models, currency))) parsed.models = Object.assign({}, reference);
3357
+ if (pricesMissing(normalizeModels(parsed.models, currency))) parsed.models = Object.assign({}, officialDefaultModels(currency));
1763
3358
  const priceVersion = typeof parsed.priceVersion === "number" ? parsed.priceVersion : 0;
3359
+ /* v4 迁移:官方模型目录默认**全部加入价格表**(按官网价播种)。已有条目一律不动
3360
+ (用户价 / feeMultiplier 都保留);DEFAULT_PRICES 里的键沿用内嵌 CNY 参考价,
3361
+ 与「恢复默认」和旧版默认价保持一致。 */
3362
+ /* 只对**带 priceVersion 的旧配置**播种:3.0.x 写出的配置一定带版本号;
3363
+ 没有版本号的手写/极老配置仍走「参考价合并」老路径,避免把「没配置过」误当「官方模型已加入」。 */
3364
+ /* 只对**带 priceVersion 的旧配置**播种:3.0.x 写出的配置一定带版本号;
3365
+ 没有版本号的手写/极老配置仍走「参考价合并」老路径,避免把「没配置过」误当「官方模型已加入」。
3366
+ v4 之后不再重复播种(用户删掉的官方模型要靠「恢复默认」找回,不能被升级悄悄加回)。 */
3367
+ const seeded = typeof parsed.priceVersion === "number" && priceVersion < PRICE_SEED_VERSION
3368
+ ? officialSeededModels()
3369
+ : {};
1764
3370
  /* 价格库落后于参考价版本时并入官方价:**官方价打底、用户条目优先** ——
1765
3371
  官方新增的模型补进来,但用户已经存在的条目(改过价的、明确填 0 的)一律不动。
1766
3372
  原来把 reference 写在后面,结果是官方价盖掉用户改过的同名条目,
1767
3373
  与上面那句"用户自己改过的条目不覆盖"正好相反(实测缺陷,用户确认要修)。 */
3374
+ /* 参考价合并沿用老口径:配置版本落后于**当前** PRICE_VERSION 就并入官方价
3375
+ (官方价打底、用户条目优先);播种只看 PRICE_SEED_VERSION,避免重复播种。 */
3376
+ /* v6/v8 迁移:官方目录**新增**的模型自动补播(用户拍板:老用户不用点「恢复默认」也能看到;v8 补 Claude Fable 5.2)。
3377
+ 只补当前价格库**缺失**的官方模型,已有条目一律不动(用户价 / feeMultiplier / relay 都保留);
3378
+ 候选只来自 MODEL_PRESENTATION,所以 v5 清掉的已下架模型不会被加回来。
3379
+ 与 v4 播种同一判定:只认**带 priceVersion 的旧配置**,手写 / 极老配置不做补播。
3380
+ 今后官方目录再加模型:把 PRICE_VERSION 与 PRICE_BACKFILL_VERSION 一起提到下一个版本号,这条会自动补上。 */
3381
+ const backfill = typeof parsed.priceVersion === "number" && priceVersion < PRICE_BACKFILL_VERSION
3382
+ ? officialBackfillModels(priceVersion)
3383
+ : {};
1768
3384
  const models = priceVersion < PRICE_VERSION
1769
- ? normalizeModels(Object.assign({}, reference, parsed.models), currency)
3385
+ ? normalizeModels(Object.assign({}, backfill, seeded, reference, parsed.models), currency)
1770
3386
  : normalizeModels(parsed.models, currency);
3387
+ /* v5 迁移:删掉旧版目录点选加入、现已下架的官方模型(只按确切名字;用户自建条目不动)。
3388
+ 自定义模型组随之为空时本来就不渲染(customModelRows.length > 0 才输出)。 */
3389
+ if (priceVersion < PRICE_RETIRED_PRUNE_VERSION) {
3390
+ RETIRED_OFFICIAL_MODELS.forEach((name) => {
3391
+ if (Object.prototype.hasOwnProperty.call(models, name)) delete models[name];
3392
+ });
3393
+ }
3394
+ /* v7 迁移:给缺 base 的旧条目补「当前值 + 当前币种」的基准价(数值一字不动)——
3395
+ 切币种来回切不漂的锚点,见 normalizeBase / setModelCurrency。 */
3396
+ if (priceVersion < PRICE_BASE_VERSION) {
3397
+ Object.keys(models).forEach((name) => {
3398
+ if (models[name].base !== undefined) return;
3399
+ models[name].base = { currency: models[name].currency, peak: models[name].peak, offPeak: models[name].offPeak };
3400
+ });
3401
+ }
3402
+ /* v8 迁移:模型气泡里的旧「第三方平台」配置(条目上的 `relay`)→ 平台档案。
3403
+ 平台名默认 = 模型名,`models = [{ model, feeMultiplier }]`,条目上不再保留 relay;
3404
+ 计费倍率仍在条目上(旧配置本来就存那里),所以归档后余额 / 计价行为都不变。 */
3405
+ const relayPlatforms = normalizePlatforms(parsed.relayPlatforms);
3406
+ const rawModels = parsed.models !== null && parsed.models !== undefined && typeof parsed.models === "object"
3407
+ ? parsed.models
3408
+ : {};
3409
+ Object.keys(rawModels).forEach((name) => {
3410
+ const legacyRaw = rawModels[name] === null || rawModels[name] === undefined ? undefined : rawModels[name].relay;
3411
+ const legacy = normalizeRelayConfig(legacyRaw);
3412
+ if (legacy === null || models[name] === undefined || relayPlatforms[name] !== undefined) return;
3413
+ relayPlatforms[name] = normalizePlatform({
3414
+ endpoint: legacy.endpoint,
3415
+ userIdHeader: legacy.userIdHeader,
3416
+ balancePath: legacy.balancePath,
3417
+ currency: legacy.currency,
3418
+ balanceDivisor: legacy.balanceDivisor,
3419
+ models: [{ model: name, feeMultiplier: models[name].feeMultiplier }]
3420
+ });
3421
+ });
1771
3422
  /* 旧版取消勾选「峰谷计价」时会把空闲价写成高峰价的副本,再勾回来也回不去。
1772
3423
  这里按参考价补回:只修"勾着峰谷计价、两档却完全相同"的官方模型。 */
1773
3424
  Object.keys(reference).forEach((name) => {
@@ -1794,8 +3445,10 @@ window.__ModuleLoader__.load({
1794
3445
  currency: currency,
1795
3446
  priceVersion: PRICE_VERSION,
1796
3447
  priceConfigured: priceConfigured,
1797
- models: Object.keys(models).length > 0 ? models : normalizeModels(reference, currency),
1798
- modelOrder: modelOrder.length > 0 ? modelOrder : Object.keys(reference),
3448
+ models: Object.keys(models).length > 0 ? models : normalizeModels(officialDefaultModels(currency), currency),
3449
+ modelOrder: modelOrder.length > 0 ? modelOrder : Object.keys(officialDefaultModels(currency)),
3450
+ relayPlatforms: relayPlatforms,
3451
+ catalogOrder: catalogOrder,
1799
3452
  /* 抓来的放假日历:字符串数组,按年分组在 refreshHolidays() 里做 */
1800
3453
  holidayDays: Array.isArray(parsed.holidayDays)
1801
3454
  ? parsed.holidayDays.filter((day) => typeof day === "string" && day.length === 10)
@@ -1823,8 +3476,65 @@ window.__ModuleLoader__.load({
1823
3476
  function useConfig() {
1824
3477
  return react.useSyncExternalStore(subscribe, snapshot, snapshot);
1825
3478
  }
1826
- /** 勾选只切换显示:段序不动,取消勾选的段留在原位。 */
1827
- function toggleSegment(id, on) {
3479
+ /* --------------------------------------- 中转站余额查询状态(宿主回传快照) */
3480
+ /* GET 回传整条 channel(含 token / userId 等);本快照只存内存 / 组件 state 用于编辑区回显,
3481
+ 绝不写进 localStorage / config。 */
3482
+ let relayState = { loaded: false, models: {} };
3483
+ /* 模型下拉的锚点按钮:滚动 / 缩放时按它实时重算浮层位置(关闭时置 null) */
3484
+ let platformMenuAnchor = null;
3485
+ let relayLoading = null;
3486
+ const relayListeners = new Set();
3487
+ function relaySnapshot() { return relayState; }
3488
+ function subscribeRelayState(fn) {
3489
+ relayListeners.add(fn);
3490
+ return () => { relayListeners.delete(fn); };
3491
+ }
3492
+ function publishRelayState(channels) {
3493
+ const models = {};
3494
+ (Array.isArray(channels) ? channels : []).forEach((one) => {
3495
+ if (one === null || one === undefined || typeof one !== "object") return;
3496
+ if (typeof one.channelKey !== "string" || one.channelKey.length === 0) return;
3497
+ /* 保留整条 channel 数据(endpoint/tokenHeader/userIdHeader/balancePath/currency/
3498
+ balanceDivisor/token/userId/tokenConfigured/userIdConfigured),供编辑区回显已保存值。 */
3499
+ models[one.channelKey] = Object.assign({}, one);
3500
+ });
3501
+ relayState = { loaded: true, models: models };
3502
+ relayListeners.forEach((fn) => { try { fn(); } catch (error) { /* 单个订阅者失败不影响其余 */ } });
3503
+ }
3504
+ /** 首次需要时 GET 一次(模块级缓存)。 */
3505
+ function ensureRelayState() {
3506
+ if (relayState.loaded === true) return Promise.resolve(relayState);
3507
+ if (relayLoading !== null) return relayLoading;
3508
+ relayLoading = window.fetch(RELAY_URL, { cache: "no-store" })
3509
+ .then((response) => response.json())
3510
+ .then((data) => {
3511
+ if (data !== null && data !== undefined && data.ok === true) publishRelayState(data.channels);
3512
+ return relayState;
3513
+ })
3514
+ .catch(() => relayState)
3515
+ .then((result) => {
3516
+ relayLoading = null;
3517
+ return result;
3518
+ });
3519
+ return relayLoading;
3520
+ }
3521
+ /** 保存 / 移除某个模型的中转站配置;响应里的布尔状态刷新本地缓存。 */
3522
+ function postRelayState(payload) {
3523
+ return window.fetch(RELAY_URL, {
3524
+ method: "POST",
3525
+ headers: { "content-type": "application/json" },
3526
+ body: JSON.stringify(payload)
3527
+ }).then((response) => response.json()).then((data) => {
3528
+ if (data !== null && data !== undefined && data.ok === true) publishRelayState(data.channels);
3529
+ return data;
3530
+ });
3531
+ }
3532
+ function useRelayState() {
3533
+ return react.useSyncExternalStore(subscribeRelayState, relaySnapshot, relaySnapshot);
3534
+ }
3535
+
3536
+ /** 勾选只切换显示:段序不动,取消勾选的段留在原位。 */
3537
+ function toggleSegment(id, on) {
1828
3538
  const hidden = (Array.isArray(config.hidden) ? config.hidden : []).filter((x) => x !== id);
1829
3539
  if (on !== true) hidden.push(id);
1830
3540
  setConfig({ hidden: hidden });
@@ -1868,7 +3578,7 @@ window.__ModuleLoader__.load({
1868
3578
  * 调用方必须按新数字重建草稿;否则数值一个字没动,调用方只该换草稿的币种标记,
1869
3579
  * **保住用户还没保存的输入**。
1870
3580
  */
1871
- function setModelCurrency(name, code, draftNow) {
3581
+ function setModelCurrency(name, code, draftNow) {
1872
3582
  const entry = config.models === undefined || config.models === null ? null : config.models[name];
1873
3583
  if (entry === null || entry === undefined) return null;
1874
3584
  const from = entry.currency === undefined || entry.currency === null ? normalizeCurrency(config.currency) : normalizeCurrency(entry.currency);
@@ -1883,16 +3593,51 @@ window.__ModuleLoader__.load({
1883
3593
  : { peak: normalizeTier(draftNow.peak), offPeak: normalizeTier(draftNow.offPeak) };
1884
3594
  const isPristineOfficial = official !== null
1885
3595
  && sameTier(shown.peak, official[from].peak) && sameTier(shown.offPeak, official[from].offPeak);
3596
+ /* 基准价(上次保存 / 播种时的值 + 币种)是切币种的**锚点**:切回基准币种直接用原值
3597
+ (不换算、不取整),切到别的币种从它按今日汇率换算 —— 否则「CNY→USD→CNY」来回切两次,
3598
+ 两位小数的舍入会把官方价越切越小(用户实测)。 */
3599
+ const base = baseOf(entry, from);
3600
+ const dirty = draftNow !== null && draftNow !== undefined
3601
+ && (sameTier(shown.peak, current.peak) !== true || sameTier(shown.offPeak, current.offPeak) !== true);
1886
3602
  const next = {
1887
3603
  tiered: isPristineOfficial === true ? true : entry.tiered !== false,
1888
3604
  currency: to,
1889
- peak: isPristineOfficial === true ? Object.assign({}, official[to].peak) : current.peak,
1890
- offPeak: isPristineOfficial === true ? Object.assign({}, official[to].offPeak) : current.offPeak
3605
+ peak: current.peak,
3606
+ offPeak: current.offPeak
1891
3607
  };
3608
+ if (isPristineOfficial === true) {
3609
+ /* deepseek 官方双表:直接换目标币种那一套官方价(现有语义不变) */
3610
+ next.tiered = true;
3611
+ next.peak = Object.assign({}, official[to].peak);
3612
+ next.offPeak = Object.assign({}, official[to].offPeak);
3613
+ } else if (official !== null) {
3614
+ /* 改过的双表条目:只换币种标记,数值一字不动(现有语义不变) */
3615
+ } else if (dirty === true) {
3616
+ /* 用户改了价还没保存:保住输入,把草稿数值按今日汇率换算过去 */
3617
+ const converted = tiersFromBase({ currency: from, peak: shown.peak, offPeak: shown.offPeak }, to, liveRate());
3618
+ next.peak = converted.peak;
3619
+ next.offPeak = converted.offPeak;
3620
+ } else if (to === base.currency) {
3621
+ /* 切回基准币种:**原值还原**,不换算、不取整(来回切不漂) */
3622
+ next.peak = Object.assign({}, base.peak);
3623
+ next.offPeak = Object.assign({}, base.offPeak);
3624
+ } else {
3625
+ const converted = tiersFromBase(base, to, liveRate());
3626
+ next.peak = converted.peak;
3627
+ next.offPeak = converted.offPeak;
3628
+ }
3629
+ /* 基准价原样保留:没保存过就还是上次的锚点,下次切回原币种照样精确还原 */
3630
+ next.base = base;
3631
+ /* 费用倍率与币种无关,切币种时原样保留(余额查询配置在平台档案里,不随条目走) */
3632
+ const feeConfigured = entry !== null && entry !== undefined && entry.feeConfigured === true;
3633
+ const feeMultiplier = normalizeFeeMultiplier(entry.feeMultiplier);
3634
+ if (feeConfigured === true) { next.feeConfigured = true; next.feeMultiplier = feeMultiplier; }
3635
+ else if (feeMultiplier !== 1) next.feeMultiplier = feeMultiplier;
1892
3636
  const models = Object.assign({}, config.models);
1893
3637
  models[name] = next;
1894
3638
  setConfig({ models: models });
1895
- return { entry: next, replaced: isPristineOfficial === true };
3639
+ /* replaced = 官方双表整条换(调用方重建草稿);converted = 框里的数字变了(调用方按新数字重建草稿) */
3640
+ return { entry: next, replaced: isPristineOfficial === true, converted: isPristineOfficial !== true && official === null };
1896
3641
  }
1897
3642
 
1898
3643
  /**
@@ -1925,12 +3670,26 @@ window.__ModuleLoader__.load({
1925
3670
  tiered: true,
1926
3671
  currency: "CNY",
1927
3672
  peak: normalizeTier(official.peak),
1928
- offPeak: normalizeTier(official.offPeak)
3673
+ offPeak: normalizeTier(official.offPeak),
3674
+ /* 官方 CNY 值本身就是这一条的基准价 */
3675
+ base: {
3676
+ currency: "CNY",
3677
+ peak: normalizeTier(official.peak),
3678
+ offPeak: normalizeTier(official.offPeak)
3679
+ }
1929
3680
  };
1930
3681
  });
1931
- /* ② 自建:原样搬过来(顺序取 modelOrder 的相对顺序,不在其中的补在后面) */
1932
- const source = config.models === undefined || config.models === null ? {} : config.models;
1933
3682
  const modelOrder = Object.keys(DEFAULT_PRICES).slice();
3683
+ /* ② 官方目录(MODEL_PRESENTATION):缺失的官方模型按官网价全部加回来
3684
+ (用户删掉的模型靠这一步找回;顺序按目录顺序,已存在的条目不覆盖) */
3685
+ const seeded = officialSeededModels();
3686
+ Object.keys(seeded).forEach((name) => {
3687
+ if (models[name] !== undefined) return;
3688
+ models[name] = seeded[name];
3689
+ modelOrder.push(name);
3690
+ });
3691
+ /* ③ 自建:原样搬过来(顺序取 modelOrder 的相对顺序,不在其中的补在后面) */
3692
+ const source = config.models === undefined || config.models === null ? {} : config.models;
1934
3693
  const walk = (Array.isArray(config.modelOrder) ? config.modelOrder : []).concat(Object.keys(source));
1935
3694
  walk.forEach((name) => {
1936
3695
  if (models[name] !== undefined || modelOrder.indexOf(name) !== -1) return;
@@ -1944,6 +3703,18 @@ window.__ModuleLoader__.load({
1944
3703
  peak: normalizeTier(entry.peak),
1945
3704
  offPeak: normalizeTier(entry.offPeak)
1946
3705
  };
3706
+ /* 自建条目:费用倍率也原样保留(恢复默认不该清掉它) */
3707
+ const feeConfigured = entry.feeConfigured === true;
3708
+ const feeMultiplier = normalizeFeeMultiplier(entry.feeMultiplier);
3709
+ if (feeConfigured === true) { models[name].feeConfigured = true; models[name].feeMultiplier = feeMultiplier; }
3710
+ else if (feeMultiplier !== 1) models[name].feeMultiplier = feeMultiplier;
3711
+ /* 自建条目也带基准价:旧配置没 base 就按「当前值 + 当前币种」补,别丢 */
3712
+ const customBase = normalizeBase(entry.base, models[name].currency);
3713
+ models[name].base = customBase !== null ? customBase : {
3714
+ currency: models[name].currency,
3715
+ peak: models[name].peak,
3716
+ offPeak: models[name].offPeak
3717
+ };
1947
3718
  modelOrder.push(name);
1948
3719
  });
1949
3720
  return { models: models, modelOrder: modelOrder };
@@ -2619,28 +4390,29 @@ window.__ModuleLoader__.load({
2619
4390
  }
2620
4391
 
2621
4392
  /** 悬停文字与「工具调用」标题之间至少留 1ch(11px 字号下约 7px)。 */
2622
- const HOVER_PLAIN_TITLE_GAP = 7;
4393
+ const HOVER_PLAIN_INSET = 8;
4394
+ /* 文字提示与「工具调用」标题之间的最小水平间距(约 1ch):不压标题 */
4395
+ const HOVER_PLAIN_TITLE_GAP = 12;
2623
4396
 
2624
4397
  /**
2625
- * 工具彩条悬停文字的**水平夹取范围**(用户拍板):
2626
- * 左 = 「工具调用」标题四个字的右边界 **再往右 1ch**(至少离标题 1ch,不能压到标题上);
2627
- * 右 = **色条本身**(`.dsb-bar`)的右边界,不能超出色条;再与视口右缘取小。
2628
- * 色条拿不到时退回气泡右边界;两者都没有就只用视口。
2629
- * 纯函数,便于单测;返回 { min, max },max 是文字右边界能到的最远位置。
4398
+ * 工具彩条悬停文字的**可用范围**:提示必须落在气泡内部(用户实测:跑到气泡外面了)。
4399
+ * 以气泡矩形为界,左右各留 8px 边距;返回 { min, max }(max 是文字右边界能到的最远处)。
4400
+ * 拿不到气泡几何(或气泡比两边距还窄)返回 null,交给夹取/视口兜底。纯函数,便于单测。
2630
4401
  */
2631
- function plainBoundsOf(headBox, barBox, viewportWidth) {
4402
+ function plainBoundsOf(headBox, panelBox, viewportWidth) {
4403
+ if (panelBox === null || panelBox === undefined) return null;
4404
+ if (typeof panelBox.left !== "number" || typeof panelBox.right !== "number") return null;
2632
4405
  const viewport = typeof viewportWidth === "number" && viewportWidth > 0 ? viewportWidth : 0;
2633
- const barRight = barBox !== null && barBox !== undefined && typeof barBox.right === "number"
2634
- ? barBox.right
2635
- : null;
2636
4406
  const titleRight = headBox !== null && headBox !== undefined && typeof headBox.right === "number"
2637
4407
  ? headBox.right
2638
4408
  : null;
2639
- let min = 8;
2640
- if (titleRight !== null) min = Math.max(8, titleRight + HOVER_PLAIN_TITLE_GAP);
2641
- let max = barRight !== null ? barRight : (viewport > 0 ? viewport - 8 : null);
2642
- if (max === null) return null;
2643
- if (viewport > 0) max = Math.min(max, viewport - 8);
4409
+ /* 左边界:标题文字右侧 + 间距(拿不到标题就退回气泡内边距),保证不压住标题 */
4410
+ const min = titleRight !== null
4411
+ ? Math.max(HOVER_PLAIN_INSET, titleRight + HOVER_PLAIN_TITLE_GAP)
4412
+ : panelBox.left + HOVER_PLAIN_INSET;
4413
+ /* 右边界:气泡右边界 - 8(再与视口右缘取小) */
4414
+ let max = panelBox.right - HOVER_PLAIN_INSET;
4415
+ if (viewport > 0) max = Math.min(max, viewport - HOVER_PLAIN_INSET);
2644
4416
  if (max < min) return null;
2645
4417
  return { min: min, max: max };
2646
4418
  }
@@ -3614,6 +5386,23 @@ window.__ModuleLoader__.load({
3614
5386
  const barSegments = opened === null
3615
5387
  ? (Array.isArray(tip.segments) ? tip.segments : [])
3616
5388
  : (Array.isArray(opened.segments) ? opened.segments : []);
5389
+ const hoverProbeTexts = opened !== null && opened.tight === true
5390
+ ? barSegments.filter((one) => typeof one.name === "string" && typeof one.percentText === "string")
5391
+ .map((one) => one.name + " " + one.percentText)
5392
+ : [];
5393
+ const hoverProbes = hoverProbeTexts.length > 0 && sub !== null && sub !== undefined
5394
+ && sub.hoverMeasureRef !== null && sub.hoverMeasureRef !== undefined
5395
+ ? h("span", {
5396
+ className: "dsb-hover-measures",
5397
+ key: "__xhovermeasures",
5398
+ ref: sub.hoverMeasureRef,
5399
+ style: { position: "fixed", left: "-10000px", top: "0px", visibility: "hidden", pointerEvents: "none" }
5400
+ }, hoverProbeTexts.map((text, index) => h("span", {
5401
+ className: "dsb-hover-plain dsb-hover-plain-probe",
5402
+ key: "__xhoverprobe" + index,
5403
+ style: { position: "static", display: "inline-block" }
5404
+ }, text)))
5405
+ : null;
3617
5406
  return h("span", {
3618
5407
  className: wide === true ? "dsb-tip dsb-meter dsb-meter-wide" : "dsb-tip dsb-meter",
3619
5408
  key: "__tip", ref: ref, style: panelStyle(pos), onClick: stopTipClick, onMouseDown: stopTipClick
@@ -3671,6 +5460,7 @@ window.__ModuleLoader__.load({
3671
5460
  return h("span", segProps);
3672
5461
  }))
3673
5462
  : h("span", { className: "dsb-meter-divider", key: "__xdiv" }),
5463
+ hoverProbes,
3674
5464
  body
3675
5465
  ]);
3676
5466
  }
@@ -3757,7 +5547,9 @@ window.__ModuleLoader__.load({
3757
5547
  function turnHitRate(sessionUsage) {
3758
5548
  const current = sessionUsage === undefined || sessionUsage === null ? null : sessionUsage.current;
3759
5549
  if (current === null || current === undefined) return "-";
3760
- const denominator = (current.input || 0) + (current.cacheRead || 0) + (current.cacheWrite || 0);
5550
+ /* 缓存字段没上报 ⇒ 本轮命中率给横杠(不拿 0% 冒充) */
5551
+ if (typeof current.cacheRead !== "number" || Number.isFinite(current.cacheRead) !== true) return "-";
5552
+ const denominator = (current.input || 0) + current.cacheRead + (current.cacheWrite || 0);
3761
5553
  if (denominator <= 0) return "-";
3762
5554
  return hitRateText(((current.cacheRead || 0) / denominator) * 100);
3763
5555
  }
@@ -4019,7 +5811,9 @@ window.__ModuleLoader__.load({
4019
5811
 
4020
5812
  /** 余额接口给的金额字符串;没有这个字段时按 0.00 显示。 */
4021
5813
  function balanceAmount(value) {
4022
- return typeof value === "string" && value.length > 0 ? value : "0.00";
5814
+ if (typeof value === "string" && value.length > 0) return value;
5815
+ const n = Number(value);
5816
+ return Number.isFinite(n) ? n.toFixed(2) : "0.00";
4023
5817
  }
4024
5818
 
4025
5819
  /**
@@ -4215,11 +6009,16 @@ window.__ModuleLoader__.load({
4215
6009
  return { title: t("tipCreditsTitle"), totalText: totalText, rewards: rows };
4216
6010
  }
4217
6011
 
4218
- /** 单次调用的缓存命中率(%);这次调用一个输入 token 都没有时返回 null(算不出比例)。 */
6012
+ /** 单次调用的缓存命中率(%);缓存字段没上报或没有输入 token 时返回 null(算不出可信比例)。 */
4219
6013
  function hitRateOf(call) {
4220
- const denominator = (call.input || 0) + (call.cacheRead || 0) + (call.cacheWrite || 0);
6014
+ if (call === null || call === undefined) return null;
6015
+ /* 缓存字段没上报(缺字段 / null / 非数字)⇒ 这笔样本**不可信**:整笔跳过,绝不按 0% 计入。
6016
+ 用户实测「最低命中 0」就是把这些样本当成了真 0%;真实上报的 cacheRead = 0 仍算真 0%。 */
6017
+ if (typeof call.cacheRead !== "number" || Number.isFinite(call.cacheRead) !== true) return null;
6018
+ const denominator = (call.input || 0) + call.cacheRead + (call.cacheWrite || 0);
6019
+ /* 空调用(三路 token 全 0)算不出比例,同样跳过 */
4221
6020
  if (denominator <= 0) return null;
4222
- return ((call.cacheRead || 0) / denominator) * 100;
6021
+ return (call.cacheRead / denominator) * 100;
4223
6022
  }
4224
6023
 
4225
6024
  /** 命中率文本:四舍五入到小数点后三位,第三位是 0 也照留(99.995%、50.000%)。 */
@@ -4401,6 +6200,9 @@ window.__ModuleLoader__.load({
4401
6200
 
4402
6201
  if (id === "cacheHit") {
4403
6202
  if (usage === undefined || usage === null) return null;
6203
+ /* 平均命中率与极值同一口径:缓存字段没上报(缺字段 / null / 非数字)的旧数据,
6204
+ 算不出可信比例 —— 给横杠,不把样本当 0% 命中。 */
6205
+ if (typeof usage.cacheReadTokens !== "number" || Number.isFinite(usage.cacheReadTokens) !== true) return null;
4404
6206
  /* 会话级命中率用**合并后的用量**重算:分母口径与本面板一致
4405
6207
  (命中 + 未命中,未命中 = 未缓存输入 + 缓存写入),只是把队友那一份也加进来。
4406
6208
  气泡里"本轮命中率"照旧只算本页面(用户明确要求)。 */
@@ -4537,10 +6339,11 @@ window.__ModuleLoader__.load({
4537
6339
  displayCurrency: symbolCurrency,
4538
6340
  defaultCurrency: src.defaultCurrency
4539
6341
  });
6342
+ const costShown = held.cost === null ? "-" : costText(held.cost);
4540
6343
  return {
4541
6344
  id: id,
4542
6345
  /* 一条都算不出价(本会话与队友都没价)时给横杠:与"这笔真的是 0"区分开 */
4543
- text: t("f_cost", { symbol: symbol, cost: held.cost === null ? "-" : costText(held.cost) }),
6346
+ text: t("f_cost", { symbol: costShown === "-" ? "" : symbol, cost: costShown }),
4544
6347
  /* token 计数并进总计:本会话的 + 队友的,同一个数字相加,不新增行;
4545
6348
  条形图里队友那部分单独成块画在左边(sub) */
4546
6349
  tip: tokensTip(held.tokens, t("f_tokensTotal"), t, sub)
@@ -4601,9 +6404,10 @@ window.__ModuleLoader__.load({
4601
6404
  };
4602
6405
  const amountText = (amount) => (amount === null || amount === undefined ? "-" : costText(amount));
4603
6406
  if (turnPriced === true || subTurnCost > 0) {
6407
+ const shown = amountText(settleAmount(turnTotal + subTurnCost));
4604
6408
  return {
4605
6409
  id: id,
4606
- text: t("f_lastCost", { symbol: symbol, cost: amountText(settleAmount(turnTotal + subTurnCost)) }),
6410
+ text: t("f_lastCost", { symbol: shown === "-" ? "" : symbol, cost: shown }),
4607
6411
  /* 本轮点开的是本轮 token 明细,读法与总计那个面板同一套 */
4608
6412
  tip: turnTip
4609
6413
  };
@@ -4623,7 +6427,8 @@ window.__ModuleLoader__.load({
4623
6427
  if (active === true && bucket !== null && sameTurn === true) {
4624
6428
  const runningCost = costOf(bucket, fallbackModel, src.now);
4625
6429
  if (runningCost !== null) {
4626
- return { id: id, text: t("f_lastCost", { symbol: symbol, cost: amountText(settleAmount(toDisplayCurrency(runningCost, src.models, fallbackModel, symbolCurrency, src.defaultCurrency) + subTurnCost)) }), tip: turnTip };
6430
+ const shown = amountText(settleAmount(toDisplayCurrency(runningCost, src.models, fallbackModel, symbolCurrency, src.defaultCurrency) + subTurnCost));
6431
+ return { id: id, text: t("f_lastCost", { symbol: shown === "-" ? "" : symbol, cost: shown }), tip: turnTip };
4627
6432
  }
4628
6433
  }
4629
6434
  /* 新一轮已经开跑、但还没有属于它的调用:必须归零,不能退回上一轮
@@ -4638,9 +6443,10 @@ window.__ModuleLoader__.load({
4638
6443
  && Array.isArray(src.sessionUsage.calls) === true
4639
6444
  && src.sessionUsage.calls.length > 0;
4640
6445
  const live = settled === true || subTurnCost > 0 ? subTurnCost : null;
6446
+ const shown = amountText(settleAmount(live));
4641
6447
  return {
4642
6448
  id: id,
4643
- text: t("f_lastCost", { symbol: symbol, cost: amountText(settleAmount(live)) }),
6449
+ text: t("f_lastCost", { symbol: shown === "-" ? "" : symbol, cost: shown }),
4644
6450
  tip: turnTip
4645
6451
  };
4646
6452
  }
@@ -4652,9 +6458,10 @@ window.__ModuleLoader__.load({
4652
6458
  const cost = bucket === null ? null : costOf(bucket, fallbackModel, src.now);
4653
6459
  const idleCost = cost === null ? null : toDisplayCurrency(cost, src.models, fallbackModel, symbolCurrency, src.defaultCurrency);
4654
6460
  const idleValue = idleCost === null && subTurnCost === 0 ? null : (idleCost === null ? 0 : idleCost) + subTurnCost;
6461
+ const shown = amountText(settleAmount(idleValue));
4655
6462
  return {
4656
6463
  id: id,
4657
- text: t("f_lastCost", { symbol: symbol, cost: amountText(settleAmount(idleValue)) }),
6464
+ text: t("f_lastCost", { symbol: shown === "-" ? "" : symbol, cost: shown }),
4658
6465
  tip: turnTip
4659
6466
  };
4660
6467
  }
@@ -4675,27 +6482,33 @@ window.__ModuleLoader__.load({
4675
6482
  气泡里仍然是「充值余额 / 赠金余额」两行,只是没有数字。
4676
6483
  积分口径没有构成可分,这两行不给 —— 而且它整个气泡都不该出现(见下)。 */
4677
6484
  const dashBalance = () => {
4678
- const credits = balanceIsCredits(src.balance);
4679
- const dashSymbol = credits ? "" : currencySymbol(src.currency);
6485
+ /* Magpie 会话在「还没查到 / 网关挂了」时,上游可能是积分也可能是金额,客户端分不出;
6486
+ 此时一律按积分口径显示「余额 -」(不拼 ¥),避免订阅会话第一次加载闪出 ¥-。
6487
+ 查到后 success 分支会用 host 给的 isCredits/currency 覆盖。 */
6488
+ const providerText = src.sessionModel !== undefined && src.sessionModel !== null
6489
+ && typeof src.sessionModel.provider === "string" ? src.sessionModel.provider.toLowerCase() : "";
6490
+ const credits = balanceIsCredits(src.balance) || providerText.includes("magpie");
4680
6491
  if (credits === true) {
4681
6492
  /* 积分口径不给 tip:段没有 tip 就不会变成可点击项(见渲染处的 tip !== null),
4682
6493
  点不出、悬停也不弹。积分只有一个总数、没有可展开的内容,
4683
6494
  弹一个只有标题的空气泡只会让人以为能点。 */
4684
- return { id: id, text: t("f_balanceDash", { symbol: dashSymbol }) };
6495
+ return { id: id, text: t("f_balanceDash", { symbol: "" }) };
4685
6496
  }
4686
6497
  return {
4687
6498
  id: id,
4688
- text: t("f_balanceDash", { symbol: dashSymbol }),
6499
+ text: t("f_balanceDash", { symbol: "" }),
4689
6500
  tip: {
4690
6501
  kind: "rows",
4691
6502
  title: t("segBalance"),
4692
6503
  rows: [
4693
- { label: t("tipTopUp"), value: dashSymbol + "-" },
4694
- { label: t("tipGranted"), value: dashSymbol + "-" }
6504
+ { label: t("tipTopUp"), value: "-" },
6505
+ { label: t("tipGranted"), value: "-" }
4695
6506
  ]
4696
6507
  }
4697
6508
  };
4698
6509
  };
6510
+ /* Magpie 网关:3.0.4 起 Host 会真正读 /v1/magpie/quotas 并按模型/账号返回余额,
6511
+ 所以这里不再强制横杠,直接按 host 返回的 ok/total 渲染(查不到才走横杠)。 */
4699
6512
  /* 显示哪一家的余额由 host 按「会话实际用的模型/平台」决定,这里只看结果:
4700
6513
  查到了就显示,没查到(该平台没配 key / 请求失败)才是横杠。 */
4701
6514
  const balance = src.balance;
@@ -4759,8 +6572,13 @@ window.__ModuleLoader__.load({
4759
6572
  if (sawAny !== true) return null;
4760
6573
  return { topUp: topSum, granted: grantSum };
4761
6574
  })();
4762
- const topUp = balanceTopUpRows === null ? (Number(balance.toppedUp) || 0) : balanceTopUpRows.topUp;
4763
- const granted = balanceTopUpRows === null ? (Number(balance.granted) || 0) : balanceTopUpRows.granted;
6575
+ let topUp = balanceTopUpRows === null ? (Number(balance.toppedUp) || 0) : balanceTopUpRows.topUp;
6576
+ let granted = balanceTopUpRows === null ? (Number(balance.granted) || 0) : balanceTopUpRows.granted;
6577
+ /* 无拆分来源(Magpie 网关 / 第三方中转)只返回总额 total:两行金额都为 0 时用总额兜底第一行,
6578
+ 色条与气泡第一行都会显示该总额,赠金仍为 0;有拆分(如 DeepSeek balances)时行为不变。 */
6579
+ if (balanceTopUpRows === null && Math.max(0, topUp) + Math.max(0, granted) <= 0 && isQuota !== true && isCredits !== true && Number.isFinite(Number(balance.total)) && Number(balance.total) > 0) {
6580
+ topUp = Number(balance.total);
6581
+ }
4764
6582
  const balanceSum = Math.max(0, topUp) + Math.max(0, granted);
4765
6583
  /* ⚠ 百分比配额(智谱 Coding Plan 等)的 `total` 是**已用**百分比,不是余额。
4766
6584
  上游解析器(lib/balance-api.js 的 deepseek 适配器 parse 里的 isPercent 分支)把接口给的 `percentage` 原样当 `total` 返回 ——
@@ -4833,8 +6651,8 @@ window.__ModuleLoader__.load({
4833
6651
  { label: t("tipGranted"), value: costByCurrencyText(currencyMapsOf.granted, 0, t), color: BALANCE_COLORS.granted }
4834
6652
  ]
4835
6653
  : [
4836
- { label: t("tipTopUp"), value: balSymbol + balanceAmount(balance.toppedUp), color: BALANCE_COLORS.topUp },
4837
- { label: t("tipGranted"), value: balSymbol + balanceAmount(balance.granted), color: BALANCE_COLORS.granted }
6654
+ { label: t("tipTopUp"), value: balSymbol + balanceAmount(topUp), color: BALANCE_COLORS.topUp },
6655
+ { label: t("tipGranted"), value: balSymbol + balanceAmount(granted), color: BALANCE_COLORS.granted }
4838
6656
  ]);
4839
6657
  /* 余额气泡:配额口径一行;金额口径**固定两行**(充值余额 / 赠金余额,
4840
6658
  值与是否分币种无关 —— 分币种只影响那两行的**值怎么写**,不影响行数)。
@@ -4905,15 +6723,13 @@ window.__ModuleLoader__.load({
4905
6723
  * 段名说明这一段统计的是什么,缺数据的位置用横杠顶上,
4906
6724
  * 计数、比率、速度、时长各自带上单位(- 轮 - 步 / -m -s / - t/s),
4907
6725
  * 金额段无数据只留横杠,不写「暂无」这类文字。 */
4908
- function detectLocale(t) {
4909
- return t("segCounts") === zh.segCounts ? "zh" : "en";
4910
- }
6726
+ function detectLocale(t) { const probe = t("segCounts"); const all = { zh: zh, en: en, ja: ja, es: es, fr: fr, de: de, ru: ru, pt: pt }; const codes = Object.keys(all); for (let i = 0; i < codes.length; i += 1) { if (probe === all[codes[i]].segCounts) return codes[i]; } return "en"; }
4911
6727
  function segmentText(id, view, t, currency) {
4912
6728
  if (view !== null && view !== undefined) return view.text;
4913
6729
  const segment = SEGMENTS.filter((s) => s.id === id)[0];
4914
6730
  if (segment === undefined || segment.short === undefined) return "";
4915
6731
  const locale = detectLocale(t);
4916
- const label = segment.short[locale] !== undefined ? segment.short[locale] : segment.short.zh;
6732
+ const label = segment.short[locale] !== undefined ? segment.short[locale] : (segment.short.en !== undefined ? segment.short.en : segment.short.zh);
4917
6733
  const dash = "-";
4918
6734
  /* 横杠占位也用**显示币种**的符号(与有数据时一致);没传就退回默认币种 */
4919
6735
  const symbol = currencySymbol(normalizeCurrency(currency === undefined || currency === null ? config.currency : currency));
@@ -4923,8 +6739,8 @@ window.__ModuleLoader__.load({
4923
6739
  /* 速度占位不带单位:英文那边标签已经是 TPS,再跟 t/s 就重复了 */
4924
6740
  if (id === "tps") return label + " " + dash;
4925
6741
  if (id === "sessionTime") return label + " " + dash + "m " + dash + "s";
4926
- if (id === "cost" || id === "lastCost") return label + " " + symbol + dash;
4927
- if (id === "balance") return t("f_balanceDash", { symbol: symbol });
6742
+ if (id === "cost" || id === "lastCost") return label + " " + dash;
6743
+ if (id === "balance") return t("f_balanceDash", { symbol: "" });
4928
6744
  return dash;
4929
6745
  }
4930
6746
 
@@ -4947,7 +6763,7 @@ window.__ModuleLoader__.load({
4947
6763
  const locale = detectLocale(t);
4948
6764
  const label = segment === undefined || segment.short === undefined
4949
6765
  ? t("segBalance")
4950
- : (segment.short[locale] !== undefined ? segment.short[locale] : segment.short.zh);
6766
+ : (segment.short[locale] !== undefined ? segment.short[locale] : (segment.short.en !== undefined ? segment.short.en : segment.short.zh));
4951
6767
  return {
4952
6768
  kind: "rows",
4953
6769
  title: t("tipEmptyTitle", { label: label }),
@@ -5032,11 +6848,13 @@ window.__ModuleLoader__.load({
5032
6848
  ".dsb-bar-hoverable .dsb-bar-seg:hover{transform:scaleY(1.45);z-index:2}",
5033
6849
  /* 工具彩条的悬停提示:**不要气泡、也不要阴影**,只显示一行文字(比 10px 的悬停浮层大、
5034
6850
  但小于 12px 的标题)。位置由 JS 给 left/top,贴在鼠标上方很近处。 */
5035
- /* 气泡上的工具名悬停提示。**z-index = 106,必须始终比气泡(105)高一层**:
6851
+ /* 气泡上的工具名悬停提示。**z-index = 120,必须始终比气泡面板(105)高**:
5036
6852
  它是气泡内部的提示,被自己的容器盖住就没意义了。
5037
- 106 同样夹在官方档位的 101(子菜单)与 1000(对话框/遮罩)之间 ——
5038
- 盖得住对话区的浮动控件,又盖不住系统级弹层。详见 `.dsb-tip` 那段的说明。 */
5039
- ".dsb-hover-plain{position:fixed;z-index:106;pointer-events:none;white-space:nowrap;font-size:11px;line-height:15px;font-weight:500;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}",
6853
+ 它和气泡一样 Portal 到 body、同层比较 z-index;120 仍夹在官方 101(子菜单)与 1000(遮罩)之间 ——
6854
+ 盖得住气泡,又盖不住系统级弹层。详见 `.dsb-tip` 那段的说明。 */
6855
+ ".dsb-hover-plain{position:fixed;z-index:120;pointer-events:none;white-space:nowrap;font-size:11px;line-height:15px;font-weight:500;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}",
6856
+ ".dsb-hover-measures{position:fixed;left:-10000px;top:0;visibility:hidden;pointer-events:none}",
6857
+ ".dsb-hover-plain-probe{position:static;display:inline-block}",
5040
6858
  /* 宽度按内容自适应:width:max-content 让气泡收到"最长那一行"的宽度,
5041
6859
  * 行内标签与数值之间至少留 5ch(.dsb-meter-value 的 padding-left),所以不会出现大片留白;
5042
6860
  * 内容超过 max-width 时退回换行(white-space:normal)。 */
@@ -5189,7 +7007,9 @@ window.__ModuleLoader__.load({
5189
7007
  ".dsb-heat-top{background:#a78bfa}",
5190
7008
  /* 悬停浮层:与主气泡同一套质感,但字号比标题(12px)更小、行距更紧、数值不加粗。
5191
7009
  选择器必须带上 .dsb-tip.dsb-meter 这一段,否则压不过主气泡那两条高优先级的字号声明。 */
5192
- ".dsb-tip.dsb-hovercard{font-size:10px;line-height:14px}",
7010
+ /* 悬停浮层要 Portal 到 body;z-index 120 高于官方气泡档(100/101),
7011
+ pointer-events:none 防止浮层截获鼠标导致气泡闪跳。 */
7012
+ ".dsb-tip.dsb-hovercard{font-size:10px;line-height:14px;z-index:120;pointer-events:none}",
5193
7013
  ".dsb-tip.dsb-hovercard .dsb-meter-rows{margin-top:2px}",
5194
7014
  ".dsb-tip.dsb-hovercard .dsb-meter-row{padding:0;gap:4px}",
5195
7015
  ".dsb-tip.dsb-hovercard .dsb-meter-figures{font-weight:400;padding-left:5ch}",
@@ -5239,7 +7059,8 @@ window.__ModuleLoader__.load({
5239
7059
  ".dsb-root,.dsb-tip,.dsb-settings,.dsb-hover-plain,.dsb-drag-card{user-select:none;-webkit-user-select:none}",
5240
7060
  ".dsb-root ::selection,.dsb-tip ::selection,.dsb-settings ::selection,.dsb-hover-plain::selection,.dsb-drag-card ::selection{background:transparent;color:inherit}",
5241
7061
  /* 设置页里的输入框要能选中/编辑(改价格那几个 number 框):单独放开 */
5242
- ".dsb-settings input,.dsb-settings textarea{user-select:text;-webkit-user-select:text}",
7062
+ ".dsb-settings input,.dsb-settings textarea{user-select:text !important;-webkit-user-select:text !important}",
7063
+ ".dsb-settings input::selection,.dsb-settings textarea::selection{background:#0078D4;color:#ffffff;background:Highlight;color:HighlightText}",
5243
7064
  /* 这里的 14px 是面板内所有文字的继承来源;挂到 body 的跟手浮层继承不到它,
5244
7065
  那边(.dsb-drag-card)自己写死了一份 —— 改这里要同步那边。 */
5245
7066
  ".dsb-settings{display:flex;flex-direction:column;gap:18px;font-size:14px}",
@@ -5249,6 +7070,8 @@ window.__ModuleLoader__.load({
5249
7070
  ".dsb-settings .dsb-intro{margin:0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.6}",
5250
7071
  ".dsb-settings .dsb-section{display:flex;flex-direction:column;gap:8px}",
5251
7072
  ".dsb-settings .dsb-sectitle{color:var(--dsw-alias-label-primary);font-size:13px;font-weight:600;letter-spacing:.02em}",
7073
+ /* task-20:胶囊样式保持不变,只把角标按 x² 的上标位置贴在「第三方平台」右上角 */
7074
+ ".dsb-settings .dsb-experimental-badge{padding:1px 3px;border:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.3));border-radius:999px;font-size:6px;line-height:10px;font-weight:400;color:var(--dsw-alias-label-secondary);white-space:nowrap;vertical-align:super;margin-left:2px}",
5252
7075
  ".dsb-settings .dsb-hint{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:1.6}",
5253
7076
  ".dsb-settings .dsb-row{display:flex;align-items:center;justify-content:space-between;gap:12px;border-radius:8px;padding:6px 8px;background:var(--dsw-alias-bg-layer-1,transparent);user-select:none;-webkit-user-select:none}",
5254
7077
  ".dsb-settings .dsb-row:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.08))}",
@@ -5298,24 +7121,68 @@ window.__ModuleLoader__.load({
5298
7121
  ".dsb-settings .dsb-card{border:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.25));border-radius:10px;padding:10px 12px;display:flex;flex-direction:column;gap:10px}",
5299
7122
  ".dsb-settings .dsb-current{display:flex;align-items:center;gap:12px;color:var(--dsw-alias-label-secondary);font-size:13px;line-height:1.6}",
5300
7123
  ".dsb-settings .dsb-current b{color:var(--dsw-alias-label-primary);font-weight:600}",
5301
- /* 「更新节假峰谷」+ 状态提示整体贴到这一行的右端,与下面的添加/修改按钮同一条右边界;
5302
- 提示在按钮前面,出现时按钮的右边界不动 */
5303
- ".dsb-settings .dsb-current-act{display:flex;align-items:center;gap:8px;margin-left:auto}",
7124
+ ".dsb-settings .dsb-price-catalog{display:flex;flex-direction:column;gap:4px;margin:0 -12px -6px;padding:0 12px}",
7125
+ ".dsb-settings .dsb-catalog-vendor{border-top:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.18))}",
7126
+ ".dsb-settings .dsb-catalog-summary{display:flex;align-items:center;justify-content:flex-start;gap:8px;box-sizing:border-box;min-height:38px;padding:7px 2px 3px 2px;line-height:20px;color:var(--dsw-alias-label-primary);font-size:14px;font-weight:500;cursor:pointer;list-style:none}",
7127
+ ".dsb-settings .dsb-catalog-summary::-webkit-details-marker{display:none}",
7128
+ '.dsb-settings .dsb-catalog-summary::before{content:"";flex:none;width:6px;height:6px;border-right:1px solid currentColor;border-bottom:1px solid currentColor;transform:rotate(-45deg);transition:transform .12s ease}',
7129
+ ".dsb-settings .dsb-catalog-vendor[open]>.dsb-catalog-summary::before{transform:rotate(45deg)}",
7130
+ ".dsb-settings .dsb-catalog-summary:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4d6bfe);outline-offset:2px}",
7131
+ ".dsb-settings .dsb-catalog-list{display:flex;flex-direction:column;gap:0;padding:0 0 0 14px;min-width:0;margin-top:4px}",
7132
+
7133
+ ".dsb-settings .dsb-catalog-model{display:flex;flex-direction:column;gap:4px;padding:4px 0;border-top:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.18));min-width:0}",
7134
+ ".dsb-settings .dsb-catalog-list .dsb-catalog-model:first-child{margin-left:-14px;padding-left:14px;}",
5304
7135
  ".dsb-settings .dsb-models{display:flex;flex-direction:column}",
5305
- ".dsb-settings .dsb-model{position:relative;display:flex;flex-direction:column;gap:8px;padding:6px 0;border-top:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.18))}",
7136
+ ".dsb-settings .dsb-model{position:relative;display:flex;flex-direction:column;gap:4px;padding:4px 0;border-top:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.18))}",
5306
7137
  /* 编辑区:毛玻璃浮层,从卡片头部下方展开,盖在下面的内容上 */
5307
- ".dsb-settings .dsb-edit-pop{position:absolute;top:calc(100% - 2px);left:0;right:0;z-index:55;display:flex;flex-direction:column;gap:8px;padding:10px 12px;border-radius:var(--dsw-radius-lg,16px);background:rgb(from var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1,#1f1f1f)) r g b / .382);backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));box-shadow:0 0 0 .5px var(--dsw-alias-border-l1,rgba(127,127,127,.3))}",
5308
- ".dsb-settings .dsb-tier{display:flex;align-items:center;gap:8px;flex-wrap:wrap}",
7138
+ ".dsb-settings .dsb-edit-pop{position:absolute;top:calc(100% + 2px);left:0;right:0;z-index:55;overflow:visible;display:flex;flex-direction:column;gap:8px;padding:10px 12px;border-radius:var(--dsw-radius-lg,16px);background:rgb(from var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1,#1f1f1f)) r g b / .382);backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));box-shadow:0 0 0 .5px var(--dsw-alias-border-l1,rgba(127,127,127,.3))}",
7139
+ /* 平台编辑用毛玻璃浮层 */
7140
+ /* 适用模型行:每行自带标签(像「请求头 / 用户 ID」那样:标签在左、控件紧随其后)。
7141
+ 模型行 = 自定义下拉占满剩余宽度;倍率行 = 输入框 + 行尾删除按钮(不再绝对定位) */
7142
+ ".dsb-settings .dsb-modelrow-fee{flex:1 1 0;min-width:0;display:flex;align-items:center;gap:8px}",
7143
+ ".dsb-settings .dsb-modelrow-fee .dsb-action{margin-left:auto;flex:none}",
7144
+ ".dsb-settings .dsb-select-empty .dsb-select-btn{color:var(--dsw-alias-label-tertiary);opacity:1;background:var(--dsw-alias-bg-layer-1,#fff)}",
7145
+ ".dsb-settings .dsb-select-placeholder{opacity:.5}",
7146
+ ".dsb-settings .dsb-modelrow-fee input[type=number]{width:calc(5ch + 18px);min-width:calc(5ch + 18px);text-align:left}",
7147
+ ".dsb-settings .dsb-relay-fields .dsb-action{flex:none}",
7148
+ /* 价格行不换行:档位名与后面那组价格框始终同一行;空间不够时由 .dsb-fields 内部换行 */
7149
+ ".dsb-settings .dsb-tier{display:flex;align-items:center;gap:8px;flex-wrap:nowrap}",
5309
7150
  ".dsb-settings .dsb-tier-name{flex:none;width:48px;white-space:nowrap;font-size:12px;color:var(--dsw-alias-label-secondary)}",
5310
7151
  ".dsb-settings .dsb-model:first-child{border-top:0;padding-top:0}",
5311
7152
  ".dsb-settings .dsb-model:last-child{padding-bottom:0}",
5312
- ".dsb-settings .dsb-model-name{color:var(--dsw-alias-label-primary);font-weight:600;font-size:13px}",
5313
- ".dsb-settings .dsb-model-head{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:28px}",
5314
- ".dsb-settings .dsb-model-actions{display:flex;gap:6px;flex:none}",
7153
+ /* 厂商展开后的模型行:每行上下内边距统一 4px,名字与右侧按钮同行垂直居中 */
7154
+ ".dsb-settings .dsb-models .dsb-model{padding:4px 0;border-top:0}",
7155
+ ".dsb-settings .dsb-models .dsb-model:first-child{padding-top:4px}",
7156
+ ".dsb-settings .dsb-models .dsb-model:last-child{padding-bottom:4px}",
7157
+ ".dsb-settings .dsb-model-name{color:var(--dsw-alias-label-primary);font-weight:400;font-size:13px;line-height:18px}",
7158
+ ".dsb-settings .dsb-model-head{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:26px}",
7159
+ ".dsb-settings .dsb-model-actions{display:flex;align-items:center;gap:6px;flex:none}",
7160
+ /* 第三方平台行:紧凑高度、整行(按钮外)可点展开/收起;平台名带箭头且垂直居中 */
7161
+ ".dsb-settings .dsb-platform-list{display:flex;flex-direction:column;gap:0;margin:0 -12px -6px;padding:0 12px}",
7162
+ ".dsb-settings .dsb-platform-list .dsb-platform-row:first-child{border-top:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.18))}",
7163
+ ".dsb-settings .dsb-platform-row{position:relative;padding:0;gap:0;height:38px;box-sizing:border-box;justify-content:center}",
7164
+ ".dsb-settings .dsb-platform-head{min-height:0;align-items:center}",
7165
+ ".dsb-settings .dsb-platform-row:not(.dsb-open) .dsb-platform-head{position:absolute;left:0;right:0;top:0;bottom:0;height:auto;display:flex;align-items:center}",
7166
+ ".dsb-settings .dsb-platform-title{flex:1 1 auto;min-width:0;display:flex;align-items:center;gap:6px;padding:0 2px;cursor:pointer;font-size:14px;font-weight:500;line-height:normal;color:var(--dsw-alias-label-primary);justify-content:flex-start}",
7167
+ ".dsb-settings .dsb-platform-row:not(.dsb-open) .dsb-platform-title{height:auto;align-self:center;}",
7168
+ ".dsb-settings .dsb-platform-title::before{content:\"\";flex:none;width:6px;height:6px;border-right:1px solid currentColor;border-bottom:1px solid currentColor;transform:rotate(-45deg);transition:transform .12s ease}",
7169
+ ".dsb-settings .dsb-platform-title.dsb-open::before{transform:rotate(45deg)}",
7170
+ ".dsb-settings .dsb-platform-title.dsb-open.dsb-pop-up::before{transform:rotate(-135deg)}",
7171
+ ".dsb-settings .dsb-platform-row.dsb-open .dsb-platform-head{min-height:38px;align-items:center}",
7172
+ ".dsb-settings .dsb-platform-row.dsb-open .dsb-platform-title{min-height:36px}",
7173
+ ".dsb-settings .dsb-platform-pop{gap:4px;padding:8px 10px;left:0;right:0;max-height:min(70vh,calc(100vh - 120px));overflow-y:auto;overscroll-behavior:contain}",
7174
+ ".dsb-settings .dsb-platform-pop .dsb-platform-model-list{display:flex;flex-direction:column;gap:4px;max-height:calc(5 * 32px);overflow-y:auto;scrollbar-width:none}",
7175
+ ".dsb-settings .dsb-platform-pop .dsb-platform-model-list::-webkit-scrollbar{display:none;width:0;height:0}",
7176
+ ".dsb-settings .dsb-token-input{-webkit-text-security:disc;text-security:disc;}",
7177
+ ".dsb-settings .dsb-platform-pop .dsb-relay-fields{gap:4px}",
7178
+ ".dsb-settings .dsb-platform-pop .dsb-relay-row + .dsb-relay-row{margin-top:0}",
7179
+ ".dsb-settings .dsb-platform-pop .dsb-relay-line,.dsb-settings .dsb-platform-pop .dsb-relay-row{min-height:28px;margin:0}",
7180
+ ".dsb-settings .dsb-platform-pop .dsb-modelrow-select .dsb-select-btn{height:28px;font-size:13px}",
5315
7181
  /* 峰谷计价那个勾选只占"勾选框 + 四个字"的宽度,不然整行都能点 */
5316
7182
  ".dsb-settings .dsb-inline-check{display:flex;align-self:flex-start;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-secondary);cursor:pointer}",
5317
7183
  /* 勾选在左、计价单位在右 */
5318
7184
  ".dsb-settings .dsb-tier-head{display:flex;align-items:center;justify-content:space-between;gap:8px}",
7185
+ ".dsb-settings .dsb-tier-checks{display:flex;align-items:center;gap:12px}",
5319
7186
  /* 币种只有条目这一个下拉:CSS 给它的位置留白(条目级选择器与"峰谷计价"同一行) */
5320
7187
  ".dsb-settings .dsb-currency-pick{display:flex;align-items:center;gap:8px}",
5321
7188
  ".dsb-settings .dsb-select{position:relative}",
@@ -5324,21 +7191,42 @@ window.__ModuleLoader__.load({
5324
7191
  /* 下拉复刻底栏气泡那套材质:半透明菜单底 + 毛玻璃 + 大圆角 + .5px 描边柔光 */
5325
7192
  /* 宽度贴合文字:原先写死 min-width:92px,只有三个字母的菜单右边空出一大截。
5326
7193
  材质保持毛玻璃,只把不透明度从 .382 提到 .618 —— 原来太透,底下价格卡上的数字会透上来。 */
5327
- ".dsb-settings .dsb-select-menu{position:absolute;top:calc(100% + 4px);right:0;padding:4px;border-radius:var(--dsw-radius-lg,16px);background:rgb(from var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1,#1f1f1f)) r g b / .618);backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));box-shadow:0 0 0 .5px var(--dsw-alias-border-l1,rgba(127,127,127,.3));z-index:60}",
7194
+ ".dsb-settings .dsb-select-menu{box-sizing:border-box;position:absolute;top:calc(100% + 4px);right:0;padding:4px;border-radius:var(--dsw-radius-lg,16px);background:rgb(from var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1,#fff)) r g b / .96);backdrop-filter:blur(40px) saturate(180%);-webkit-backdrop-filter:blur(40px) saturate(180%);box-shadow:0 0 0 .5px var(--dsw-alias-border-l1,rgba(127,127,127,.3));z-index:60}",
5328
7195
  ".dsb-settings .dsb-select-item{display:block;width:100%;padding:6px 10px;border:0;border-radius:var(--dsw-radius-sm,8px);background:transparent;font:inherit;font-size:12px;color:var(--dsw-alias-label-primary);text-align:left;cursor:pointer}",
5329
7196
  ".dsb-settings .dsb-select-item:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}",
5330
7197
  ".dsb-settings .dsb-select-item-on{color:var(--dsw-alias-brand-primary,#4d6bfe)}",
7198
+ /* 已被本平台其他行选中的模型:灰显、不可点 */
7199
+ ".dsb-settings .dsb-select-item-disabled{opacity:.45;cursor:not-allowed}",
7200
+ /* 平台「适用模型」下拉:占满左侧列,菜单强制向下、限制在设置页内 */
7201
+ ".dsb-settings .dsb-modelrow-select{flex:1 1 0;min-width:0}",
7202
+ ".dsb-settings .dsb-modelrow-select .dsb-select-btn{display:flex;width:100%;height:28px;box-sizing:border-box;font-size:13px;justify-content:flex-start;text-align:left;white-space:nowrap;overflow:hidden}",
7203
+ ".dsb-settings .dsb-modelrow-menu{box-sizing:border-box;max-width:100%;left:0;right:auto;width:100%;max-height:calc(3 * 30px + 8px);overflow-y:auto;overscroll-behavior:contain;scrollbar-width:none;background:rgb(from var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1,#fff)) r g b / .96);backdrop-filter:blur(40px) saturate(180%);-webkit-backdrop-filter:blur(40px) saturate(180%)}",
7204
+ ".dsb-settings .dsb-modelrow-menu::-webkit-scrollbar{display:none;width:0;height:0}",
7205
+ ".dsb-settings .dsb-modelrow-menu .dsb-select-item{display:flex;align-items:center;height:30px;box-sizing:border-box;padding:0 10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
5331
7206
  /* 三组字段整体贴右边缘:左边留给时段名,右边一列对齐。
5332
7207
  未勾选「峰谷计价」时那行也走同一套 —— 左边是「全时段」标签,
5333
7208
  不再用"单档那行没有档位名"时的那条双边对齐规则(用户嫌它跟勾选后的两行不一致)。 */
5334
- ".dsb-settings .dsb-fields{display:flex;flex-wrap:wrap;gap:8px;margin-left:auto}",
7209
+ ".dsb-settings .dsb-fields{display:flex;flex:1;min-width:0;flex-wrap:wrap;justify-content:flex-end;gap:8px}",
5335
7210
  ".dsb-settings .dsb-field{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-tertiary)}",
5336
- /* 够放 xx.xx 就行,输入框不再拉一大条 */
7211
+ ".dsb-settings .dsb-relay-fields{display:flex;flex-direction:column;gap:8px;padding:0;border:0;background:transparent}",
7212
+ ".dsb-settings .dsb-relay-line{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--dsw-alias-label-tertiary)}",
7213
+ /* 请求头 / 用户 ID:左右各一半(同一行两个 label,各自 flex:1) */
7214
+ ".dsb-settings .dsb-relay-row{display:flex;align-items:center;gap:8px;width:100%;box-sizing:border-box}",
7215
+ ".dsb-settings .dsb-relay-row>.dsb-relay-line{flex:1 1 0;min-width:0;width:0}",
7216
+ ".dsb-settings .dsb-relay-line>span:first-child{flex:none;width:84px;white-space:nowrap}",
7217
+ ".dsb-settings .dsb-relay-line input{flex:1 1 0;min-width:0;width:0;box-sizing:border-box;height:28px;padding:0 8px;font:inherit;font-size:13px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-1,#fff);border:1px solid var(--dsw-alias-separator-primary,rgba(127,127,127,.3));border-radius:6px;outline:none}",
7218
+ /* 与 .dsb-settings input[type=text] 的聚焦态一致(密码框不在那条通用规则里,必须单列) */
7219
+ ".dsb-settings .dsb-relay-line input:focus{border-color:var(--dsw-alias-brand-primary,#4d6bfe)}",
7220
+ ".dsb-settings .dsb-relay-line input::placeholder{color:var(--dsw-alias-label-tertiary);opacity:.5}",
7221
+ /* 够放 XXX.XX 就行,输入框不再拉一大条 —— 但 52px 连「28.41」都显示不全
7222
+ (用户实测:Claude 条目切成人民币后数值被截断)。88px = 6 位数字(13px 字号)
7223
+ + 左右 padding 16px + 边框 2px 还有余量;`flex:none` 保证窄面板下也不被压窄
7224
+ (`.dsb-fields` 本来就 flex-wrap:wrap,放不下就整组换行,不会挤坏)。 */
5337
7225
  /* 价格框:只有它 24px。选择器必须带 input[type=...] —— 通用规则
5338
7226
  `.dsb-settings input[type=number]{height:28px}` 的权重与 `.dsb-field input` 相等、
5339
7227
  又排在后面,会把高度覆盖回去(实测踩过:用户看到"又变高了")。
5340
7228
  自定义模型的名称框走通用规则,保持 28px。 */
5341
- ".dsb-settings .dsb-field input[type=text],.dsb-settings .dsb-field input[type=number]{width:52px;height:24px;text-align:right}",
7229
+ ".dsb-settings .dsb-field input[type=text],.dsb-settings .dsb-field input[type=number]{width:calc(6ch + 18px);min-width:calc(6ch + 18px);flex:none;height:24px;text-align:right}",
5342
7230
  ".dsb-settings input[type=number]::-webkit-outer-spin-button,.dsb-settings input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}",
5343
7231
  ".dsb-settings input[type=number]{-moz-appearance:textfield;appearance:textfield}",
5344
7232
  ".dsb-settings input::placeholder{color:var(--dsw-alias-label-tertiary);opacity:.5}",
@@ -5402,6 +7290,25 @@ window.__ModuleLoader__.load({
5402
7290
  /* 导航图标使用外部传入的 gauge(24x24 lucide,stroke=currentColor,随主题变色) */
5403
7291
  const NAV_ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-gauge"><path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/></svg>';
5404
7292
 
7293
+ /** 设置导航的 gauge 图标:官方 `settings.section.icon` 槽与 DOM 兜底共用同一形状。 */
7294
+ function NavIcon() {
7295
+ return h("svg", {
7296
+ xmlns: "http://www.w3.org/2000/svg",
7297
+ width: 16,
7298
+ height: 16,
7299
+ viewBox: "0 0 24 24",
7300
+ fill: "none",
7301
+ stroke: "currentColor",
7302
+ strokeWidth: 2,
7303
+ strokeLinecap: "round",
7304
+ strokeLinejoin: "round",
7305
+ className: "lucide lucide-gauge"
7306
+ }, [
7307
+ h("path", { key: "__gaugeNeedle", d: "m12 14 4-4" }),
7308
+ h("path", { key: "__gaugeArc", d: "M3.34 19a10 10 0 1 1 17.32 0" })
7309
+ ]);
7310
+ }
7311
+
5405
7312
  /**
5406
7313
  * 把设置导航里本插件那一项的前导图标换成 gauge。
5407
7314
  * 定位方式是按导航文案匹配(DSH 没给导航项留 id 属性),匹配不到就什么都不做。
@@ -5438,8 +7345,6 @@ window.__ModuleLoader__.load({
5438
7345
  let devMode = false;
5439
7346
  /** 演示用的假版本号:一眼看出不是真版本,避免被误当成真实更新。 */
5440
7347
  const DEV_VERSION = "9.9.9";
5441
- /** 演示用的假失败原因,走的就是真实失败时那条显示路径。 */
5442
- const DEV_FAIL_REASON = "release-age";
5443
7348
  /* 更新失败的**全部分类**,与 host 侧 `classifyPnpmFailure()` 的返回值一一对应
5444
7349
  (见 lib/self-update.js:outdated-lockfile / store-error / postinstall-failed /
5445
7350
  symlink-failed / disk-full / install-failed),另加 `timeout` 与 `release-age`
@@ -7424,14 +9329,16 @@ window.__ModuleLoader__.load({
7424
9329
  if (marked !== true && String(cell.textContent).trim() !== label) continue;
7425
9330
  if (marked !== true && typeof cell.setAttribute === "function") cell.setAttribute(NAV_MARK, "1");
7426
9331
  if (typeof getPill === "function") syncNavPill(cell, String(getPill()));
7427
- if (cell.querySelector(".lucide-gauge") !== null) continue; /* 已经换过 */
7428
- const first = cell.firstElementChild;
7429
- if (first === null || typeof first.tagName !== "string" || first.tagName.toLowerCase() !== "svg") continue;
9332
+ if (cell.querySelector(".lucide-gauge") !== null) continue; /* 图标槽已渲染 / 已经换过 */
9333
+ /* 宿主 0.2.2-rc.1 起把图标包进 `span.navIcon`(按钮第一个子元素不再是 svg);
9334
+ 旧宿主则是按钮第一个子元素直接为 svg。两种结构都兜住,找不到就什么都不做。 */
9335
+ const target = cell.querySelector("span.navIcon svg") || cell.querySelector("svg");
9336
+ if (target === null || target === undefined) continue;
7430
9337
  const box = document.createElement("span");
7431
9338
  box.innerHTML = NAV_ICON_SVG;
7432
9339
  const gauge = box.firstElementChild;
7433
9340
  if (gauge === null) continue;
7434
- first.replaceWith(gauge);
9341
+ target.replaceWith(gauge);
7435
9342
  }
7436
9343
  };
7437
9344
  let scheduled = false;
@@ -7576,10 +9483,19 @@ window.__ModuleLoader__.load({
7576
9483
  return;
7577
9484
  }
7578
9485
  if (models === null || Object.keys(models).length === 0) return;
9486
+ /* base 只是客户端内部基准价:上报前剥掉(Host 的价格 sanitize 会丢它,没必要白带) */
9487
+ const hostModels = {};
9488
+ Object.keys(models).forEach((name) => {
9489
+ const one = models[name];
9490
+ if (one === null || one === undefined || typeof one !== "object") { hostModels[name] = one; return; }
9491
+ const copy = Object.assign({}, one);
9492
+ delete copy.base;
9493
+ hostModels[name] = copy;
9494
+ });
7579
9495
  window.fetch(PRICES_URL, {
7580
9496
  method: "POST",
7581
9497
  headers: { "content-type": "application/json" },
7582
- body: JSON.stringify({ models: models })
9498
+ body: JSON.stringify({ models: hostModels })
7583
9499
  }).then((response) => {
7584
9500
  /* 失败要说出来。原先只有 `.catch(() => {})`,而 fetch 对 4xx/5xx 是
7585
9501
  **resolve** 不是 reject —— 上报被拒(如体积超限返回 400)时既不进
@@ -7596,6 +9512,7 @@ window.__ModuleLoader__.load({
7596
9512
  });
7597
9513
  }, [reportedPrices, devActive]);
7598
9514
 
9515
+
7599
9516
  const running = pick(useSession, (s) => s.running, undefined);
7600
9517
  const partial = pick(useSession, (s) => s.partial, undefined);
7601
9518
  const runningCalls = pick(useSession, (s) => s.runningCalls, undefined);
@@ -7640,7 +9557,7 @@ window.__ModuleLoader__.load({
7640
9557
  换会话时整份状态由 applyTotalFloor 自己清空,这里不必额外处理。 */
7641
9558
  const totalHoldRef = react.useRef({
7642
9559
  sessionId: null, seen: new Map(), cost: 0, tokens: null,
7643
- priced: false, subCostSettled: 0, debts: new Map()
9560
+ priced: false, subCostSettled: 0, debts: new Map(), feeFingerprint: ""
7644
9561
  });
7645
9562
  /* 点开「总计」气泡时 +1:强制重拉一次队友用量(别的触发条件都带 SUBAGENT_REFRESH_MS 节流) */
7646
9563
  const [subagentTick, setSubagentTick] = react.useState(0);
@@ -7665,21 +9582,24 @@ window.__ModuleLoader__.load({
7665
9582
  const [hoverPos, setHoverPos] = react.useState(null);
7666
9583
  /* 工具彩条段悬停的「无气泡纯文字」内容(工具名 + 占比);有值时只渲染一行文字 */
7667
9584
  const [hoverPlain, setHoverPlain] = react.useState(null);
7668
- /* 工具名悬停提示**整组开关**(用户拍板):当前气泡放不下那行小字时置 true,
7669
- 此后所有工具名的悬停都不再挂 onMouseEnter。由气泡定位 effect 量出实际宽度后判定
7670
- (见 plainFits);换气泡 / 换子视图时由那条 effect 重新得出结论。 */
9585
+ /* 工具名悬停提示**整组开关**(用户拍板):当前工具列表里有个名字比**视口**还宽时置 true,
9586
+ 此后所有工具名的悬停都不再挂 onMouseEnter(不是只关超长那个 —— 半套提示更难看)。
9587
+ 判据用离屏探针量出的最大名字宽度 vs **气泡内部可用宽度**(见 plainFits);提示画在气泡里。
9588
+ **必须能自己恢复**:气泡变长 / 变宽后重测,放得下了就整组打开 —— 以前只有 window
9589
+ resize 才重测,气泡自己变长没有任何信号,于是一次「放不下」就把本次会话的悬停
9590
+ 永久关死(用户实测的「完全不弹提示」)。重测由下面的 ResizeObserver 触发。 */
7671
9591
  const [hoverPlainOff, setHoverPlainOff] = react.useState(false);
7672
- /* 纯文字提示的固定垂直位置(与气泡标题行文字居中对齐):定位 effect 算好后存这里,
9592
+ /* 纯文字提示的固定垂直位置(画在**气泡内部**、标题行下方):定位 effect 算好后存这里,
7673
9593
  段内左右移动时直接复用,保证「只左右移动、不上下移动」且不抖。 */
7674
9594
  const hoverPlainTopRef = react.useRef(null);
7675
- /* 纯文字提示的水平夹取范围:左 = 「工具调用」标题右边界 + 1ch,右 = 色条右边界
7676
- (再与视口右缘取小)。定位 effect 里算一次存这里,段内移动时复用。 */
9595
+ /* 纯文字提示的水平夹取范围:**气泡内部**(左右各 8px),提示在气泡里跟随鼠标。 */
7677
9596
  const hoverPlainBoundsRef = react.useRef(null);
7678
9597
  /* 当前悬停的是哪一周(用来给那条底板加深);悬停方块/柱子时为 null */
7679
9598
  const [hoverWeek, setHoverWeek] = react.useState(null);
7680
9599
  /* 当前悬停的是哪一根柱(那一列的判定区变灰);不在柱上时为 null */
7681
9600
  const [hoverBar, setHoverBar] = react.useState(null);
7682
9601
  const hoverRef = react.useRef(null);
9602
+ const hoverMeasureRef = react.useRef(null);
7683
9603
  /* 工具调用彩条悬停时「跟着鼠标走」:鼠标坐标(clientX / clientY)。
7684
9604
  仅鼠标跟随型浮层(payload.follow === true)设置;活跃总览的柱/方块不设,仍贴整个气泡上方。 */
7685
9605
  const [hoverMouse, setHoverMouse] = react.useState(null);
@@ -7736,14 +9656,14 @@ window.__ModuleLoader__.load({
7736
9656
  if (node.style === undefined || node.style === null) return;
7737
9657
  const size = node.getBoundingClientRect();
7738
9658
  if (hoverPlain !== null) {
7739
- /* 纯文字提示:水平夹在「标题右边界 ~ 色条右边界」之间(放不放得下已在定位 effect
7740
- 判过,能走到这里就说明放得下,不做任何缩放)。宽度用 offsetWidth(不含 transform)。 */
9659
+ /* 纯文字提示:水平夹在「标题右边界 ~ 色条右边界」之间(放不放得下在悬停那一刻已
9660
+ 按名字判过,能走到这里就说明放得下,不做任何缩放)。宽度用 offsetWidth(不含 transform)。 */
7741
9661
  const layoutWidth = typeof node.offsetWidth === "number" && node.offsetWidth > 0
7742
9662
  ? node.offsetWidth
7743
9663
  : size.width;
7744
9664
  const left = clampPlainLeft(event.clientX - layoutWidth / 2, layoutWidth, hoverPlainBoundsRef.current, window.innerWidth);
7745
9665
  node.style.left = left + "px";
7746
- /* 上下固定:沿用 title 行居中算出的 top */
9666
+ /* 上下固定:沿用定位 effect 算好的「气泡上方」top(段内只左右移动) */
7747
9667
  if (hoverPlainTopRef.current !== null) node.style.top = hoverPlainTopRef.current + "px";
7748
9668
  } else {
7749
9669
  const left = Math.max(8, Math.min(event.clientX - size.width / 2, window.innerWidth - size.width - 8));
@@ -7768,7 +9688,7 @@ window.__ModuleLoader__.load({
7768
9688
  const tipDiagRef = react.useRef(null);
7769
9689
  /* 窗口缩放时 +1:定位 effect 没有依赖数组(每次渲染都重算),
7770
9690
  但 resize 本身不会引起渲染,得靠它推一次 */
7771
- const [, setTipTick] = react.useState(0);
9691
+ const [tipTick, setTipTick] = react.useState(0);
7772
9692
 
7773
9693
  /* 本轮费用兜底:官方全量 tokenUsage 差分 */
7774
9694
  const turnBaseRef = react.useRef(null);
@@ -7836,6 +9756,16 @@ window.__ModuleLoader__.load({
7836
9756
  return () => window.clearTimeout(timer);
7837
9757
  }, [needsNow, running, clockActive, subagentBusy, devActive]);
7838
9758
 
9759
+ /* 节假日自动更新:不新增定时器,借现有时钟 now 每跳检查一次;
9760
+ 打开 DSH 首次渲染也会跑一次(时钟在显示段全关时不会跳,至少保证开机检查一次)。
9761
+ 当年完全缺失时任何日期都补抓(12/30 到 2/10 没开机的漏抓场景),
9762
+ 12/31 仍按原逻辑抓下一年;失败按年份各记一个时间戳,24 小时内不重试;
9763
+ 开发模式一律不发真实请求。 */
9764
+ const holidayAutoRef = react.useRef({ busy: false, failed: null });
9765
+ react.useEffect(() => {
9766
+ void autoUpdateHolidays(now, cfg.holidayDays, holidayAutoRef.current, devActive);
9767
+ }, [now, cfg.holidayDays, devActive]);
9768
+
7839
9769
  /* 价格库缺省或全 0 时自动补上官方参考价(不用用户手动填)。
7840
9770
  开发模式跳过:它内部会发一次真实 fetch(verify-dev-mode ⑦ 要求开发模式 0 次请求)。 */
7841
9771
  react.useEffect(() => {
@@ -7848,8 +9778,15 @@ window.__ModuleLoader__.load({
7848
9778
  这两个值变了要重新查,所以下面 effect 的依赖里带着它们。 */
7849
9779
  const balanceProvider = sessionModel !== undefined && sessionModel !== null ? sessionModel.provider : null;
7850
9780
  const balanceModel = sessionModel !== undefined && sessionModel !== null ? sessionModel.model : null;
9781
+ /* 当前模型归属的第三方平台(宽容匹配):有归属就在余额请求里带 `&relay=平台名`,
9782
+ 取不到归属就不加 —— Host 侧按 relay → provider → model 依次查档案。 */
9783
+ const balanceRelay = platformOfBook(cfg.models, cfg.relayPlatforms, balanceModel);
7851
9784
  const balanceQuery = "?provider=" + encodeURIComponent(String(balanceProvider === undefined || balanceProvider === null ? "" : balanceProvider))
7852
- + "&model=" + encodeURIComponent(String(balanceModel === undefined || balanceModel === null ? "" : balanceModel));
9785
+ + "&model=" + encodeURIComponent(String(balanceModel === undefined || balanceModel === null ? "" : balanceModel))
9786
+ + (balanceRelay === null ? "" : "&relay=" + encodeURIComponent(balanceRelay))
9787
+ /* 带上会话 id:Magpie 网关可用 /v1/magpie/route?session=<id> 精确到"这个会话用哪个账号"。
9788
+ 取不到 sessionId 时给空串,Host 会退回"最近一次实际服务的账号"。 */
9789
+ + "&session=" + encodeURIComponent(String(sessionId === undefined || sessionId === null ? "" : sessionId));
7853
9790
  /* 点开余额气泡时先强制重查一次:host 端余额不缓存,带上 force 就不用等
7854
9791
  下一次轮询(最多 60 秒),气泡里直接是此刻的数字。轮询本身不带 force。 */
7855
9792
  const balanceReloadRef = react.useRef(null);
@@ -7894,7 +9831,7 @@ window.__ModuleLoader__.load({
7894
9831
  /* 依赖里**必须带 devBalanceCount**:开发模式下余额来自 devFixture,而这个 effect 负责
7895
9832
  把它 setBalance 进去。只依赖 round 的话,点余额气泡时 round 不变 ⇒ effect 不重跑
7896
9833
  ⇒ setBalance 压根不执行 ⇒ 余额数字冻住(用户实测的"余额点开不变"就是这个)。 */
7897
- }, [wantsBalance, balanceProvider, balanceModel, devActive, devState.round, devBalanceCount]);
9834
+ }, [wantsBalance, balanceProvider, balanceModel, balanceRelay, devActive, devState.round, devBalanceCount]);
7898
9835
 
7899
9836
  /* 活跃总览(峰谷段的气泡):不轮询。挂载时取一次(走 host 缓存),
7900
9837
  之后每次点开气泡都带 force=1 —— force 只绕过 host 那 30 秒缓存;
@@ -8264,57 +10201,81 @@ window.__ModuleLoader__.load({
8264
10201
  ② 活跃总览的柱 / 方块 / 底板 —— 固定贴在气泡正上方、左右同宽。
8265
10202
  hoverMouse 由 onHover 记录;离开后由 closeHoverSoon 清空。 */
8266
10203
  useTipLayout(() => {
8267
- if (hoverCard === null && hoverPlain === null) return;
8268
- const node = hoverRef.current;
10204
+ const measureView = tipId === "counts" && tipSub === 2;
10205
+ const probe = measureView === true ? hoverMeasureRef.current : null;
10206
+ const measurePlain = hoverPlain !== null || (probe !== null && hoverCard === null);
10207
+ if (hoverCard === null && hoverPlain === null && probe === null) return;
10208
+ const plainNode = hoverPlain !== null ? hoverRef.current : null;
10209
+ const node = plainNode !== null && plainNode !== undefined
10210
+ ? plainNode
10211
+ : (measurePlain === true && probe !== null && probe !== undefined ? probe : hoverRef.current);
8269
10212
  const panel = tipRef.current;
8270
10213
  if (node === null || node === undefined || panel === null || panel === undefined) return;
8271
10214
  if (typeof node.getBoundingClientRect !== "function" || typeof panel.getBoundingClientRect !== "function") return;
8272
10215
  const size = node.getBoundingClientRect();
8273
- if (hoverPlain !== null) {
10216
+ if (measurePlain === true) {
8274
10217
  const one = hoverMouse;
8275
- if (one === null || one === undefined) return;
8276
- /* 标题行(.dsb-meter-head)的垂直中心:文字提示与它居中对齐 */
10218
+ if (hoverPlain !== null && (one === null || one === undefined)) return;
10219
+ /* 可用范围 = **气泡内部**(左右各留 8px):提示画在气泡里(用户实测跑到外面去了)。
10220
+ 气泡宽度就是可用宽度上限;整组「有名字放不下就全不显示」的判据见下面的 plainFits。 */
10221
+ const panelBox = panel.getBoundingClientRect();
8277
10222
  const head = typeof panel.querySelector === "function" ? panel.querySelector(".dsb-meter-head") : null;
8278
10223
  const headBox = head !== null && head !== undefined && typeof head.getBoundingClientRect === "function"
8279
10224
  ? head.getBoundingClientRect()
8280
10225
  : null;
8281
- const fixedTop = headBox === null || headBox.height <= 0
8282
- ? Math.max(8, node.getBoundingClientRect().top)
8283
- : headBox.top + headBox.height / 2 - size.height / 2;
8284
- hoverPlainTopRef.current = fixedTop;
8285
- /* 水平范围:左 = 标题右边界 + 1ch;右 = **色条本身**的右边界(不是气泡右边界) */
10226
+ /* 标题文字(「工具调用」那四个字)的右边界:悬停提示不能压到它 */
8286
10227
  const title = typeof panel.querySelector === "function" ? panel.querySelector(".dsb-meter-headline") : null;
8287
10228
  const titleBox = title !== null && title !== undefined && typeof title.getBoundingClientRect === "function"
8288
10229
  ? title.getBoundingClientRect()
8289
10230
  : null;
8290
- const bar = typeof panel.querySelector === "function" ? panel.querySelector(".dsb-bar") : null;
8291
- const barBox = bar !== null && bar !== undefined && typeof bar.getBoundingClientRect === "function"
8292
- ? bar.getBoundingClientRect()
8293
- : panel.getBoundingClientRect();
8294
- const bounds = plainBoundsOf(titleBox, barBox, window.innerWidth);
10231
+ const bounds = plainBoundsOf(titleBox, panelBox, window.innerWidth);
8295
10232
  hoverPlainBoundsRef.current = bounds;
8296
10233
  /* 提示文字的自然宽度。用 offsetWidth(布局宽度)而不是
8297
- getBoundingClientRect().width:后者含 transform,而这条 effect 的依赖里有
8298
- hoverMouse(鼠标一动就重跑),量到缩放后的宽会越缩越小。 */
8299
- const layoutWidth = typeof node.offsetWidth === "number" && node.offsetWidth > 0
8300
- ? node.offsetWidth
8301
- : size.width;
10234
+ getBoundingClientRect().width:后者含 transform,而这条 effect 的依赖里有
10235
+ hoverMouse(鼠标一动就重跑),量到缩放后的宽会越缩越小。 */
10236
+ const layoutWidth = plainNode !== null && plainNode !== undefined
10237
+ && typeof plainNode.offsetWidth === "number" && plainNode.offsetWidth > 0
10238
+ ? plainNode.offsetWidth
10239
+ : (hoverPlain !== null && size.width > 0 ? size.width : 0);
10240
+ /* 离屏探针里每个工具名的自然宽度取最大:最大的那个放得下,这一屏就都放得下 */
10241
+ let probeWidth = 0;
10242
+ const probeChildren = probe === null || probe === undefined ? null : probe.children;
10243
+ if (probeChildren !== null && probeChildren !== undefined && typeof probeChildren.length === "number") {
10244
+ for (let index = 0; index < probeChildren.length; index += 1) {
10245
+ const candidate = probeChildren[index];
10246
+ if (candidate === null || candidate === undefined) continue;
10247
+ const candidateWidth = typeof candidate.offsetWidth === "number" && candidate.offsetWidth > 0
10248
+ ? candidate.offsetWidth
10249
+ : (typeof candidate.getBoundingClientRect === "function" ? candidate.getBoundingClientRect().width : 0);
10250
+ if (candidateWidth > probeWidth) probeWidth = candidateWidth;
10251
+ }
10252
+ }
10253
+ const fitWidth = probeWidth > 0 ? probeWidth : layoutWidth;
8302
10254
  /* 放不下就**整组不显示**(用户拍板):工具名很长、气泡不够长时,
8303
- 这行小字会压到别的内容上或被裁掉。以前是等比缩小硬塞进去,
8304
- 现在改成关掉 —— 缩到 5.5px 本来就读不清,不如不显示。
8305
- 一旦这个气泡放不下,**所有**工具名的悬停提示都关(不是只关超长那个),
8306
- 否则只有一部分能弹,看起来更像故障。 */
8307
- if (plainFits(layoutWidth, bounds, window.innerWidth) !== true) {
10255
+ 这行小字会压到别的内容上或被裁掉。一旦这个气泡放不下,**所有**工具名的
10256
+ 悬停提示都关(不是只关超长那个),否则只有一部分能弹,看起来更像故障。
10257
+ 缩放硬塞的老路已经删掉 —— 缩到 5.5px 本来就读不清。 */
10258
+ if (plainFits(fitWidth, bounds, window.innerWidth) !== true) {
8308
10259
  if (hoverPlainOff !== true) setHoverPlainOff(true);
8309
10260
  /* 内容也当场清掉:不留半行字孤零零挂在屏幕上 */
8310
- setHoverPlain(null);
10261
+ if (hoverPlain !== null) setHoverPlain(null);
8311
10262
  setHoverPos(null);
8312
10263
  return;
8313
10264
  }
10265
+ /* 气泡变长 / 变宽后重新量出「放得下」⇒ 整组恢复(用户实测的 bug 就在这里) */
8314
10266
  if (hoverPlainOff === true) setHoverPlainOff(false);
10267
+ if (hoverPlain === null) return;
10268
+ if (plainNode === null || plainNode === undefined) return;
10269
+ const plainSize = plainNode.getBoundingClientRect();
10270
+ /* 垂直:与「工具调用」标题行**上下居中对齐**(同一行,用户要求) */
10271
+ const textHeight = plainSize.height > 0 ? plainSize.height : 15;
10272
+ const fixedTop = headBox === null || headBox.height <= 0
10273
+ ? Math.max(8, panelBox.top + HOVER_PLAIN_INSET)
10274
+ : Math.max(8, headBox.top + headBox.height / 2 - textHeight / 2);
10275
+ hoverPlainTopRef.current = fixedTop;
8315
10276
  setHoverPos({
8316
10277
  left: clampPlainLeft(one.x - layoutWidth / 2, layoutWidth, bounds, window.innerWidth),
8317
- top: Math.max(8, fixedTop)
10278
+ top: fixedTop
8318
10279
  });
8319
10280
  return;
8320
10281
  }
@@ -8327,7 +10288,21 @@ window.__ModuleLoader__.load({
8327
10288
  top: Math.max(8, box.top - size.height - 3),
8328
10289
  width: box.width
8329
10290
  });
8330
- }, [hoverCard, hoverPlain, hoverMouse]);
10291
+ }, [hoverCard, hoverPlain, hoverMouse, hoverPlainOff, tipTick, tipId, tipSub]);
10292
+
10293
+ /* 气泡尺寸一变就重测「那行小字放不放得下」(用户实测「完全不弹提示」的根因修复):
10294
+ 工具调用变多 → 气泡变长变宽 → 长工具名重新放得下时,整组悬停必须**自动恢复**。
10295
+ 以前只有 window resize 才 bump tipTick,气泡自己长高长宽没有任何信号,
10296
+ 于是一次「放不下」就把本次会话的悬停永久关死。
10297
+ ResizeObserver 拿不到(老环境 / 测试替身)就跳过,靠 resize 重测,行为不退化。 */
10298
+ react.useEffect(() => {
10299
+ if (typeof ResizeObserver !== "function") return undefined;
10300
+ const panel = tipRef.current;
10301
+ if (panel === null || panel === undefined) return undefined;
10302
+ const observer = new ResizeObserver(() => setTipTick((tick) => tick + 1));
10303
+ observer.observe(panel);
10304
+ return () => observer.disconnect();
10305
+ }, [tipId, tipSub]);
8331
10306
 
8332
10307
  /* 主气泡收起时顺手把悬停浮层也收掉,避免它孤零零留在屏幕上。
8333
10308
  `hoverPlainOff` 也必须在这里复位:它是「本气泡放不下所以整组不显示」的一次性结论,
@@ -8341,13 +10316,35 @@ window.__ModuleLoader__.load({
8341
10316
  }
8342
10317
  }, [tipId]);
8343
10318
 
8344
- /* 开关状态同步到 <html>:CSS 里那两条"藏官方底栏"的规则挂在 html.dsb-on 上。 */
10319
+ /* 开关状态同步到 <html>:CSS 里那两条"藏官方底栏"的规则挂在 html.dsb-on 上。
10320
+ 官方「活动 / 用量 / 上下文」节点会重新插回 dock 的嵌套层,光靠 CSS 的直系子节点规则藏不住:
10321
+ 从 .dsb-root 逐层向上到 dock,把同层非本插件节点按行内 display 藏掉,卸载时原样还原。 */
8345
10322
  react.useEffect(() => {
8346
10323
  if (typeof document === "undefined" || document === null) return undefined;
8347
10324
  const root = document.documentElement;
8348
10325
  if (root === null || root === undefined || root.classList === undefined) return undefined;
8349
10326
  root.classList.add("dsb-on");
8350
- return () => { root.classList.remove("dsb-on"); };
10327
+ const dock = document.querySelector('[data-slot="conversation.composer.dock"]');
10328
+ const barRoot = dock && dock.querySelector(".dsb-root");
10329
+ const hidden = [];
10330
+ if (dock && barRoot) {
10331
+ let node = barRoot;
10332
+ while (node && node !== dock) {
10333
+ const parent = node.parentElement;
10334
+ if (!parent) break;
10335
+ Array.from(parent.children).forEach((child) => {
10336
+ if (child !== node && !child.contains(barRoot) && child.style.display !== "none") {
10337
+ hidden.push([child, child.style.display]);
10338
+ child.style.display = "none";
10339
+ }
10340
+ });
10341
+ node = parent;
10342
+ }
10343
+ }
10344
+ return () => {
10345
+ root.classList.remove("dsb-on");
10346
+ hidden.forEach(([el, prev]) => { el.style.display = prev; });
10347
+ };
8351
10348
  }, []);
8352
10349
 
8353
10350
  /* 本轮费用:优先节点折叠(与官方同源),节点缺失才用差分兜底。
@@ -8586,6 +10583,7 @@ window.__ModuleLoader__.load({
8586
10583
  setTipSub(null);
8587
10584
  },
8588
10585
  rowsPerColumn: toolRows,
10586
+ hoverMeasureRef: hoverMeasureRef,
8589
10587
  /* 工具名悬停提示整组开关:这个气泡放不下那行小字时一律不挂(用户拍板) */
8590
10588
  hoverSuppressed: hoverPlainOff,
8591
10589
  /* 工具调用彩条每段的悬停浮层(工具名 + 占比)走同一套 onHover,与柱状图互不干扰;
@@ -8661,25 +10659,38 @@ window.__ModuleLoader__.load({
8661
10659
  const hoverStyle = hoverPos === null
8662
10660
  ? undefined
8663
10661
  : { left: hoverPos.left + "px", top: hoverPos.top + "px" };
8664
- children.push(h("span", {
10662
+ const hoverPlainNode = h("span", {
8665
10663
  className: "dsb-hover-plain",
8666
10664
  key: "__hoverplain",
8667
10665
  ref: hoverRef,
8668
10666
  style: hoverStyle
8669
- }, hoverPlain));
10667
+ }, hoverPlain);
10668
+ /* 必须 Portal 到 body:底栏处在宿主 composer dock 的 z-index:7 层叠上下文里,
10669
+ 而「工具调用」气泡是 body 级 z-index:105 —— 就地渲染的文字会被气泡整块盖住
10670
+ (用户实测「什么都不显示」就是这个原因)。拿不到 createPortal 时退回就地渲染。 */
10671
+ children.push(canPortal === true && typeof document !== "undefined" && document !== null
10672
+ && document.body !== undefined && document.body !== null
10673
+ ? reactDom.createPortal(hoverPlainNode, document.body)
10674
+ : hoverPlainNode);
8670
10675
  }
8671
10676
  /* 悬停浮层:与主气泡同一套质感,fixed 定位在触发元素上方。
8672
10677
  必须先挂上节点(此时 pos 还是 null、不给 left/bottom),
8673
10678
  layout effect 才量得到宽度并把坐标算出来 —— 否则会永远卡在"没有坐标"而不显示。 */
8674
10679
  if (hoverCard !== null) {
8675
- children.push(h("span", {
10680
+ const hoverCardNode = h("span", {
8676
10681
  className: "dsb-tip dsb-meter dsb-hovercard",
8677
10682
  key: "__hovercard",
8678
10683
  ref: hoverRef,
8679
10684
  style: hoverPos === null ? undefined : { left: hoverPos.left + "px", top: hoverPos.top + "px", width: hoverPos.width + "px" },
8680
10685
  onClick: stopTipClick,
8681
10686
  onMouseDown: stopTipClick
8682
- }, hoverCard));
10687
+ }, hoverCard);
10688
+ /* 必须 Portal 到 body:底栏处在宿主 composer dock 的包含块里(fixed 会被它捕获并裁掉),
10689
+ 与 hoverPlain / tipPanelOf 同一套兜底。 */
10690
+ children.push(canPortal === true && typeof document !== "undefined" && document !== null
10691
+ && document.body !== undefined && document.body !== null
10692
+ ? reactDom.createPortal(hoverCardNode, document.body)
10693
+ : hoverCardNode);
8683
10694
  }
8684
10695
  return h("span", {
8685
10696
  ref: rootRef,
@@ -8747,6 +10758,8 @@ window.__ModuleLoader__.load({
8747
10758
  进入后标题右侧挂一枚「开发模式」胶囊 —— 那是唯一的可见迹象。 */
8748
10759
  const devState = useDevState();
8749
10760
  const devOn = devState.on === true;
10761
+ /* 中转站余额查询状态(只存 tokenConfigured / userIdConfigured 布尔) */
10762
+ const relayState = useRelayState();
8750
10763
 
8751
10764
  /* 版本号被点击:累计连点次数,够 5 次就切换开发模式。
8752
10765
  计数与时间窗都在模块级(onVersionClick);
@@ -8768,14 +10781,96 @@ window.__ModuleLoader__.load({
8768
10781
  const [hostModel, setHostModel] = react.useState(null);
8769
10782
  const [editing, setEditing] = react.useState(null);
8770
10783
  const [draft, setDraft] = react.useState(null);
8771
- const [holidayBusy, setHolidayBusy] = react.useState(false);
8772
- const [holidayNote, setHolidayNote] = react.useState(null);
10784
+ /* catalogNotice 这个状态槽原来没人用(从未 set 过),这里复用成「自定义模型分组是否展开」:
10785
+ 不新增 useState 是为了保持 tools/shot.cjs 截图 presets 的 hook 下标不变(有测试盯着那张表)。
10786
+ true = 展开;addModel 自动置 true,用户手动开合时同步。 */
10787
+ const [catalogNotice, setCatalogNotice] = react.useState(false);
10788
+ /* platformModelOpen 状态槽:平台「适用模型」下拉展开行号。 */
10789
+ const [platformModelOpen, setPlatformModelOpen] = react.useState(null);
8773
10790
  const [currencyOpen, setCurrencyOpen] = react.useState(false);
10791
+ /* 第三方平台区块:平台名(编辑中)/ 草稿 / 校验提示 / 新平台名输入框。
10792
+ **必须排在 currencyOpen 之后**:tools/shot.cjs 的截图 presets 按下标注入,前 9 个下标不能挪 */
10793
+ const [platformEditing, setPlatformEditing] = react.useState(null);
10794
+ const [platformDraft, setPlatformDraft] = react.useState(null);
10795
+ const [platformNotice, setPlatformNotice] = react.useState(null);
10796
+ const [newPlatform, setNewPlatform] = react.useState("");
10797
+ /* 平台编辑气泡:空间不足时向上弹 */
10798
+ const [platformPopUp, setPlatformPopUp] = react.useState(false);
10799
+ /* 模型下拉:根级浮层的固定定位坐标(跟随锚点按钮滚动 / 缩放重算) */
10800
+ const [platformMenuSpec, setPlatformMenuSpec] = react.useState(null);
8774
10801
  const currencyRef = react.useRef(null);
8775
10802
  const editPopRef = react.useRef(null);
8776
10803
  /* 币种下拉的**菜单节点**(不是那个按钮):展开后要把它滚进视野 */
8777
10804
  const currencyMenuRef = react.useRef(null);
8778
-
10805
+ /* 平台编辑区节点:点「添加平台」/加模型行后把它的底边带进视野 */
10806
+ const platformEditRef = react.useRef(null);
10807
+ /* 当前展开平台行的头部节点:外部点击保存时,头部内的点击(保存/删除/平台名)不在此处重复处理 */
10808
+ const platformHeadRef = react.useRef(null);
10809
+ /* 平台「适用模型」下拉的菜单节点:用于外部点击判定 */
10810
+ const platformModelMenuRef = react.useRef(null);
10811
+ /* 模型下拉可用空间的底边:找最近的可滚祖先(与平台编辑气泡同一套口径) */
10812
+ const platformMenuBoundary = (anchor) => {
10813
+ const start = platformEditRef.current && platformEditRef.current.closest ? platformEditRef.current.closest(".dsb-settings") : null;
10814
+ let sc = start !== null && start !== undefined ? start : (anchor !== null && anchor !== undefined ? anchor.parentElement : null);
10815
+ let boundary = Math.min(window.innerHeight, document.documentElement.clientHeight);
10816
+ while (sc) {
10817
+ if (sc === document.body || sc === document.documentElement) { sc = sc.parentElement; continue; }
10818
+ const cs = getComputedStyle(sc);
10819
+ if ((cs.overflowY === "auto" || cs.overflowY === "scroll") && sc.scrollHeight > sc.clientHeight + 2) {
10820
+ boundary = Math.min(boundary, sc.getBoundingClientRect().bottom);
10821
+ break;
10822
+ }
10823
+ sc = sc.parentElement;
10824
+ }
10825
+ return boundary;
10826
+ };
10827
+ /* 模型下拉打开期间:滚动 / 缩放都让菜单跟着锚点按钮走(不关闭)。
10828
+ 依赖 platformModelOpen:关闭时(变回 null)本 effect 体把 anchor 置 null。 */
10829
+ react.useEffect(() => {
10830
+ if (platformModelOpen === null || platformMenuAnchor === null) {
10831
+ platformMenuAnchor = null;
10832
+ return undefined;
10833
+ }
10834
+ const anchor = platformMenuAnchor;
10835
+ const reposition = () => {
10836
+ if (anchor === null || anchor === undefined || typeof anchor.getBoundingClientRect !== "function") return;
10837
+ const rect = anchor.getBoundingClientRect();
10838
+ const boundary = platformMenuBoundary(anchor);
10839
+ setPlatformMenuSpec((spec) => {
10840
+ if (spec === null || spec === undefined) return spec;
10841
+ const menuHeight = spec.menuHeight === undefined ? 8 + Math.min(spec.items.length, 3) * 30 : spec.menuHeight;
10842
+ const need = menuHeight + 8;
10843
+ const menuUp = (boundary - rect.bottom) < need;
10844
+ const top = Math.max(4, menuUp ? rect.top - menuHeight - 4 : rect.bottom + 4);
10845
+ return { rowIndex: spec.rowIndex, left: rect.left, width: rect.width, up: top, menuHeight: menuHeight, items: spec.items };
10846
+ });
10847
+ };
10848
+ window.addEventListener("scroll", reposition, true);
10849
+ window.addEventListener("resize", reposition);
10850
+ return () => {
10851
+ window.removeEventListener("scroll", reposition, true);
10852
+ window.removeEventListener("resize", reposition);
10853
+ if (platformMenuAnchor === anchor) platformMenuAnchor = null;
10854
+ };
10855
+ }, [platformModelOpen]);
10856
+ /* 平台编辑气泡:绘制前按实际高度决定向上/向下弹 */
10857
+ react.useLayoutEffect(() => {
10858
+ if (platformEditing === null) return;
10859
+ const pop = platformEditRef.current;
10860
+ const head = platformHeadRef.current;
10861
+ if (pop === null || pop === undefined || head === null || head === undefined) return;
10862
+ const need = pop.getBoundingClientRect().height + 2;
10863
+ let boundary = window.innerHeight;
10864
+ let sc = head.parentElement;
10865
+ while (sc) {
10866
+ const cs = getComputedStyle(sc);
10867
+ if ((cs.overflowY === "auto" || cs.overflowY === "scroll") && sc.scrollHeight > sc.clientHeight + 2) { boundary = sc.getBoundingClientRect().bottom; break; }
10868
+ sc = sc.parentElement;
10869
+ }
10870
+ boundary = Math.min(boundary, window.innerHeight);
10871
+ const spaceBelow = boundary - head.getBoundingClientRect().bottom;
10872
+ setPlatformPopUp(spaceBelow < need);
10873
+ }, [platformEditing]);
8779
10874
  /* 设置页里会"向下展开"的浮层,统一走这一个钩子把底边带进视野。
8780
10875
  旧实现用浏览器自带的"滚进视野"接口(block:nearest),而 ① 浮层自身比可视区高时
8781
10876
  它只保证顶部对齐、底部永远进不来;② 设置面板外层是个可滚容器,滚 window 没用。
@@ -8810,11 +10905,14 @@ window.__ModuleLoader__.load({
8810
10905
  **依赖里带 draft.tiered**:勾选会撑高浮层,必须重算一次。
8811
10906
  CSS/字体度量可能让高度到下一帧才稳定,所以再用一帧复测补滚一次
8812
10907
  (rAF,不是定时器 —— 底栏的定时器数量有断言盯着)。 */
8813
- /* 价格编辑浮层:打开时、以及勾上「峰谷计价」把它撑高之后各滚一次 */
8814
- useRevealBottom(editPopRef, editing !== null, draft === null ? null : draft.tiered);
10908
+ /* 价格编辑浮层:打开时、切到另一张卡(含 addModel 新增)时、以及勾上「峰谷计价」把它撑高之后各滚一次 */
10909
+ useRevealBottom(editPopRef, editing !== null, draft === null ? null : String(draft.tiered === true) + "|" + String(editing));
8815
10910
  /* 币种下拉菜单(CNY/USD):展开后同样按底部溢出量滚进视野。
8816
10911
  用户实测反馈"还要手动滚一下"的就是它 —— 上一轮只接到了价格编辑浮层。 */
8817
10912
  useRevealBottom(currencyMenuRef, currencyOpen === true, null);
10913
+ /* 平台编辑区(行内展开):点「添加平台」后、以及加适用模型行后,把编辑区底边带进视野 */
10914
+ useRevealBottom(platformEditRef, platformEditing !== null,
10915
+ platformDraft === null ? null : String(platformEditing) + "|" + String(platformDraft.modelRows.length));
8818
10916
  /**
8819
10917
  * 币种下拉控件(**只在条目的编辑浮层里用一处**:与三个价格框同一处、无文字标签)。
8820
10918
  *
@@ -8826,6 +10924,12 @@ window.__ModuleLoader__.load({
8826
10924
  * (实测反馈:切一下币种,刚填的价格就被清空了)。
8827
10925
  */
8828
10926
  const currencySelect = (key, draftNow, open, setOpen, menuRef, boxRef) => {
10927
+ /* 菜单项被点后 React 会立刻卸载它:事件冒泡到 document 时 target 已脱离价格卡,
10928
+ 外层「点别处收起编辑区」会误判成点了外面(实测:选个币种就把气泡关了)。
10929
+ 这里把点击拦在组件内部,别让它冒到 document;点真正的外部仍会正常收起。 */
10930
+ const stop = (event) => {
10931
+ if (event !== null && event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
10932
+ };
8829
10933
  const value = normalizeCurrency(draftNow === null || draftNow === undefined ? cfg.currency : draftNow.currency);
8830
10934
  const pick = (code) => {
8831
10935
  setOpen(false);
@@ -8837,12 +10941,24 @@ window.__ModuleLoader__.load({
8837
10941
  return;
8838
10942
  }
8839
10943
  /* 整份重建会连用户没保存的输入一起丢掉 —— 这里只换币种标记,三个价格框的值保持不变 */
8840
- setDraft({
8841
- tiered: draftNow.tiered,
8842
- currency: normalizeCurrency(code),
8843
- peak: draftNow.peak,
8844
- offPeak: draftNow.offPeak
8845
- });
10944
+ /* 官方另一套价 / 按今日汇率换算后的数值:框里的数字必须跟着变,
10945
+ 同时保留中转站配置与用户还没提交的密文输入 */
10946
+ if (changed.converted === true) {
10947
+ const asText = (tier) => ({
10948
+ input: tier.input === null || tier.input === undefined ? "" : priceText(tier.input),
10949
+ cacheRead: tier.cacheRead === null || tier.cacheRead === undefined ? "" : priceText(tier.cacheRead),
10950
+ cacheWrite: tier.cacheWrite === null || tier.cacheWrite === undefined ? "" : priceText(tier.cacheWrite),
10951
+ output: tier.output === null || tier.output === undefined ? "" : priceText(tier.output)
10952
+ });
10953
+ setDraft(Object.assign({}, draftNow, {
10954
+ currency: normalizeCurrency(code),
10955
+ peak: asText(changed.entry.peak),
10956
+ offPeak: asText(changed.entry.offPeak)
10957
+ }));
10958
+ return;
10959
+ }
10960
+ /* 只换币种标记:草稿里其余字段(含中转站配置与未保存的输入)原样保留 */
10961
+ setDraft(Object.assign({}, draftNow, { currency: normalizeCurrency(code) }));
8846
10962
  };
8847
10963
  return h("div", { className: "dsb-select", key: key, ref: boxRef }, [
8848
10964
  h("button", {
@@ -8850,7 +10966,7 @@ window.__ModuleLoader__.load({
8850
10966
  className: "dsb-select-btn",
8851
10967
  "aria-haspopup": "listbox",
8852
10968
  "aria-expanded": open === true ? "true" : "false",
8853
- onClick: () => setOpen(open !== true)
10969
+ onClick: (event) => { stop(event); setOpen(open !== true); }
8854
10970
  }, value),
8855
10971
  open === true
8856
10972
  ? h("div", { className: "dsb-select-menu", role: "listbox", ref: menuRef },
@@ -8860,7 +10976,8 @@ window.__ModuleLoader__.load({
8860
10976
  role: "option",
8861
10977
  "aria-selected": value === code ? "true" : "false",
8862
10978
  className: value === code ? "dsb-select-item dsb-select-item-on" : "dsb-select-item",
8863
- onClick: () => pick(code)
10979
+ onClick: (event) => { stop(event); pick(code); },
10980
+ onMouseDown: stop
8864
10981
  }, code)))
8865
10982
  : null
8866
10983
  ]);
@@ -8868,7 +10985,12 @@ window.__ModuleLoader__.load({
8868
10985
 
8869
10986
  /* 编辑浮层:点别处收起并丢弃草稿。判断"里面"上三重保险 —— 浮层节点、价格卡节点,
8870
10987
  以及鼠标坐标是否落在卡片或币种下拉的矩形内。切币种时点在卡片内的控件上,
8871
- 无论 DOM 结构怎么变都不该把编辑区收掉。 */
10988
+ 无论 DOM 结构怎么变都不该把编辑区收掉。
10989
+ 这条只管**价格气泡**:平台编辑区改成行内展开后不遮挡任何东西,也就不该被顺手收掉。
10990
+ 更要紧的是实测缺陷:这个文档监听原先在平台编辑打开时也在挂,而命中范围只认
10991
+ `.dsb-model` / 浮层矩形 / 币种菜单 —— 用户看到编辑区没反应后再点一次「添加平台」,
10992
+ 这一击就落在"外面",把刚打开、还没落库的平台编辑 cancelPlatformEdit() 掉
10993
+ (名字输入框也已被清空),表现就是「加不出来」。 */
8872
10994
  react.useEffect(() => {
8873
10995
  if (editing === null) return undefined;
8874
10996
  const inside = (event) => {
@@ -8906,6 +11028,60 @@ window.__ModuleLoader__.load({
8906
11028
  return () => document.removeEventListener("click", onDocClick);
8907
11029
  }, [currencyOpen]);
8908
11030
 
11031
+ /* 平台「适用模型」下拉:点空白处收起;点在任意一行下拉容器内不处理(由行内按钮自己切换) */
11032
+ react.useEffect(() => {
11033
+ if (platformModelOpen === null) return undefined;
11034
+ const onDocClick = (event) => {
11035
+ const target = event.target;
11036
+ if (target !== null && target !== undefined && typeof target.closest === "function"
11037
+ && target.closest(".dsb-modelrow-select") !== null) return;
11038
+ if (platformModelMenuRef.current !== null && platformModelMenuRef.current !== undefined && typeof platformModelMenuRef.current.contains === "function" && platformModelMenuRef.current.contains(target)) return;
11039
+ setPlatformModelOpen(null);
11040
+ };
11041
+ document.addEventListener("click", onDocClick);
11042
+ return () => document.removeEventListener("click", onDocClick);
11043
+ }, [platformModelOpen]);
11044
+
11045
+ /* 平台编辑区:点当前编辑区外部 → 自动保存并收起(校验不过则 savePlatform 内部保留展开)。
11046
+ 头部(保存/删除/平台名)与编辑区内部不处理;点别的平台名会先保存当前行,再由该行 onClick 打开新行。
11047
+ 用 pointerdown 捕获阶段,早于行内按钮的 click,避免先收起再触发。 */
11048
+ react.useEffect(() => {
11049
+ if (platformEditing === null) return undefined;
11050
+ const onDocPointerDown = (event) => {
11051
+ const el = event.target;
11052
+ if (el !== null && el !== undefined && typeof el.closest === "function" && el.closest("input,textarea,select,button") !== null) return;
11053
+ const target = event.target;
11054
+ const head = platformHeadRef.current;
11055
+ if (head !== null && head !== undefined && typeof head.contains === "function" && head.contains(target)) return;
11056
+ const node = platformEditRef.current;
11057
+ if (node !== null && node !== undefined && typeof node.contains === "function" && node.contains(target)) return;
11058
+ if (platformModelMenuRef.current !== null && platformModelMenuRef.current !== undefined && typeof platformModelMenuRef.current.contains === "function" && platformModelMenuRef.current.contains(target)) return;
11059
+ savePlatform();
11060
+ };
11061
+ document.addEventListener("pointerdown", onDocPointerDown, true);
11062
+ return () => document.removeEventListener("pointerdown", onDocPointerDown, true);
11063
+ }, [platformEditing, platformDraft, cfg]);
11064
+ /* 厂商目录:点目录外收起所有展开的厂商分组(自定义组是受控的,另同步 catalogNotice=false) */
11065
+ react.useEffect(() => {
11066
+ if (typeof document === "undefined" || document === null || typeof document.addEventListener !== "function") return undefined;
11067
+ const onDocClick = (event) => {
11068
+ const target = event.target;
11069
+ if (target !== null && target !== undefined && typeof target.closest === "function"
11070
+ && target.closest(".dsb-price-catalog") !== null) return;
11071
+ if (typeof document.querySelectorAll === "function") {
11072
+ const opened = document.querySelectorAll(".dsb-catalog-vendor[open]");
11073
+ if (opened !== null && opened !== undefined && typeof opened.forEach === "function") {
11074
+ opened.forEach((node) => { if (node !== null && node !== undefined) node.open = false; });
11075
+ }
11076
+ }
11077
+ setCatalogNotice(false);
11078
+ };
11079
+ document.addEventListener("click", onDocClick);
11080
+ return () => {
11081
+ if (typeof document.removeEventListener === "function") document.removeEventListener("click", onDocClick);
11082
+ };
11083
+ }, []);
11084
+
8909
11085
  /* 当前会话模型:底栏在模型一变时就 POST 给 host(那个 effect 依赖 sessionModel),
8910
11086
  所以 host 的投影始终最新;设置页进来读一次就够,不需要轮询。
8911
11087
  **开发模式开着时一次真实请求都不发**(项目硬约束):这时底栏吃的是假数据,
@@ -8926,6 +11102,15 @@ window.__ModuleLoader__.load({
8926
11102
  return () => { alive = false; };
8927
11103
  }, [devOn]);
8928
11104
 
11105
+ /* 中转站余额查询状态:进设置页时 GET 一次(模块级缓存;只拿「已配置/未配置」布尔)。
11106
+ 开发模式一次真实请求都不发(与上面 active-model 那条同一条硬约束)。 */
11107
+ react.useEffect(() => {
11108
+ if (devOn === true) return undefined;
11109
+ void ensureRelayState();
11110
+ return undefined;
11111
+ }, [devOn]);
11112
+
11113
+
8929
11114
  /* ---- 价格库操作:先改草稿,点保存才写入配置 ---- */
8930
11115
  /* 顺序来自 modelOrder:新加的模型追加在末尾 */
8931
11116
  const modelOrder = Array.isArray(cfg.modelOrder) ? cfg.modelOrder : [];
@@ -8951,13 +11136,25 @@ window.__ModuleLoader__.load({
8951
11136
  modelOrder: (Array.isArray(cfg.modelOrder) ? cfg.modelOrder : Object.keys(cfg.models)).concat([name])
8952
11137
  });
8953
11138
  startEdit(name, next[name], true); /* 新加的模型直接展开待填:框留空,不预填 0 */
11139
+ /* 自定义模型分组必须是展开的:折叠时编辑浮层不可见,用户会以为没加上 */
11140
+ setCatalogNotice(true);
8954
11141
  }
11142
+ /** 删模型:从价格库与各平台的「适用模型」里同时摘掉(平台档案本身保留)。 */
8955
11143
  function removeModel(name) {
8956
11144
  const next = Object.assign({}, cfg.models);
8957
11145
  delete next[name];
11146
+ /* 平台档案整份保留,只把该模型从各平台的「适用模型」里摘掉(别把无关平台一起丢了) */
11147
+ const platforms = Object.assign({}, cfg.relayPlatforms);
11148
+ Object.keys(platforms).forEach((platformName) => {
11149
+ const platform = platforms[platformName];
11150
+ const listed = Array.isArray(platform.models) ? platform.models : [];
11151
+ const models = listed.filter((one) => sameModelName(one.model, name) !== true);
11152
+ if (models.length !== listed.length) platforms[platformName] = Object.assign({}, platform, { models: models });
11153
+ });
8958
11154
  setConfig({
8959
11155
  models: next,
8960
- modelOrder: (Array.isArray(cfg.modelOrder) ? cfg.modelOrder : Object.keys(cfg.models)).filter((x) => x !== name)
11156
+ modelOrder: (Array.isArray(cfg.modelOrder) ? cfg.modelOrder : Object.keys(cfg.models)).filter((x) => x !== name),
11157
+ relayPlatforms: platforms
8961
11158
  });
8962
11159
  if (editing === name) cancelEdit();
8963
11160
  }
@@ -8972,11 +11169,14 @@ window.__ModuleLoader__.load({
8972
11169
  const entry = normalizePrice(stored);
8973
11170
  const untouched = blank === true || isLegacyZeroEntry(stored);
8974
11171
  const asText = (tier) => ({
8975
- input: untouched === true || tier.input === null || tier.input === undefined ? "" : String(tier.input),
8976
- cacheRead: untouched === true || tier.cacheRead === null || tier.cacheRead === undefined ? "" : String(tier.cacheRead),
8977
- cacheWrite: untouched === true || tier.cacheWrite === null || tier.cacheWrite === undefined ? "" : String(tier.cacheWrite),
8978
- output: untouched === true || tier.output === null || tier.output === undefined ? "" : String(tier.output)
11172
+ input: untouched === true || tier.input === null || tier.input === undefined ? "" : priceText(tier.input),
11173
+ cacheRead: untouched === true || tier.cacheRead === null || tier.cacheRead === undefined ? "" : priceText(tier.cacheRead),
11174
+ cacheWrite: untouched === true || tier.cacheWrite === null || tier.cacheWrite === undefined ? "" : priceText(tier.cacheWrite),
11175
+ output: untouched === true || tier.output === null || tier.output === undefined ? "" : priceText(tier.output)
8979
11176
  });
11177
+ const multiplier = normalizeFeeMultiplier(stored === null || stored === undefined ? undefined : stored.feeMultiplier);
11178
+ /* 同一时间只开一个编辑区:开价格气泡就把平台编辑收起 */
11179
+ if (platformEditing !== null) cancelPlatformEdit();
8980
11180
  setDraft({
8981
11181
  tiered: isTiered(stored),
8982
11182
  /* 条目的币种也进草稿:它在浮层里与三个价格框并排可改(改哪条只动哪条) */
@@ -8984,7 +11184,10 @@ window.__ModuleLoader__.load({
8984
11184
  ? normalizeCurrency(stored.currency)
8985
11185
  : normalizeCurrency(cfg.currency),
8986
11186
  peak: asText(entry === null ? EMPTY_TIER : entry.peak),
8987
- offPeak: asText(entry === null ? EMPTY_TIER : entry.offPeak)
11187
+ offPeak: asText(entry === null ? EMPTY_TIER : entry.offPeak),
11188
+ /* 费用倍率由「第三方平台」区块按模型写入条目:这里只读出来留给保存时原样保留,
11189
+ 界面上不再让它可编辑(用户要求:倍率只在平台编辑里填)。 */
11190
+ feeMultiplier: multiplier === 1 ? "" : String(multiplier)
8988
11191
  });
8989
11192
  setEditing(name);
8990
11193
  }
@@ -8996,7 +11199,7 @@ window.__ModuleLoader__.load({
8996
11199
  function setDraftValue(tierKey, field, value) {
8997
11200
  setDraft((prev) => {
8998
11201
  if (prev === null) return prev;
8999
- const next = { tiered: prev.tiered, currency: prev.currency, peak: Object.assign({}, prev.peak), offPeak: Object.assign({}, prev.offPeak) };
11202
+ const next = Object.assign({}, prev, { peak: Object.assign({}, prev.peak), offPeak: Object.assign({}, prev.offPeak) });
9000
11203
  next[tierKey][field] = value;
9001
11204
  /* 勾了「峰谷计价」就按官方比例联动:填高峰 → 空闲 ÷2;填空闲 → 高峰 ×2,
9002
11205
  用户只需要填一档。没勾(全天同价)时两档没有关系,另一档不动。 */
@@ -9007,23 +11210,295 @@ window.__ModuleLoader__.load({
9007
11210
  return next;
9008
11211
  });
9009
11212
  }
9010
- function setDraftTiered(on) {
9011
- setDraft((prev) => {
11213
+ function setDraftTiered(on) {
11214
+ setDraft((prev) => {
11215
+ if (prev === null) return prev;
11216
+ if (prev.tiered === on) return prev;
11217
+ /* 切换「峰谷计价」**不丢数据**(用户实测:勾上再取消,价格全空)。
11218
+ 勾上:当前单档价搬到「低谷(offPeak)」行,高峰(peak)按现有联动规则 ×2 带出(用户可再改);
11219
+ 取消:低谷行的值搬回单档行(单档显示 / 计价都读 peak);offPeak 留在内部不影响计价。
11220
+ 两档都空时用条目基准价 `base` 回填(task-24:切币种不漂的那份锚点)。 */
11221
+ const asText = (tier) => ({
11222
+ input: tier.input === undefined || tier.input === null ? "" : priceText(tier.input),
11223
+ cacheRead: tier.cacheRead === undefined || tier.cacheRead === null ? "" : priceText(tier.cacheRead),
11224
+ cacheWrite: tier.cacheWrite === undefined || tier.cacheWrite === null ? "" : priceText(tier.cacheWrite),
11225
+ output: tier.output === undefined || tier.output === null ? "" : priceText(tier.output)
11226
+ });
11227
+ const blank = (tier) => {
11228
+ const one = asText(tier);
11229
+ return one.input === "" && one.cacheRead === "" && one.cacheWrite === "" && one.output === "";
11230
+ };
11231
+ const linkedUp = (tier) => ({
11232
+ input: priceText(linkedTierValue(tier.input, false)),
11233
+ cacheRead: priceText(linkedTierValue(tier.cacheRead, false)),
11234
+ cacheWrite: priceText(tier.cacheWrite),
11235
+ output: priceText(linkedTierValue(tier.output, false))
11236
+ });
11237
+ const stored = editing === null || config.models === undefined || config.models === null ? null : config.models[editing];
11238
+ const base = stored === null || stored === undefined ? null : baseOf(stored, prev.currency);
11239
+ const baseUsable = base !== null && base.currency === normalizeCurrency(prev.currency);
11240
+ if (on === true) {
11241
+ /* 两档都空(新模型或用户清过)→ 用 base 回填;base 是峰谷存档时两档一起还原 */
11242
+ if (blank(prev.peak) && blank(prev.offPeak) && baseUsable === true) {
11243
+ const baseTiered = stored !== null && stored !== undefined && stored.tiered !== false;
11244
+ if (baseTiered === true) return Object.assign({}, prev, { tiered: true, peak: asText(base.peak), offPeak: asText(base.offPeak) });
11245
+ const single = asText(base.peak);
11246
+ if (blank(single) !== true) return Object.assign({}, prev, { tiered: true, peak: linkedUp(single), offPeak: single });
11247
+ }
11248
+ /* 单档价先搬到「低谷」行,高峰再按现有联动规则 ×2 带出(两档都不清空,用户可再改) */
11249
+ let single = prev.peak;
11250
+ if (blank(single) === true && blank(prev.offPeak) === false) single = prev.offPeak;
11251
+ if (blank(single) !== true) {
11252
+ const offPeak = single;
11253
+ return Object.assign({}, prev, { tiered: true, peak: linkedUp(offPeak), offPeak: offPeak });
11254
+ }
11255
+ /* 两档都空:保持空(不造数) */
11256
+ return Object.assign({}, prev, { tiered: true });
11257
+ }
11258
+ /* 取消:低谷行的值搬回单档行(计价只用 peak 这一行) */
11259
+ let peak = blank(prev.offPeak) === false ? prev.offPeak : prev.peak;
11260
+ if (blank(peak) === true && baseUsable === true) peak = asText(base.peak);
11261
+ return Object.assign({}, prev, { tiered: false, peak: peak });
11262
+ });
11263
+ }
11264
+ /* ---- 第三方平台档案:平台列表 / 编辑 / 保存 / 删除(费用倍率与余额查询都挂在这里) ---- */
11265
+ const platformNames = Object.keys(cfg.relayPlatforms === undefined || cfg.relayPlatforms === null ? {} : cfg.relayPlatforms);
11266
+ /* 平台编辑的六个输入:按 Enter 后立即失焦,不残留输入光标 */
11267
+ const blurOnEnter = (event) => {
11268
+ if (event === null || event === undefined || event.key !== "Enter") return;
11269
+ if (typeof event.preventDefault === "function") event.preventDefault();
11270
+ if (event.target !== null && event.target !== undefined && typeof event.target.blur === "function") event.target.blur();
11271
+ };
11272
+ /* 适用模型按钮:先按 13px 排满,只有实际超宽才按 0.5px 递减(最低 10px);重渲染从 13px 重测 */
11273
+ const fitModelSelectLabel = (button) => {
11274
+ if (button === null || button === undefined || button.style === undefined) return;
11275
+ button.style.fontSize = "13px";
11276
+ let size = 13;
11277
+ while (size > 10 && button.scrollWidth > button.clientWidth) {
11278
+ size -= 0.5;
11279
+ button.style.fontSize = size + "px";
11280
+ }
11281
+ };
11282
+ const platformOf = (name) => normalizePlatform((cfg.relayPlatforms === undefined || cfg.relayPlatforms === null ? {} : cfg.relayPlatforms)[name]);
11283
+ /** 打开平台编辑:优先回显宿主已保存的真实值(含密文令牌 / 用户 ID);无快照时回退平台档案。 */
11284
+ function startPlatform(name) {
11285
+ cancelEdit();
11286
+ const platform = platformOf(name);
11287
+ const saved = relayState.models === null || relayState.models === undefined
11288
+ ? null
11289
+ : (relayState.models[name] === undefined ? null : relayState.models[name]);
11290
+ setPlatformDraft({
11291
+ userIdHeader: saved !== null && typeof saved.userIdHeader === "string" && saved.userIdHeader.length > 0
11292
+ ? saved.userIdHeader
11293
+ : (platform === null ? "" : platform.userIdHeader),
11294
+ endpoint: saved !== null && typeof saved.endpoint === "string" && saved.endpoint.length > 0
11295
+ ? saved.endpoint
11296
+ : (platform === null ? "" : platform.endpoint),
11297
+ balanceField: saved !== null && typeof saved.balancePath === "string" && saved.balancePath.length > 0
11298
+ ? balanceFieldText({ balancePath: saved.balancePath, balanceDivisor: saved.balanceDivisor, currency: saved.currency })
11299
+ : (platform === null ? "" : balanceFieldText(platform)),
11300
+ token: saved !== null && typeof saved.token === "string" ? saved.token : "",
11301
+ userId: saved !== null && typeof saved.userId === "string" ? saved.userId : "",
11302
+ /* 适用模型 = 价格库下拉行;档案里有几行就回填几行,
11303
+ **永远至少一行**(新建 / 已存档案模型为空都补一行空白,用户要求固定常驻) */
11304
+ modelRows: (platform === null || platform.models.length === 0)
11305
+ ? [{ model: "", fee: "" }]
11306
+ : platform.models.map((one) => ({
11307
+ model: one.model,
11308
+ fee: one.feeMultiplier === 1
11309
+ ? (one.feeConfigured === true ? "1" : "")
11310
+ : String(one.feeMultiplier)
11311
+ }))
11312
+ });
11313
+ setPlatformEditing(name);
11314
+ setPlatformNotice(null);
11315
+ setPlatformModelOpen(null);
11316
+ }
11317
+ /** 新平台:名称只做「非空白 + 不重名」两项校验(数字/英文/符号都允许);**添加即落库**再进编辑。 */
11318
+ function addPlatform() {
11319
+ const name = newPlatform.trim();
11320
+ if (name.length === 0) {
11321
+ setPlatformNotice(null);
11322
+ return;
11323
+ }
11324
+ if (platformNames.indexOf(name) !== -1 || name === platformEditing) {
11325
+ setPlatformNotice(t("platformNameDuplicate"));
11326
+ return;
11327
+ }
11328
+ setNewPlatform("");
11329
+ /* 空平台也立刻写进 config:用户实测「什么都没填,点别处关掉就没了」——
11330
+ 档案必须在添加那一刻就存在,后续编辑只是补充字段。 */
11331
+ const platforms = Object.assign({}, cfg.relayPlatforms);
11332
+ platforms[name] = normalizePlatform({});
11333
+ setConfig({ relayPlatforms: platforms });
11334
+ }
11335
+ function cancelPlatformEdit() {
11336
+ setPlatformEditing(null);
11337
+ setPlatformDraft(null);
11338
+ setPlatformNotice(null);
11339
+ setPlatformModelOpen(null);
11340
+ setPlatformPopUp(false);
11341
+ }
11342
+ function setPlatformField(key, value) {
11343
+ setPlatformDraft((prev) => (prev === null ? prev : Object.assign({}, prev, { [key]: value })));
11344
+ }
11345
+ /** 适用模型下拉行:增行 / 改行 / 删行(行索引只在本次草稿里有效) */
11346
+ function addPlatformModelRow() {
11347
+ setPlatformModelOpen(null);
11348
+ setPlatformDraft((prev) => (prev === null ? prev : Object.assign({}, prev, {
11349
+ modelRows: (Array.isArray(prev.modelRows) ? prev.modelRows : []).concat([{ model: "", fee: "" }])
11350
+ })));
11351
+ }
11352
+ function setPlatformModelRow(index, patch) {
11353
+ setPlatformDraft((prev) => {
11354
+ if (prev === null) return prev;
11355
+ const rows = Array.isArray(prev.modelRows) ? prev.modelRows : [];
11356
+ if (rows[index] === undefined) return prev;
11357
+ return Object.assign({}, prev, {
11358
+ modelRows: rows.map((one, at) => (at === index ? Object.assign({}, one, patch) : one))
11359
+ });
11360
+ });
11361
+ }
11362
+ function removePlatformModelRow(index) {
11363
+ setPlatformModelOpen(null);
11364
+ setPlatformDraft((prev) => {
9012
11365
  if (prev === null) return prev;
9013
- if (prev.tiered === on) return prev;
9014
- /* **只在勾上时清空**(用户要求:"勾选后全部留空、等重新填")。
9015
- 为什么取消勾选不清:单档显示与计价用的就是 `peak` 那一行 —— 取消勾选是
9016
- `peak → peak`,同一行、不存在串档;会串档的只有"单档 → 高峰行"这一次,
9017
- 而勾上时清空已经把它挡住了。双向清空会把用户**没动过**的数据静默抹掉
9018
- (实测:`peak.cacheWrite` 从 0 变 null、`peak.output` 从 8 变空),
9019
- 那是用户可见的数据丢失,代价远大于"切换模式要重填"的收益。
9020
- `cacheWrite` 连勾上时也不清:界面从来不渲染这一格(历史遗留字段),
9021
- 清掉等于改用户看不到的数据。 */
9022
- const cleared = (tier) => (on === true
9023
- ? { input: "", cacheRead: "", output: "", cacheWrite: tier.cacheWrite }
9024
- : tier);
9025
- return { tiered: on, currency: prev.currency, peak: cleared(prev.peak), offPeak: cleared(prev.offPeak) };
11366
+ const rows = Array.isArray(prev.modelRows) ? prev.modelRows : [];
11367
+ return Object.assign({}, prev, { modelRows: rows.filter((one, at) => at !== index) });
11368
+ });
11369
+ }
11370
+ /** 平台保存:写 config → 按适用模型行把倍率写进价格条目 → 同步宿主余额查询配置(直接保存、不校验不拦截)。 */
11371
+ function savePlatform() {
11372
+ if (platformEditing === null || platformDraft === null) return;
11373
+ const name = platformEditing;
11374
+ const draftNow = platformDraft;
11375
+ const oldPlatform = platformOf(name);
11376
+ const endpoint = typeof draftNow.endpoint === "string" ? draftNow.endpoint.trim() : "";
11377
+ const endpointValid = endpoint.length > 0 && /^https?:\/\//i.test(endpoint);
11378
+ let noticeKey = null;
11379
+ if (endpoint.length > 0 && endpointValid !== true) noticeKey = noticeKey || "priceEndpointInvalid";
11380
+ let balance = {};
11381
+ if (typeof draftNow.balanceField === "string" && draftNow.balanceField.trim().length > 0) {
11382
+ const parsed = parseBalanceField(draftNow.balanceField);
11383
+ if (parsed !== null) balance = parsed;
11384
+ else noticeKey = noticeKey || "priceBalanceFieldInvalid";
11385
+ }
11386
+ /* 适用模型自由行:空行忽略、同名宽容去重(先出现的行说了算)、留空倍率按 1;
11387
+ 填了就必须 >0 且 ≤1000,非法时记住是哪一行 */
11388
+ const typed = [];
11389
+ const draftRows = Array.isArray(draftNow.modelRows) ? draftNow.modelRows : [];
11390
+ draftRows.forEach((one) => {
11391
+ const modelName = typeof one.model === "string" ? one.model.trim() : "";
11392
+ if (modelName.length === 0) return;
11393
+ const raw = typeof one.fee === "string" ? one.fee.trim() : one.fee;
11394
+ let fee = 1;
11395
+ let feeConfigured = false;
11396
+ if (raw !== "" && raw !== null && raw !== undefined) {
11397
+ feeConfigured = true;
11398
+ fee = Number(raw);
11399
+ if (Number.isFinite(fee) !== true || fee <= 0 || fee > 1000) { fee = 1; noticeKey = noticeKey || "priceFeeMultiplierInvalid"; }
11400
+ }
11401
+ if (typed.some((entry) => sameModelName(entry[0], modelName) === true)) return;
11402
+ typed.push([modelName, fee, feeConfigured]);
11403
+ });
11404
+ /* 语法 errors 只用于字段定位,不再阻止保存(功能校验:能否查到余额才算通过) */
11405
+ /* 能对上价格条目的写条目键(宽容同名);对不上也允许保存 —— 只作为平台记录、不参与计费 */
11406
+ const bookKeys = Object.keys(cfg.models);
11407
+ const picked = typed.map((entry) => {
11408
+ if (cfg.models[entry[0]] !== undefined) return entry;
11409
+ const hit = bookKeys.filter((key) => sameModelName(key, entry[0]) === true)[0];
11410
+ return [hit === undefined ? entry[0] : hit, entry[1], entry[2]];
11411
+ });
11412
+ /* 地址非法就只存空地址(不报错不拦截),其它字段照常保存 */
11413
+ const endpointOk = endpointValid ? endpoint : "";
11414
+ const platform = normalizePlatform({
11415
+ endpoint: endpointOk,
11416
+ userIdHeader: draftNow.userIdHeader,
11417
+ /* 没填就存空(normalizePlatform 不再塞默认值);默认值只在向宿主 POST 时补 */
11418
+ balancePath: balance.balancePath,
11419
+ currency: balance.currency,
11420
+ balanceDivisor: balance.balanceDivisor,
11421
+ models: picked.map((one) => Object.assign({ model: one[0], feeMultiplier: one[1] },
11422
+ one[1] === 1 && one[2] === true ? { feeConfigured: true } : {}))
11423
+ }) || normalizePlatform({});
11424
+ const platforms = Object.assign({}, cfg.relayPlatforms);
11425
+ platforms[name] = platform;
11426
+ /* 价格条目:勾选的写倍率(=1 清字段);原先属于本平台、这次取消勾选的清掉倍率 */
11427
+ const next = Object.assign({}, cfg.models);
11428
+ const putFee = (modelName, fee, feeConfigured) => {
11429
+ if (next[modelName] === undefined) return;
11430
+ const entry = Object.assign({}, next[modelName]);
11431
+ if (feeConfigured === true) {
11432
+ entry.feeConfigured = true;
11433
+ entry.feeMultiplier = fee;
11434
+ } else {
11435
+ delete entry.feeMultiplier;
11436
+ delete entry.feeConfigured;
11437
+ }
11438
+ next[modelName] = entry;
11439
+ };
11440
+ picked.forEach((one) => putFee(one[0], one[1], one[2]));
11441
+ (oldPlatform === null ? [] : oldPlatform.models).forEach((one) => {
11442
+ if (picked.some((entry) => sameModelName(entry[0], one.model) === true)) return;
11443
+ putFee(one.model, 1, false);
9026
11444
  });
11445
+ setConfig({ models: next, relayPlatforms: platforms });
11446
+ const secretToken = typeof draftNow.token === "string" ? draftNow.token : "";
11447
+ const secretUserId = typeof draftNow.userId === "string" ? draftNow.userId : "";
11448
+ /* 同步宿主:地址合法且非空 → 保存余额查询配置;否则旧平台有地址 → 移除旧配置。
11449
+ feeMultiplier 固定 1:计费倍率已随价格库上报,避免 Host 二次相乘。 */
11450
+ const relayFailure = (data) => {
11451
+ const reason = data !== null && data !== undefined && typeof data.reason === "string" ? data.reason : "failed";
11452
+ setPlatformNotice(t("priceRelaySyncFailed", { reason: reason }));
11453
+ };
11454
+ if (endpointValid === true) {
11455
+ const payload = {
11456
+ channelKey: name,
11457
+ feeMultiplier: 1,
11458
+ endpoint: platform.endpoint,
11459
+ tokenHeader: platform.tokenHeader,
11460
+ tokenPrefix: "Bearer ",
11461
+ /* 档案里空 = 用户没填,但**运行时就按默认值跑**(用户确认的口径):
11462
+ 请求头 New-Api-User、余额字段 ¥data.quota / 500000(CNY,除数 500000)。
11463
+ 默认值只在这里补,不写回档案 —— 再打开编辑仍是空的。 */
11464
+ userIdHeader: platform.userIdHeader.length > 0 ? platform.userIdHeader : "New-Api-User",
11465
+ balancePath: platform.balancePath.length > 0 ? platform.balancePath : "data.quota",
11466
+ currency: platform.currency.length > 0 ? platform.currency : "CNY",
11467
+ balanceDivisor: platform.balanceDivisor === null ? 500000 : platform.balanceDivisor
11468
+ };
11469
+ /* 密文只在本次输入时带上:空 = 保留宿主原值(提交后本地不保留) */
11470
+ if (secretToken.length > 0) payload.token = secretToken;
11471
+ if (secretUserId.length > 0) payload.userId = secretUserId;
11472
+ postRelayState(payload).then((data) => {
11473
+ if (data === null || data === undefined || data.ok !== true) relayFailure(data);
11474
+ }).catch(() => { relayFailure(null); });
11475
+ } else if (oldPlatform !== null && oldPlatform.endpoint.length > 0) {
11476
+ postRelayState({ remove: true, channelKey: name }).then((data) => {
11477
+ if (data === null || data === undefined || data.ok !== true) relayFailure(data);
11478
+ }).catch(() => { relayFailure(null); });
11479
+ }
11480
+ cancelPlatformEdit();
11481
+ if (noticeKey !== null) setPlatformNotice(t(noticeKey));
11482
+ return;
11483
+ }
11484
+ /** 删平台:档案与对应条目的倍率一起清掉,宿主侧的余额查询配置也移除。 */
11485
+ function removePlatform(name) {
11486
+ const platforms = Object.assign({}, cfg.relayPlatforms);
11487
+ const oldPlatform = platformOf(name);
11488
+ delete platforms[name];
11489
+ const next = Object.assign({}, cfg.models);
11490
+ (oldPlatform === null ? [] : oldPlatform.models).forEach((one) => {
11491
+ if (next[one.model] === undefined) return;
11492
+ const entry = Object.assign({}, next[one.model]);
11493
+ delete entry.feeMultiplier;
11494
+ delete entry.feeConfigured;
11495
+ next[one.model] = entry;
11496
+ });
11497
+ setConfig({ models: next, relayPlatforms: platforms });
11498
+ if (platformEditing === name) cancelPlatformEdit();
11499
+ if (oldPlatform !== null && oldPlatform.endpoint.length > 0) {
11500
+ postRelayState({ remove: true, channelKey: name }).catch(() => { /* 移除失败不影响本地删除 */ });
11501
+ }
9027
11502
  }
9028
11503
  function saveDraft() {
9029
11504
  if (editing === null || draft === null) return;
@@ -9050,8 +11525,9 @@ window.__ModuleLoader__.load({
9050
11525
  真要取消添加,用卡片上的「删除」。 */
9051
11526
  const hasValue = (tier) => tier.input !== null || tier.cacheRead !== null
9052
11527
  || tier.cacheWrite !== null || tier.output !== null;
11528
+ const modelName = editing;
9053
11529
  const next = Object.assign({}, cfg.models);
9054
- next[editing] = {
11530
+ const entry = {
9055
11531
  tiered: draft.tiered === true,
9056
11532
  /* 条目自己的币种:界面上的换法见 currencySelect 那处(换完按新币种重建草稿) */
9057
11533
  currency: normalizeCurrency(draft.currency),
@@ -9059,6 +11535,19 @@ window.__ModuleLoader__.load({
9059
11535
  /* 两档都照实存:计价用哪一档看 tiered,取消勾选不该把空闲价抹掉 */
9060
11536
  offPeak: offPeak
9061
11537
  };
11538
+ /* 费用倍率由「第三方平台」区块驱动:保存价格时原样保留,界面上不再让它可编辑 */
11539
+ const oldEntry = cfg.models[modelName];
11540
+ const feeConfigured = oldEntry !== null && oldEntry !== undefined && oldEntry.feeConfigured === true;
11541
+ const feeMultiplier = normalizeFeeMultiplier(oldEntry === null || oldEntry === undefined ? undefined : oldEntry.feeMultiplier);
11542
+ if (feeConfigured === true) { entry.feeConfigured = true; entry.feeMultiplier = feeMultiplier; }
11543
+ else if (feeMultiplier !== 1) entry.feeMultiplier = feeMultiplier;
11544
+ /* 基准价 = 本次保存的数值 + 当前币种:下次切币种以它为锚,来回切不漂 */
11545
+ entry.base = {
11546
+ currency: normalizeCurrency(draft.currency),
11547
+ peak: peak,
11548
+ offPeak: offPeak
11549
+ };
11550
+ next[modelName] = entry;
9062
11551
  /* 只有真填了数字才算"配置过价格":一条全空的条目不该把"请填写价格"的提示顶掉 */
9063
11552
  if (hasValue(peak) === true || hasValue(offPeak) === true) {
9064
11553
  setConfig({ models: next, priceConfigured: true });
@@ -9245,6 +11734,9 @@ window.__ModuleLoader__.load({
9245
11734
  };
9246
11735
  }, [drag === null]);
9247
11736
 
11737
+ /* ---- 价格目录厂商顺序(固定顺序,不再支持拖拽排序) ---- */
11738
+ const catalogOrder = normalizeCatalogOrder(cfg.catalogOrder);
11739
+
9248
11740
  const contextRow = h("div", {
9249
11741
  className: "dsb-row",
9250
11742
  key: "__context",
@@ -9282,7 +11774,6 @@ window.__ModuleLoader__.load({
9282
11774
  ),
9283
11775
  h("span", {
9284
11776
  className: on === true ? "dsb-handle" : "dsb-handle dsb-handle-off",
9285
- title: on === true ? t("dragHint") : "",
9286
11777
  key: "__handle"
9287
11778
  })
9288
11779
  ];
@@ -9355,63 +11846,27 @@ window.__ModuleLoader__.load({
9355
11846
  priceCards.push(h("div", { className: "dsb-hint", key: "__pricehint" }, t("secPricesHint")));
9356
11847
  /* 价格区顶部**没有**全局币种选择器(用户明确要求去掉那个残留):
9357
11848
  币种只在每个条目的编辑浮层里选,改哪条只动哪条。 */
9358
- /* 「更新节假峰谷」+ 它的状态提示:按钮右边只在点过之后出现状态 ——
9359
- 搜索中 / 已写入概况,平时不占位。抓取失败的原因挪到按钮的悬停提示里 */
9360
- const holidayStatus = holidaySummary(Date.now());
9361
- /* 抓取「下一年」的安排有两种收场:
9362
- ① 官方还没发布(not-found / parse-empty)—— 不算出错,照常显示已写入的本年数量;
9363
- ② 真出问题(后台旧版没这个路由、或 HTTP 报错)—— 把原因显示出来,别让人以为写成功了。 */
9364
- const holidayQuiet = holidayNote !== null && holidayNote.ok !== true
9365
- && (holidayNote.reason === "not-found" || holidayNote.reason === "parse-empty");
9366
- const holidayFailure = holidayNote === null || holidayNote.ok === true || holidayQuiet
9367
- ? null
9368
- : (holidayNote.reason === "no-route"
9369
- ? t("holidayUpdateNoRoute")
9370
- : t("holidayUpdateFail", { reason: holidayNote.reason }));
9371
- /* 状态提示排在按钮**前面**:它出现或变长时按钮的右边界不动(按钮钉在卡右端)。
9372
- 按钮不挂 title —— 悬停不弹气泡,失败原因直接写进左边那句状态里。 */
9373
- const holidayActions = [];
9374
- if (holidayBusy === true || holidayNote !== null) {
9375
- holidayActions.push(h("span", { className: "dsb-hint", key: "__holidaystatus" },
9376
- holidayBusy === true
9377
- ? t("holidayUpdateBusy")
9378
- : (holidayFailure === null
9379
- ? t("holidayUpdateOk", { year: holidayStatus.year, count: holidayStatus.count })
9380
- : holidayFailure)));
9381
- }
9382
- holidayActions.push(h("button", {
9383
- type: "button",
9384
- className: "dsb-action",
9385
- key: "__holiday",
9386
- disabled: holidayBusy === true,
9387
- onClick: () => {
9388
- const year = nextHolidayYear(Date.now());
9389
- setHolidayBusy(true);
9390
- setHolidayNote(null);
9391
- updateHolidays(year).then((result) => {
9392
- setHolidayBusy(false);
9393
- setHolidayNote(result);
9394
- });
9395
- }
9396
- }, t("holidayUpdate")));
11849
+ /* 节假峰谷改为自动更新(StatusBar 的时钟 effect 调用 shouldAutoUpdateHolidays),
11850
+ 设置页不再有「更新节假峰谷」按钮与状态文案。 */
9397
11851
  /* "当前会话使用"提示:设置页是否能拿到投影由宿主决定,拿不到就显示占位 */
9398
11852
  const settingsModel = typeof props.useProjection === "function" ? props.useProjection("desktopStatusbarModel") : undefined;
9399
11853
  const currentModelName = settingsModel !== null && settingsModel !== undefined && typeof settingsModel.model === "string"
9400
11854
  ? settingsModel.model
9401
11855
  : null;
9402
11856
  const shownModel = currentModelName !== null ? currentModelName : hostModel;
11857
+ /* 只显示模型名:去掉第三方平台前缀(Remote-Magpie/group/deepseek-Flash → DeepSeek-Flash) */
11858
+ const shownModelName = shownModel === null ? null : shownModel.slice(shownModel.lastIndexOf("/") + 1);
9403
11859
  priceCards.push(h("div", { className: "dsb-current", key: "__current" }, [
9404
11860
  h("span", { key: "__currentname" }, [
9405
11861
  t("priceCurrent") + " ",
9406
- h("b", null, shownModel === null ? t("modelUnknown") : displayModelName(shownModel))
9407
- ]),
9408
- /* 「更新节假峰谷」贴这一行的右端(与下面的添加/修改按钮同一条右边界);
9409
- 状态提示排在按钮左边,免得把按钮从右边界挤开 */
9410
- h("span", { className: "dsb-current-act", key: "__currentact" }, holidayActions)
11862
+ h("b", null, shownModelName === null ? t("modelUnknown") : displayModelName(shownModelName))
11863
+ ])
9411
11864
  ]));
9412
11865
  if (cfg.priceConfigured !== true) {
9413
11866
  priceCards.push(h("div", { className: "dsb-hint", key: "__pricesuggest" }, t("priceSuggestedHint")));
9414
11867
  }
11868
+ /* 复用 catalogNotice 状态槽:true = 「自定义模型」分组展开(见组件顶部的说明) */
11869
+ const customModelsOpen = catalogNotice === true;
9415
11870
  /* 新增模型:夹在说明与模型列表之间 */
9416
11871
  priceCards.push(h("div", { className: "dsb-addrow", key: "__add" },
9417
11872
  h("input", {
@@ -9426,7 +11881,13 @@ window.__ModuleLoader__.load({
9426
11881
  if (modelNames.length === 0) {
9427
11882
  priceCards.push(h("div", { className: "dsb-hint", key: "__empty" }, t("priceEmpty")));
9428
11883
  }
9429
- const modelRows = [];
11884
+ /* 第三方平台字段行:左侧标签固定宽度、右侧输入框占满(样式见 .dsb-relay-line)。
11885
+ 价格气泡里**不再有**这些字段(用户要求全部挪到下方独立的「第三方平台」区块)。 */
11886
+ const relayLine = (label, key, input) => h("div", { className: "dsb-relay-line", key: key }, [
11887
+ h("span", { key: "__label" }, label),
11888
+ input
11889
+ ]);
11890
+ const modelRows = {};
9430
11891
  modelNames.forEach((name) => {
9431
11892
  const open = editing === name && draft !== null;
9432
11893
  const priceField = (tierKey, label, field) => h("label", { className: "dsb-field", key: tierKey + field },
@@ -9468,36 +11929,256 @@ window.__ModuleLoader__.load({
9468
11929
  const body = open === true
9469
11930
  ? h("div", { className: "dsb-edit-pop", key: "__edit", ref: editPopRef }, [
9470
11931
  /* 这一行左边是「峰谷计价」勾选,右边挂**本条目的**币种下拉:
9471
- 改哪条只动哪条(换算也只换算这一条的数值),与三个价格框同一处。 */
9472
- h("div", { className: "dsb-tier-head", key: "__tiered" },
9473
- h("label", { className: "dsb-inline-check" },
9474
- h("input", {
9475
- type: "checkbox",
9476
- checked: draft.tiered === true,
9477
- onChange: (event) => setDraftTiered(event.target.checked)
9478
- }),
9479
- h("span", null, t("priceTiered"))
9480
- ),
11932
+ 改哪条只动哪条(换算也只换算这一条的数值)。
11933
+ 「第三方平台」相关字段已整体挪到下方独立区块,气泡里不再出现。 */
11934
+ h("div", { className: "dsb-tier-head", key: "__tiered" }, [
11935
+ h("div", { className: "dsb-tier-checks", key: "__checks" }, [
11936
+ h("label", { className: "dsb-inline-check", key: "__tieredcheck" }, [
11937
+ h("input", {
11938
+ type: "checkbox",
11939
+ key: "__tieredinput",
11940
+ checked: draft.tiered === true,
11941
+ onChange: (event) => setDraftTiered(event.target.checked)
11942
+ }),
11943
+ h("span", null, t("priceTiered"))
11944
+ ])
11945
+ ]),
9481
11946
  h("div", { className: "dsb-currency-pick", key: "__curpick" },
9482
11947
  currencySelect("__entrycur", draft, currencyOpen, setCurrencyOpen, currencyMenuRef, currencyRef)
9483
11948
  )
9484
- ),
11949
+ ]),
9485
11950
  /* 未勾选时那行也有档位名(「全时段」),与勾选后的高峰/空闲两行结构一致,
9486
- 布局自然一致 —— 取代原先靠 CSS 做的双边对齐 */
11951
+ 布局自然一致 —— 取代原先靠 CSS 做的双边对齐 */
9487
11952
  draft.tiered === true ? tierRow("offPeak", t("priceTierOffPeak")) : tierRow("peak", t("priceTierAllDay")),
9488
11953
  draft.tiered === true ? tierRow("peak", t("priceTierPeak")) : null
9489
11954
  ])
9490
- : null;
9491
- modelRows.push(h("div", { className: "dsb-model", key: name }, head, body));
11955
+ : null;
11956
+ modelRows[name] = h("div", { className: "dsb-model", key: name }, head, body);
9492
11957
  });
9493
- if (modelRows.length > 0) {
9494
- priceCards.push(h("div", { className: "dsb-models", key: "__models" }, modelRows));
9495
- }
11958
+ /* 目录里的模型节点:**未配置**只显示可点的模型名(点它加入价格列表);
11959
+ **已配置**只显示真实价格卡(修改/删除/编辑气泡)—— 名字与卡不再重复显示。
11960
+ 来源链接 / 费率说明 / 添加按钮都已按用户要求去掉。 */
11961
+ /* 官方模型默认都已加入价格表:目录里直接渲染真实价格卡(修改/删除/编辑气泡)。
11962
+ 被删除(不在 cfg.models)的官方模型不显示,可用「恢复默认」找回。 */
11963
+ const catalogModelNode = (name) => h("div", { className: "dsb-catalog-model", key: "__catalog" + name }, modelRows[name]);
11964
+ const catalogSummary = (label) => h("summary", { className: "dsb-catalog-summary", key: "__summary" }, [
11965
+ h("span", { key: "__vendor" }, label)
11966
+ ]);
11967
+ const catalogVendorNode = (id) => {
11968
+ const common = { className: "dsb-catalog-vendor", key: id };
11969
+ if (id === "__custom") {
11970
+ const customRows = modelNames.filter((name) => MODEL_PRESENTATION[name] === undefined).map((name) => h("div", { className: "dsb-catalog-model", key: "__c" + name }, modelRows[name]));
11971
+ if (customRows.length === 0) return null;
11972
+ return h("details", Object.assign({}, common, {
11973
+ open: customModelsOpen === true,
11974
+ /* 用户手动开合也要同步回 state,否则下一次渲染会把分组强行改回默认态 */
11975
+ onToggle: (event) => setCatalogNotice(event.currentTarget.open === true)
11976
+ }), [
11977
+ catalogSummary(t("priceManufacturerCustom")),
11978
+ h("div", { className: "dsb-catalog-list dsb-models", key: "__list" }, customRows)
11979
+ ]);
11980
+ }
11981
+ const names = Object.keys(MODEL_PRESENTATION)
11982
+ .filter((name) => MODEL_PRESENTATION[name].manufacturer === id && cfg.models[name] !== undefined);
11983
+ if (names.length === 0) return null;
11984
+ return h("details", common, [
11985
+ catalogSummary(t(MODEL_MANUFACTURER_LABEL_KEYS[id])),
11986
+ h("div", { className: "dsb-catalog-list dsb-models", key: "__list" }, names.map(catalogModelNode))
11987
+ ]);
11988
+ };
11989
+ const catalogGroups = catalogOrder.map((id) => catalogVendorNode(id)).filter((node) => node !== null);
11990
+ priceCards.push(h("div", { className: "dsb-price-catalog", key: "__officialcatalog" }, [catalogGroups]));
9496
11991
  sections.push(h("div", { className: "dsb-section", key: "__prices" },
9497
11992
  h("div", { className: "dsb-sectitle" }, t("secPrices")),
9498
11993
  h("div", { className: "dsb-card" }, priceCards)
9499
11994
  ));
9500
11995
 
11996
+ /* 第三方平台(独立区块,位置在「自定义模型价格」卡片之后):
11997
+ 平台档案 = 余额查询(地址可空)+ 适用模型 + 每个模型的费用倍率。
11998
+ 这两样东西**不再**出现在模型价格气泡里(用户要求整个挪出来)。 */
11999
+ const platformCards = [];
12000
+ platformCards.push(h("div", { className: "dsb-hint", key: "__platformhint" }, t("secPlatformsHint")));
12001
+ platformCards.push(h("div", { className: "dsb-addrow", key: "__platformadd" },
12002
+ h("input", {
12003
+ type: "text",
12004
+ placeholder: t("platformNewPh"),
12005
+ value: newPlatform,
12006
+ onChange: (event) => setNewPlatform(event.target.value),
12007
+ onKeyDown: (event) => { if (event.key === "Enter") addPlatform(); }
12008
+ }),
12009
+ h("button", { type: "button", className: "dsb-action", onClick: addPlatform }, t("platformAdd"))
12010
+ ));
12011
+ if (platformNotice !== null) {
12012
+ platformCards.push(h("div", { className: "dsb-hint", key: "__platformnotice" }, platformNotice));
12013
+ }
12014
+ const relayStatuses = relayState.models === undefined || relayState.models === null ? {} : relayState.models;
12015
+ /* 新平台还没保存时不进 config:把「编辑中但尚未落库」的平台名也渲染出来,否则点添加后看不到编辑区 */
12016
+ const platformRows = platformNames.concat(
12017
+ platformEditing === null || platformNames.indexOf(platformEditing) !== -1 ? [] : [platformEditing]
12018
+ );
12019
+ if (platformRows.length === 0) {
12020
+ platformCards.push(h("div", { className: "dsb-hint", key: "__platformempty" }, t("platformEmpty")));
12021
+ }
12022
+ const platformRowNodes = [];
12023
+ platformRows.forEach((name) => {
12024
+ const open = platformEditing === name && platformDraft !== null;
12025
+ const status = relayStatuses[name];
12026
+ const tokenSaved = status !== undefined && status !== null && status.tokenConfigured === true;
12027
+ const userIdSaved = status !== undefined && status !== null && status.userIdConfigured === true;
12028
+ /* 头部按钮自带行为:拦一下冒泡,别被"点别处收起编辑区"顺手收掉 */
12029
+ const platformAction = (label, key, onClick) => h("button", {
12030
+ type: "button",
12031
+ key: key,
12032
+ className: "dsb-action dsb-action-sm",
12033
+ onClick: (event) => {
12034
+ if (event !== undefined && event !== null && typeof event.stopPropagation === "function") event.stopPropagation();
12035
+ onClick();
12036
+ }
12037
+ }, label);
12038
+ /* 卡片头部只显示平台名:地址 / 适用模型摘要一律不再展示(用户要求),编辑区里仍可查看修改 */
12039
+ const head = h("div", { className: "dsb-model-head dsb-platform-head", key: "__head", ref: open === true ? platformHeadRef : undefined, onClick: () => { if (open === true) savePlatform(); else startPlatform(name); } }, [
12040
+ h("div", { className: "dsb-platform-title" + (open === true ? " dsb-open" : "") + (open === true && platformPopUp === true ? " dsb-pop-up" : ""), key: "__title" }, name),
12041
+ h("div", { className: "dsb-model-actions" }, [
12042
+ open === true
12043
+ ? platformAction(t("priceSave"), "__save", savePlatform)
12044
+ : null,
12045
+ platformAction(t("priceRemove"), "__remove", () => removePlatform(name))
12046
+ ])
12047
+ ]);
12048
+ /* 适用模型自由行(模型名 + 费用倍率):数据来自草稿,空数组时给一句提示 */
12049
+ const platformModelRows = platformDraft === null || Array.isArray(platformDraft.modelRows) !== true
12050
+ ? []
12051
+ : platformDraft.modelRows;
12052
+ /* 平台编辑用毛玻璃浮层 */
12053
+ const body = open === true
12054
+ ? h("div", { className: "dsb-edit-pop dsb-platform-pop", key: "__edit", ref: platformEditRef, style: platformPopUp ? { top: "auto", bottom: "calc(100% + 2px)" } : { top: "calc(100% + 2px)", bottom: "auto" } }, [
12055
+ /* 请求头(= 用户 ID 的请求头)与用户 ID 同一行;令牌单独一行。
12056
+ 令牌 / 用户 ID 打开编辑回显已保存值;令牌框仍为 password(圆点,可选中复制)。 */
12057
+ h("div", { className: "dsb-relay-row", key: "__headers" }, [
12058
+ relayLine(t("priceTokenHeader"), "__useridheader", h("input", {
12059
+ type: "text", spellCheck: false, autoCorrect: "off", key: "__useridheaderinput", value: platformDraft.userIdHeader,
12060
+ placeholder: t("priceTokenHeaderHint"),
12061
+ onChange: (event) => setPlatformField("userIdHeader", event.target.value),
12062
+ onKeyDown: blurOnEnter
12063
+ })),
12064
+ relayLine(t("priceUserId"), "__userid", h("input", {
12065
+ type: "text", autoComplete: "off", spellCheck: false, autoCorrect: "off", key: "__useridinput", value: platformDraft.userId,
12066
+ placeholder: userIdSaved === true ? t("platformSecretSaved") : t("priceUserIdHint"),
12067
+ onChange: (event) => setPlatformField("userId", event.target.value),
12068
+ onKeyDown: blurOnEnter
12069
+ }))
12070
+ ]),
12071
+ relayLine(t("priceToken"), "__token", h("input", {
12072
+ type: "text", autoComplete: "off", spellCheck: false, autoCorrect: "off", className: "dsb-token-input", key: "__tokeninput", value: platformDraft.token,
12073
+ placeholder: tokenSaved === true ? t("platformSecretSaved") : t("priceTokenHint"),
12074
+ onChange: (event) => setPlatformField("token", event.target.value),
12075
+ onKeyDown: blurOnEnter,
12076
+ onCopy: (event) => { if (event !== null && event !== undefined && event.clipboardData) { event.preventDefault(); event.clipboardData.setData("text/plain", typeof platformDraft.token === "string" ? platformDraft.token : ""); } }
12077
+ })),
12078
+ relayLine(t("priceEndpoint"), "__endpoint", h("input", {
12079
+ type: "text", spellCheck: false, autoCorrect: "off", key: "__endpointinput", value: platformDraft.endpoint,
12080
+ placeholder: t("priceEndpointHint"),
12081
+ onChange: (event) => setPlatformField("endpoint", event.target.value),
12082
+ onKeyDown: blurOnEnter
12083
+ })),
12084
+ relayLine(t("priceBalanceField"), "__balance", h("input", {
12085
+ type: "text", spellCheck: false, autoCorrect: "off", key: "__balanceinput", value: platformDraft.balanceField,
12086
+ placeholder: t("priceBalanceFieldHint"),
12087
+ onChange: (event) => setPlatformField("balanceField", event.target.value),
12088
+ onKeyDown: blurOnEnter
12089
+ })),
12090
+ /* 适用模型 = 价格库下拉选择(按 modelOrder)。每行自带标签(像「请求头 / 用户 ID」
12091
+ 那样:标签在左、输入框紧随其后),不再单独做整行表头。
12092
+ 旧档案里不在价格库的模型名也并进该行选项,保证老配置可回显、可保存。 */
12093
+ h("div", { className: "dsb-relay-fields", key: "__models" }, [
12094
+ h("div", { className: "dsb-platform-model-list", key: "__modellist" }, platformModelRows.map((one, index) => {
12095
+ const current = typeof one.model === "string" ? one.model : "";
12096
+ const names = [];
12097
+ catalogOrder.forEach((vendor) => {
12098
+ if (vendor === "__custom") return;
12099
+ Object.keys(MODEL_PRESENTATION).forEach((name) => {
12100
+ if (MODEL_PRESENTATION[name].manufacturer === vendor
12101
+ && cfg.models[name] !== undefined && names.indexOf(name) === -1) names.push(name);
12102
+ });
12103
+ });
12104
+ modelNames.forEach((name) => {
12105
+ if (MODEL_PRESENTATION[name] === undefined && names.indexOf(name) === -1) names.push(name);
12106
+ });
12107
+ if (current.length > 0 && names.indexOf(current) === -1) names.push(current);
12108
+ /* 已被本平台其他行选中的模型:本行灰显、不可点;当前行自己的已选模型正常显示 */
12109
+ const chosenByOthers = (modelName) => platformModelRows.some((other, at) => at !== index
12110
+ && typeof other.model === "string" && other.model.length > 0
12111
+ && sameModelName(other.model, modelName) === true);
12112
+ const menuOpen = platformModelOpen === index;
12113
+ const stop = (event) => {
12114
+ if (event !== null && event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
12115
+ };
12116
+ return h("div", { className: "dsb-relay-row dsb-modelrow", key: "__row" + index }, [
12117
+ relayLine(t("platformModels"), "__modelline", h("div", { className: "dsb-select dsb-modelrow-select" + (current.length > 0 ? "" : " dsb-select-empty"), key: "__model" }, [
12118
+ h("button", {
12119
+ type: "button", key: "__modelbtn", className: "dsb-select-btn",
12120
+ "aria-haspopup": "listbox",
12121
+ "aria-expanded": menuOpen === true ? "true" : "false",
12122
+ ref: fitModelSelectLabel,
12123
+ onClick: (event) => {
12124
+ stop(event);
12125
+ if (menuOpen !== true) {
12126
+ const rect = event.currentTarget.getBoundingClientRect();
12127
+ const items = names.filter(function(modelName){ return modelName === current || chosenByOthers(modelName) !== true; }).map(function(modelName){ return { name: modelName, disabled: modelName.length>0 && chosenByOthers(modelName)===true, selected: modelName===current }; });
12128
+ const menuHeight = 8 + Math.min(items.length, 3) * 30;
12129
+ const need = menuHeight + 8;
12130
+ const start = platformEditRef.current && platformEditRef.current.closest ? platformEditRef.current.closest('.dsb-settings') : null;
12131
+ let sc = start !== null && start !== undefined ? start : event.currentTarget.parentElement;
12132
+ let boundary = Math.min(window.innerHeight, document.documentElement.clientHeight);
12133
+ while (sc) {
12134
+ if (sc === document.body || sc === document.documentElement) { sc = sc.parentElement; continue; }
12135
+ const cs = getComputedStyle(sc);
12136
+ if ((cs.overflowY === "auto" || cs.overflowY === "scroll") && sc.scrollHeight > sc.clientHeight + 2) { boundary = Math.min(boundary, sc.getBoundingClientRect().bottom); break; }
12137
+ sc = sc.parentElement;
12138
+ }
12139
+ const menuUp = (boundary - rect.bottom) < need;
12140
+ const top = Math.max(4, menuUp ? rect.top - menuHeight - 4 : rect.bottom + 4);
12141
+ platformMenuAnchor = event.currentTarget;
12142
+ setPlatformMenuSpec({ rowIndex: index, left: rect.left, width: rect.width, up: top, menuHeight: menuHeight, items: items });
12143
+ } else {
12144
+ platformMenuAnchor = null;
12145
+ setPlatformMenuSpec(null);
12146
+ }
12147
+ setPlatformModelOpen(menuOpen === true ? null : index);
12148
+ }
12149
+ }, current.length > 0 ? displayModelName(current) : h("span", { className: "dsb-select-placeholder" }, t("platformModelSelectPh"))),
12150
+ null
12151
+ ])),
12152
+ relayLine(t("priceFeeMultiplier"), "__feeline", h("span", { className: "dsb-modelrow-fee", key: "__fee" }, [
12153
+ h("input", {
12154
+ type: "number", step: "0.01", min: "0", key: "__feeinput", value: one.fee,
12155
+ placeholder: t("platformFeePh"),
12156
+ onChange: (event) => setPlatformModelRow(index, { fee: event.target.value }),
12157
+ onKeyDown: blurOnEnter
12158
+ }),
12159
+ h("button", {
12160
+ type: "button", key: "__del", className: "dsb-action dsb-action-sm",
12161
+ onClick: () => removePlatformModelRow(index)
12162
+ }, t("priceRemove"))
12163
+ ]))
12164
+ ]);
12165
+ })),
12166
+ h("button", { type: "button", className: "dsb-action", key: "__addmodel", onClick: addPlatformModelRow },
12167
+ t("platformAddModel"))
12168
+ ])
12169
+ ])
12170
+ : null;
12171
+ platformRowNodes.push(h("div", { className: "dsb-model dsb-platform-row" + (open === true ? " dsb-open" : ""), key: name }, head, body));
12172
+ });
12173
+ if (platformRowNodes.length > 0) platformCards.push(h("div", { className: "dsb-platform-list", key: "__platformlist" }, platformRowNodes));
12174
+ sections.push(h("div", { className: "dsb-section", key: "__platforms" },
12175
+ h("div", { className: "dsb-sectitle" }, [
12176
+ t("secPlatforms"),
12177
+ h("sup", { className: "dsb-experimental-badge", key: "__platformbadge" }, t("secPlatformsBadge"))
12178
+ ]),
12179
+ h("div", { className: "dsb-card" }, platformCards)
12180
+ ));
12181
+
9501
12182
  /* 收尾:GitHub 支持 + 恢复默认;版本标记贴右。
9502
12183
  「更新节假峰谷」已挪到上面价格卡那一行的右端。 */
9503
12184
  sections.push(h("div", { className: "dsb-foot", key: "__foot" }, [
@@ -9627,7 +12308,9 @@ window.__ModuleLoader__.load({
9627
12308
  : null
9628
12309
  ]));
9629
12310
 
9630
- return h("div", { className: "dsb-settings" }, sections);
12311
+ const floatingMenu = platformModelOpen === null || platformMenuSpec === null ? null : h("div", { key: "__modelmenu", className: "dsb-select-menu dsb-modelrow-menu", role: "listbox", ref: platformModelMenuRef, style: { position: "fixed", left: platformMenuSpec.left + "px", width: platformMenuSpec.width + "px", top: platformMenuSpec.up + "px", right: "auto", bottom: "auto", zIndex: 70 } },
12312
+ platformMenuSpec.items.map(function(one){ return h("button", { type: "button", key: one.name === "" ? "__empty" : one.name, role: "option", "aria-selected": one.selected ? "true" : "false", "aria-disabled": one.disabled ? "true" : "false", disabled: one.disabled, className: "dsb-select-item" + (one.selected ? " dsb-select-item-on" : "") + (one.disabled ? " dsb-select-item-disabled" : ""), onMouseDown: function(event){ if (event && event.stopPropagation) event.stopPropagation(); }, onClick: function(event){ if (event && event.stopPropagation) event.stopPropagation(); if (one.disabled) return; setPlatformModelRow(platformMenuSpec.rowIndex, { model: one.name }); setPlatformModelOpen(null); setPlatformMenuSpec(null); } }, displayModelName(one.name)); }));
12313
+ return h("div", { className: "dsb-settings" }, sections.concat(floatingMenu === null ? [] : [floatingMenu]));
9631
12314
  }
9632
12315
 
9633
12316
  /* --------------------------------------------------------------- apply */
@@ -9639,7 +12322,7 @@ window.__ModuleLoader__.load({
9639
12322
  (见 startPluginUpdate 的说明),界面其余部分也不需要宿主上下文 ——
9640
12323
  曾经存过一份 `pluginCtx` 只写不读,已删除。 */
9641
12324
  ctx.effect(installStyles, "dsh-desktop-statusbar: styles");
9642
- ctx.effect(() => ctx.locale.register(NS, { zh: zh, en: en }), "dsh-desktop-statusbar: locale");
12325
+ ctx.effect(() => ctx.locale.register(NS, { zh: zh, en: en, ja: ja, es: es, fr: fr, de: de, ru: ru, pt: pt }), "dsh-desktop-statusbar: locale");
9643
12326
  ctx.effect(() => installNavIcon(
9644
12327
  () => ctx.locale.bind(NS)("nav"),
9645
12328
  () => ctx.locale.bind(NS)("updatePill")
@@ -9652,6 +12335,16 @@ window.__ModuleLoader__.load({
9652
12335
  locale: NS
9653
12336
  }, StatusBar));
9654
12337
 
12338
+ /* 设置导航图标:宿主 0.2.2+ 只认官方 `settings.section.icon` 槽(按 settings.section id 匹配)。
12339
+ 旧宿主没有这个槽,`inject` 可能同步抛错 —— 包一层 try/catch,靠 installNavIcon 的 DOM 兜底。 */
12340
+ try {
12341
+ ctx.slots.inject("settings.section.icon", () => ctx.slots.register({
12342
+ name: "settings.section.icon",
12343
+ id: "dsh-desktop-statusbar",
12344
+ order: 40
12345
+ }, NavIcon));
12346
+ } catch (error) { /* 旧宿主没有该槽:忽略,DOM 兜底仍在 */ }
12347
+
9655
12348
  ctx.slots.inject("settings.section", () => ctx.slots.register({
9656
12349
  name: "settings.section",
9657
12350
  id: "dsh-desktop-statusbar",
@@ -9664,6 +12357,7 @@ window.__ModuleLoader__.load({
9664
12357
  const inject = ["slots", "locale"];
9665
12358
 
9666
12359
  exports.apply = apply;
12360
+ if (typeof window !== "undefined" && window.__DSH_STATUSBAR_TEST__ === true) exports.__testClient = { catalogPriceEntry: catalogPriceEntry, normalizeModels: normalizeModels };
9667
12361
  exports.inject = inject;
9668
12362
  return module.exports;
9669
12363
  }