dsh-continue-cost 0.0.0-stage → 1.3.1

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/client.js ADDED
@@ -0,0 +1,1724 @@
1
+ /**
2
+ * Browser half of `dsh-continue-cost`.
3
+ *
4
+ * One compact chip in the composer's trailing cluster
5
+ * (`conversation.input.right`) shows the completed turn count. Its dot uses the
6
+ * user's green / yellow / red thresholds, and hovering opens a panel with an
7
+ * estimate of the extra input cost of continuing this conversation instead of
8
+ * starting a new one.
9
+ *
10
+ * Every input is a live session projection (turn count, token usage, context
11
+ * pressure/composition, model selection). All arithmetic happens in this
12
+ * module, on this page. The optional Host routes only contribute the official
13
+ * price table and holiday schedule; no Session content or credential is sent.
14
+ *
15
+ * Written as plain JavaScript against the module-loader factory contract: no
16
+ * JSX, no imports, React comes from the shared table.
17
+ */
18
+ ;(() => {
19
+ /** Package name; also the Client module id and the registrant row name. */
20
+ const NAME = 'dsh-continue-cost'
21
+ /** Locale namespace; every visible string goes through it. */
22
+ const NS = 'dsh-continue-cost'
23
+ /* Keys keep the pre-rename prefix on purpose: an existing install must keep
24
+ * its thresholds and cached tables across the package rename. */
25
+ /** Threshold settings survive reloads in this browser. */
26
+ const STORAGE_KEY = 'dsh-turn-cost-meter:settings:v1'
27
+ /** Last validated official price table, so a reload still has prices offline. */
28
+ const PRICE_STORAGE_KEY = 'dsh-turn-cost-meter:prices:v1'
29
+ /** Host route that fetches the official pricing page server-side. */
30
+ const PRICE_PATH = '/plugins/dsh-continue-cost/prices'
31
+ /** Last validated official holiday schedule, so a reload still has it offline. */
32
+ const HOLIDAY_STORAGE_KEY = 'dsh-turn-cost-meter:holidays:v1'
33
+ /** Host route that fetches the current/next year's State Council notice. */
34
+ const HOLIDAY_PATH = '/plugins/dsh-continue-cost/holidays'
35
+
36
+ /**
37
+ * Official list prices, CNY per 1M tokens, by wire model id. Mirrors the
38
+ * table used by the API-balance plugin and DeepSeek's pricing page. An
39
+ * unknown model is reported as unknown rather than guessed.
40
+ */
41
+ const PRICING = {
42
+ 'deepseek-flash': {
43
+ off: { cacheHit: 0.02, cacheMiss: 1, output: 4 },
44
+ peak: { cacheHit: 0.04, cacheMiss: 2, output: 8 },
45
+ },
46
+ 'deepseek-v4-pro': {
47
+ off: { cacheHit: 0.15, cacheMiss: 4.5, output: 13.5 },
48
+ peak: { cacheHit: 0.3, cacheMiss: 9, output: 27 },
49
+ },
50
+ }
51
+
52
+ /** Retired wire ids the provider still serves and bills under a current model. */
53
+ const PRICING_ALIASES = {
54
+ 'deepseek-v4-flash': 'deepseek-flash',
55
+ 'deepseek-v4-flash-vision-exp': 'deepseek-flash',
56
+ }
57
+
58
+ /**
59
+ * Chinese statutory holidays in 2026, as Beijing calendar dates. DeepSeek's
60
+ * current rule makes every Chinese public holiday an off-peak day, and
61
+ * also makes make-up working weekends off-peak (the ordinary weekend check
62
+ * already covers those). Source: the State Council's 2026 holiday notice,
63
+ * https://www.gov.cn/zhengce/content/202511/content_7047090.htm
64
+ *
65
+ * Update this table when the next year's notice is published. The fixed
66
+ * dates below cover New Year, Labour Day, and the National Day golden week
67
+ * for later years until their formal schedules replace them.
68
+ */
69
+ const CN_HOLIDAYS_2026 = new Set([
70
+ '2026-01-01', '2026-01-02', '2026-01-03',
71
+ '2026-02-15', '2026-02-16', '2026-02-17', '2026-02-18', '2026-02-19',
72
+ '2026-02-20', '2026-02-21', '2026-02-22', '2026-02-23',
73
+ '2026-04-04', '2026-04-05', '2026-04-06',
74
+ '2026-05-01', '2026-05-02', '2026-05-03', '2026-05-04', '2026-05-05',
75
+ '2026-06-19', '2026-06-20', '2026-06-21',
76
+ '2026-09-25', '2026-09-26', '2026-09-27',
77
+ '2026-10-01', '2026-10-02', '2026-10-03', '2026-10-04',
78
+ '2026-10-05', '2026-10-06', '2026-10-07',
79
+ ])
80
+
81
+ /** Month-day fixed holidays that apply without a year-specific table. */
82
+ const FIXED_HOLIDAY_MONTH_DAYS = new Set([
83
+ '01-01',
84
+ '05-01',
85
+ '10-01', '10-02', '10-03', '10-04', '10-05', '10-06', '10-07',
86
+ ])
87
+
88
+ /** Dates fetched from the current/next year's official notice. */
89
+ const FETCHED_HOLIDAYS = new Set()
90
+
91
+ /**
92
+ * @param dateKey - Beijing calendar date, `YYYY-MM-DD`.
93
+ * @returns whether DeepSeek treats the date as an off-peak public holiday.
94
+ */
95
+ function isChineseHoliday(dateKey) {
96
+ return CN_HOLIDAYS_2026.has(dateKey)
97
+ || FETCHED_HOLIDAYS.has(dateKey)
98
+ || FIXED_HOLIDAY_MONTH_DAYS.has(dateKey.slice(5))
99
+ }
100
+
101
+ /** @param value - candidate price. @returns a finite non-negative number, or undefined. */
102
+ function priceNumber(value) {
103
+ const parsed = typeof value === 'number' ? value : Number(value)
104
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined
105
+ }
106
+
107
+ /**
108
+ * Validate one model's two tariffs from the Host route or localStorage.
109
+ * @param entry - candidate `{ off, peak }`.
110
+ * @returns detached valid prices, or undefined.
111
+ */
112
+ function normalizePriceEntry(entry) {
113
+ if (entry === null || typeof entry !== 'object') return undefined
114
+ const normalized = {}
115
+ for (const tariff of ['off', 'peak']) {
116
+ const prices = entry[tariff]
117
+ if (prices === null || typeof prices !== 'object') return undefined
118
+ const cacheHit = priceNumber(prices.cacheHit)
119
+ const cacheMiss = priceNumber(prices.cacheMiss)
120
+ const output = priceNumber(prices.output)
121
+ if (cacheHit === undefined || cacheMiss === undefined || output === undefined) return undefined
122
+ normalized[tariff] = { cacheHit, cacheMiss, output }
123
+ }
124
+ return normalized
125
+ }
126
+
127
+ /**
128
+ * Merge validated official prices into the built-in table. Existing models
129
+ * are replaced only when all six prices are readable; new models are added.
130
+ * @param models - `{ modelId: { off, peak } }` from the Host or cache.
131
+ * @returns how many models were accepted.
132
+ */
133
+ function mergePriceModels(models) {
134
+ if (models === null || typeof models !== 'object') return 0
135
+ let accepted = 0
136
+ for (const [name, entry] of Object.entries(models)) {
137
+ if (!/^[a-z0-9][a-z0-9._/-]*$/iu.test(name)) continue
138
+ const prices = normalizePriceEntry(entry)
139
+ if (prices === undefined) continue
140
+ PRICING[name.toLowerCase()] = prices
141
+ accepted += 1
142
+ }
143
+ return accepted
144
+ }
145
+
146
+ /**
147
+ * Load the last officially fetched table from this browser.
148
+ * @returns `{ fetchedAt }` when at least one model was applied, else undefined.
149
+ */
150
+ function readCachedPrices() {
151
+ try {
152
+ const raw = window.localStorage.getItem(PRICE_STORAGE_KEY)
153
+ if (raw === null) return undefined
154
+ const parsed = JSON.parse(raw)
155
+ if (parsed === null || typeof parsed !== 'object') return undefined
156
+ const accepted = mergePriceModels(parsed.models)
157
+ if (accepted === 0) return undefined
158
+ return { fetchedAt: typeof parsed.fetchedAt === 'number' ? parsed.fetchedAt : undefined }
159
+ } catch {
160
+ return undefined
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Persist the merged table. `PRICING` is written as a whole so built-in
166
+ * models survive too; the next load validates every entry again.
167
+ * @param fetchedAt - Host observation time, or now when unavailable.
168
+ */
169
+ function writeCachedPrices(fetchedAt) {
170
+ try {
171
+ window.localStorage.setItem(PRICE_STORAGE_KEY, JSON.stringify({ fetchedAt, models: PRICING }))
172
+ } catch {
173
+ /* private mode or a full quota: the in-memory table still works */
174
+ }
175
+ }
176
+
177
+ /** @param value - candidate date. @returns whether it is a real `YYYY-MM-DD` date. */
178
+ function isHolidayDate(value) {
179
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) return false
180
+ const [year, month, day] = value.split('-').map(Number)
181
+ const date = new Date(Date.UTC(year, month - 1, day))
182
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
183
+ }
184
+
185
+ /**
186
+ * Merge fetched official holiday dates into the runtime set.
187
+ * @param dates - candidate `YYYY-MM-DD` strings.
188
+ * @returns how many new dates were accepted.
189
+ */
190
+ function mergeHolidayDates(dates) {
191
+ if (!Array.isArray(dates)) return 0
192
+ let accepted = 0
193
+ for (const date of dates) {
194
+ if (!isHolidayDate(date) || FETCHED_HOLIDAYS.has(date)) continue
195
+ FETCHED_HOLIDAYS.add(date)
196
+ accepted += 1
197
+ }
198
+ return accepted
199
+ }
200
+
201
+ /**
202
+ * Load the last official holiday schedule remembered by this browser.
203
+ * @returns `{ fetchedAt }` when at least one date was applied, else undefined.
204
+ */
205
+ function readCachedHolidays() {
206
+ try {
207
+ const raw = window.localStorage.getItem(HOLIDAY_STORAGE_KEY)
208
+ if (raw === null) return undefined
209
+ const parsed = JSON.parse(raw)
210
+ if (parsed === null || typeof parsed !== 'object') return undefined
211
+ const accepted = mergeHolidayDates(parsed.dates)
212
+ if (accepted === 0) return undefined
213
+ return { fetchedAt: typeof parsed.fetchedAt === 'number' ? parsed.fetchedAt : undefined }
214
+ } catch {
215
+ return undefined
216
+ }
217
+ }
218
+
219
+ /** @param fetchedAt - Host observation time, or now when unavailable. */
220
+ function writeCachedHolidays(fetchedAt) {
221
+ try {
222
+ window.localStorage.setItem(HOLIDAY_STORAGE_KEY, JSON.stringify({
223
+ fetchedAt,
224
+ dates: [...FETCHED_HOLIDAYS],
225
+ }))
226
+ } catch {
227
+ /* private mode or a full quota: the in-memory schedule still works */
228
+ }
229
+ }
230
+
231
+ /** Defaults keep the first run useful without opening the settings. */
232
+ const DEFAULT_SETTINGS = {
233
+ metric: 'turns',
234
+ turnsGreen: 5,
235
+ turnsYellow: 10,
236
+ costGreen: 0.05,
237
+ costYellow: 0.15,
238
+ }
239
+
240
+ const ZH = {
241
+ 'chip.title': '对话轮数与续聊差价',
242
+ 'chip.unit': '轮',
243
+ 'chip.turnsLoading': '轮数 …',
244
+ 'chip.costUnknown': '¥ —',
245
+ 'chip.pinHint': '悬停看估算,点击胶囊固定并调整显示与阈值',
246
+ 'panel.title': '续聊差价估算',
247
+ 'panel.turns': '已完成轮数',
248
+ 'panel.extra': '差额(继续 − 新开)',
249
+ 'panel.continue': '继续当前对话(下一轮上下文)',
250
+ 'panel.fresh': '新开对话(同一轮上下文)',
251
+ 'panel.history': '历史上下文',
252
+ 'panel.prompt': '下一轮上下文预计',
253
+ 'panel.tokens': 'tokens',
254
+ 'panel.rateMeasured': '本会话平均 token 单价',
255
+ 'panel.rateReference': '参考 token 单价(未命中缓存)',
256
+ 'panel.model': '计价模型',
257
+ 'panel.noModel': '未选择模型',
258
+ 'panel.priceTable': '价格表',
259
+ 'panel.priceOnline': '官方在线',
260
+ 'panel.priceCache': '本地缓存',
261
+ 'panel.priceBuiltin': '内置',
262
+ 'panel.holidayTable': '节假日表',
263
+ 'panel.holidayOnline': '官方在线',
264
+ 'panel.holidayCache': '本地缓存',
265
+ 'panel.holidayBuiltin': '内置',
266
+ 'panel.perMillion': '/ 百万 tokens',
267
+ 'panel.tariff': '当前时段',
268
+ 'panel.tariffRule': '工作日北京时间 9:00–12:00、14:00–18:00 为峰时;午间、周末与法定节假日全天为谷时。跨过边界后这里与胶囊上的「峰/谷」会自动切换。',
269
+ 'panel.beijingTime': '北京时间',
270
+ 'panel.noPrice': '未收录该模型价格',
271
+ 'panel.noContext': '上下文数据还没准备好,暂时无法估算历史占比。',
272
+ 'panel.waiting': '还没有可用的 token 用量,先按未命中缓存的单价估算。',
273
+ 'panel.note': '分别估算继续和新开的上下文费用(系统提示、工具 schema、历史消息);回答本身费用两边相同,所以差额来自历史消息。按缓存命中比例估算,实际可能更低;以账单为准。',
274
+ 'panel.colorBy': '显示与着色',
275
+ 'panel.current': '当前显示值',
276
+ 'panel.leq': '≤',
277
+ 'panel.gt': '>',
278
+ 'tone.green': '绿',
279
+ 'tone.yellow': '黄',
280
+ 'tone.red': '红',
281
+ 'tone.idle': '等待数据',
282
+ 'tariff.peak': '峰时',
283
+ 'tariff.off': '谷时',
284
+ 'tariff.peakShort': '峰',
285
+ 'tariff.offShort': '谷',
286
+ 'settings.title': '阈值设置',
287
+ 'settings.turns': '对话轮数',
288
+ 'settings.cost': '多花金额',
289
+ 'settings.green': '绿色上限',
290
+ 'settings.yellow': '黄色上限',
291
+ 'settings.unitTurns': '轮',
292
+ 'settings.unitCost': '元',
293
+ 'settings.hint': '胶囊显示所选项,并按同一个数值着色:不超过绿色上限为绿,不超过黄色上限为黄,超过为红;两项自动保持先后顺序。',
294
+ 'settings.reset': '恢复默认',
295
+ 'settings.unpin': '收起',
296
+ 'settings.pinHint': '点击胶囊固定面板后即可切换显示和调整阈值。',
297
+ }
298
+
299
+ const EN = {
300
+ 'chip.title': 'Turn count & carry-over delta',
301
+ 'chip.unit': 'turns',
302
+ 'chip.turnsLoading': 'Turns …',
303
+ 'chip.costUnknown': '¥ —',
304
+ 'chip.pinHint': 'Hover for the estimate; click the chip to pin and adjust display/thresholds',
305
+ 'panel.title': 'Carry-over delta estimate',
306
+ 'panel.turns': 'Completed turns',
307
+ 'panel.extra': 'Delta (continue − fresh)',
308
+ 'panel.continue': 'Continue this chat (next-turn context)',
309
+ 'panel.fresh': 'Fresh chat (same-turn context)',
310
+ 'panel.history': 'History context',
311
+ 'panel.prompt': 'Next-turn context estimate',
312
+ 'panel.tokens': 'tokens',
313
+ 'panel.rateMeasured': 'Session average token rate',
314
+ 'panel.rateReference': 'Reference token rate (cache miss)',
315
+ 'panel.model': 'Priced model',
316
+ 'panel.noModel': 'No model selected',
317
+ 'panel.priceTable': 'Price table',
318
+ 'panel.priceOnline': 'Official online',
319
+ 'panel.priceCache': 'Local cache',
320
+ 'panel.priceBuiltin': 'Built-in',
321
+ 'panel.holidayTable': 'Holiday table',
322
+ 'panel.holidayOnline': 'Official online',
323
+ 'panel.holidayCache': 'Local cache',
324
+ 'panel.holidayBuiltin': 'Built-in',
325
+ 'panel.perMillion': '/ 1M tokens',
326
+ 'panel.tariff': 'Current tariff',
327
+ 'panel.tariffRule': 'Peak is 09:00–12:00 and 14:00–18:00 Beijing weekdays; the midday break, weekends and public holidays are off-peak. The chip badge and this row follow the clock automatically.',
328
+ 'panel.beijingTime': 'Beijing',
329
+ 'panel.noPrice': 'No listed price for this model',
330
+ 'panel.noContext': 'Context data is not ready yet; the history share is unknown for now.',
331
+ 'panel.waiting': 'No token usage yet; pricing the history at the cache-miss rate.',
332
+ 'panel.note': 'Both sides estimate the context cost (system prompt, tool schemas, history messages); the answer cost is identical, so the delta comes from history. Priced from the cache-hit mix; the real delta may be lower. Actual billing may differ.',
333
+ 'panel.colorBy': 'Display & color',
334
+ 'panel.current': 'Current display',
335
+ 'panel.leq': '≤',
336
+ 'panel.gt': '>',
337
+ 'tone.green': 'green',
338
+ 'tone.yellow': 'yellow',
339
+ 'tone.red': 'red',
340
+ 'tone.idle': 'waiting for data',
341
+ 'tariff.peak': 'peak',
342
+ 'tariff.off': 'off-peak',
343
+ 'tariff.peakShort': 'peak',
344
+ 'tariff.offShort': 'off',
345
+ 'settings.title': 'Thresholds',
346
+ 'settings.turns': 'Turns',
347
+ 'settings.cost': 'Extra cost',
348
+ 'settings.green': 'Green up to',
349
+ 'settings.yellow': 'Yellow up to',
350
+ 'settings.unitTurns': 'turns',
351
+ 'settings.unitCost': 'CNY',
352
+ 'settings.hint': 'The chip shows and colors by the selected value: green up to the first limit, yellow up to the second, red above it; the two limits keep their order.',
353
+ 'settings.reset': 'Reset',
354
+ 'settings.unpin': 'Close',
355
+ 'settings.pinHint': 'Click the chip to pin the panel, then switch the display and adjust thresholds.',
356
+ }
357
+
358
+ /** @param value - candidate number. @returns a finite non-negative number, else the fallback. */
359
+ function nonNegative(value, fallback) {
360
+ const parsed = typeof value === 'number' ? value : Number(value)
361
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback
362
+ }
363
+
364
+ /**
365
+ * Coerce one stored settings object, keeping every threshold valid and the
366
+ * yellow limit at or above the green one.
367
+ * @param raw - parsed localStorage value.
368
+ * @returns complete settings.
369
+ */
370
+ function normalizeSettings(raw) {
371
+ const source = raw !== null && typeof raw === 'object' ? raw : {}
372
+ const metric = source.metric === 'cost' ? 'cost' : 'turns'
373
+ const turnsGreen = Math.round(nonNegative(source.turnsGreen, DEFAULT_SETTINGS.turnsGreen))
374
+ const turnsYellow = Math.max(
375
+ turnsGreen,
376
+ Math.round(nonNegative(source.turnsYellow, DEFAULT_SETTINGS.turnsYellow)),
377
+ )
378
+ const costGreen = nonNegative(source.costGreen, DEFAULT_SETTINGS.costGreen)
379
+ const costYellow = Math.max(costGreen, nonNegative(source.costYellow, DEFAULT_SETTINGS.costYellow))
380
+ return { metric, turnsGreen, turnsYellow, costGreen, costYellow }
381
+ }
382
+
383
+ /** @returns settings remembered by this browser, or the defaults. */
384
+ function readSettings() {
385
+ try {
386
+ const raw = window.localStorage.getItem(STORAGE_KEY)
387
+ return raw === null ? normalizeSettings(undefined) : normalizeSettings(JSON.parse(raw))
388
+ } catch {
389
+ return normalizeSettings(undefined)
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Read one non-negative finite count out of a projection value that crossed
395
+ * the wire, so a malformed bucket cannot become a fake cost.
396
+ * @param value - candidate from the projection.
397
+ * @returns the count, or 0.
398
+ */
399
+ function countOf(value) {
400
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
401
+ }
402
+
403
+ /**
404
+ * Resolve the list price of the route serving this conversation. The route
405
+ * may be addressed with a provider prefix, so both spellings resolve.
406
+ * @param selection - `modelSelection` projection.
407
+ * @returns that model's tariffs, or undefined.
408
+ */
409
+ function pricingOf(selection) {
410
+ const raw = selection?.next?.model ?? selection?.lastUsed?.model
411
+ if (typeof raw !== 'string' || raw === '') return undefined
412
+ const slash = raw.lastIndexOf('/')
413
+ const bare = slash === -1 ? raw : raw.slice(slash + 1)
414
+ const bareKey = bare.toLowerCase()
415
+ const fullKey = raw.toLowerCase()
416
+ const id = PRICING[bareKey] === undefined ? fullKey : bareKey
417
+ const alias = PRICING_ALIASES[id]
418
+ ?? PRICING_ALIASES[bareKey]
419
+ ?? PRICING_ALIASES[fullKey]
420
+ return PRICING[id] ?? (alias === undefined ? undefined : PRICING[alias])
421
+ }
422
+
423
+ /** @returns the bare model id serving the conversation, or undefined. */
424
+ function modelOf(selection) {
425
+ const raw = selection?.next?.model ?? selection?.lastUsed?.model
426
+ if (typeof raw !== 'string' || raw === '') return undefined
427
+ const slash = raw.lastIndexOf('/')
428
+ return slash === -1 ? raw : raw.slice(slash + 1)
429
+ }
430
+
431
+ /**
432
+ * Peak windows as Beijing wall-clock `[start, end)` hour pairs, straight from
433
+ * the official pricing page: "北京时间周一至周五(不含中国法定节假日)
434
+ * 9:00 - 12:00、14:00 - 18:00 为高峰时段". Everything else — including the
435
+ * 12:00-14:00 midday break, weekends and statutory holidays — is off-peak.
436
+ */
437
+ const PEAK_WINDOWS = [
438
+ [9, 12],
439
+ [14, 18],
440
+ ]
441
+
442
+ /** Hours at which the tariff can change: window edges plus midnight. */
443
+ const TARIFF_BOUNDARY_HOURS = [0, ...PEAK_WINDOWS.flat()]
444
+
445
+ /** How far ahead the boundary search looks (a weekend plus a holiday run). */
446
+ const BOUNDARY_LOOKAHEAD_DAYS = 12
447
+
448
+ /**
449
+ * Read an instant as Beijing wall-clock fields. Shifting the epoch by eight
450
+ * hours and reading the UTC fields makes the answer independent of the
451
+ * browser's own time zone.
452
+ * @param now - instant to read.
453
+ * @returns `{ day, hour, minute, timeKey, dateKey }` in Beijing time.
454
+ */
455
+ function beijingClock(now = new Date()) {
456
+ const shifted = new Date(now.getTime() + 8 * 60 * 60 * 1000)
457
+ const hour = shifted.getUTCHours()
458
+ const minute = shifted.getUTCMinutes()
459
+ return {
460
+ day: shifted.getUTCDay(),
461
+ hour,
462
+ minute,
463
+ dateKey: shifted.toISOString().slice(0, 10),
464
+ timeKey: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
465
+ }
466
+ }
467
+
468
+ /**
469
+ * @param clock - Beijing wall-clock fields from {@link beijingClock}.
470
+ * @returns true when the provider charges the peak tariff then.
471
+ */
472
+ function isPeakAtClock(clock) {
473
+ if (clock.day === 0 || clock.day === 6) return false
474
+ if (isChineseHoliday(clock.dateKey)) return false
475
+ return PEAK_WINDOWS.some(([start, end]) => clock.hour >= start && clock.hour < end)
476
+ }
477
+
478
+ /**
479
+ * Which provider tariff is in force now: peak 09:00-12:00 and 14:00-18:00
480
+ * Beijing time on weekdays, off-peak on weekends, make-up working weekends,
481
+ * and Chinese public holidays. The holiday table covers 2026 plus the fixed
482
+ * New Year / Labour Day / National Day dates for later years.
483
+ * @param now - instant to classify.
484
+ * @returns true for peak.
485
+ */
486
+ function isPeakTariff(now = new Date()) {
487
+ try {
488
+ return isPeakAtClock(beijingClock(now))
489
+ } catch {
490
+ return true
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Milliseconds until the tariff next changes, so the chip can switch exactly
496
+ * at 09:00 / 12:00 / 14:00 / 18:00 and at midnight (weekend or holiday
497
+ * starts) instead of waiting for the next poll. Returns the poll interval
498
+ * when the search fails.
499
+ * @param now - instant to measure from.
500
+ * @returns a positive delay in milliseconds.
501
+ */
502
+ function msUntilNextTariffChange(now = new Date()) {
503
+ try {
504
+ const base = now.getTime()
505
+ const shifted = new Date(base + 8 * 60 * 60 * 1000)
506
+ const year = shifted.getUTCFullYear()
507
+ const month = shifted.getUTCMonth()
508
+ const date = shifted.getUTCDate()
509
+ let next = Number.POSITIVE_INFINITY
510
+ for (let offset = 0; offset <= BOUNDARY_LOOKAHEAD_DAYS; offset += 1) {
511
+ const day = new Date(Date.UTC(year, month, date + offset))
512
+ for (const hour of TARIFF_BOUNDARY_HOURS) {
513
+ const at = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), hour)
514
+ - 8 * 60 * 60 * 1000
515
+ if (at > base + 1_000 && at < next) next = at
516
+ }
517
+ }
518
+ return Number.isFinite(next) ? next - base : 30_000
519
+ } catch {
520
+ return 30_000
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Estimate the next turn's input side and the extra part caused by carrying
526
+ * the current history into it.
527
+ *
528
+ * `historyTokens` comes from the heuristic composition of the next request,
529
+ * scaled to the provider-anchored next-request pressure when one is present.
530
+ * If neither context projection has arrived, the history share is unknown
531
+ * rather than guessed from cumulative usage: one turn can contain many
532
+ * tool/model steps, so an average input per turn would overstate it badly.
533
+ * The per-million-token rate is the session's observed cache-hit/cache-miss
534
+ * mix at the current tariff; with no usage yet it falls back to the
535
+ * cache-miss rate. Output is identical between continuing and starting
536
+ * fresh, so it is left out.
537
+ *
538
+ * @param params - live projections and the current tariff.
539
+ * @returns the estimate and the figures behind it.
540
+ */
541
+ function estimateNextTurn(params) {
542
+ const { usage, breakdown, pressure, selection, peak } = params
543
+ const tariffs = pricingOf(selection)
544
+ const tariff = tariffs === undefined ? undefined : tariffs[peak ? 'peak' : 'off']
545
+ const systemTokens = countOf(breakdown?.systemTokens)
546
+ const toolsTokens = countOf(breakdown?.toolsTokens)
547
+ const baseTokens = systemTokens + toolsTokens
548
+ const hit = countOf(usage?.cacheReadTokens)
549
+ const miss = countOf(usage?.uncachedInputTokens) + countOf(usage?.cacheWriteTokens)
550
+ const inputTokens = hit + miss
551
+ const projected = countOf(pressure?.projectedTokens)
552
+ const lastPressure = countOf(pressure?.pressureTokens)
553
+ const anchor = projected > 0 ? projected : lastPressure
554
+ const heuristicHistory = countOf(breakdown?.messageTokens)
555
+ const heuristicTotal = baseTokens + heuristicHistory
556
+ const inferredHistory = anchor > baseTokens ? anchor - baseTokens : 0
557
+ const hasContext = anchor > 0 || breakdown !== undefined
558
+ // `projectedTokens`/`pressureTokens` are provider-anchored while the
559
+ // composition is heuristic. When both exist, scale the message share to
560
+ // the anchored total so a systematic CJK/JSON undercount does not shrink
561
+ // the history.
562
+ const historyTokens =
563
+ anchor > 0 && heuristicHistory > 0 && heuristicTotal > 0
564
+ ? anchor * (heuristicHistory / heuristicTotal)
565
+ : heuristicHistory > 0
566
+ ? heuristicHistory
567
+ : inferredHistory
568
+ const promptTokens = anchor > 0 ? anchor : historyTokens + baseTokens
569
+
570
+ const ratePerMillion =
571
+ tariff === undefined
572
+ ? undefined
573
+ : inputTokens > 0
574
+ ? (hit * tariff.cacheHit + miss * tariff.cacheMiss) / inputTokens
575
+ : tariff.cacheMiss
576
+
577
+ const priced = tariff !== undefined && ratePerMillion !== undefined
578
+ const extraCny = priced && hasContext ? (historyTokens / 1e6) * ratePerMillion : undefined
579
+ const totalCny = priced && hasContext ? (promptTokens / 1e6) * ratePerMillion : undefined
580
+ const freshCny =
581
+ priced && hasContext ? (Math.max(0, promptTokens - historyTokens) / 1e6) * ratePerMillion : undefined
582
+ return {
583
+ priced,
584
+ hasContext,
585
+ measured: inputTokens > 0,
586
+ historyTokens,
587
+ promptTokens,
588
+ baseTokens,
589
+ extraCny,
590
+ totalCny,
591
+ freshCny,
592
+ rate: ratePerMillion,
593
+ model: modelOf(selection),
594
+ peak,
595
+ hasUsage: inputTokens > 0,
596
+ }
597
+ }
598
+
599
+ /**
600
+ * Pick the dot tone from the configured metric and thresholds.
601
+ * @param settings - normalized settings.
602
+ * @param turns - completed turns.
603
+ * @param estimate - the current estimate.
604
+ * @param loaded - whether the turn projection has arrived.
605
+ * @returns `green`, `yellow`, `red`, or `idle`.
606
+ */
607
+ function toneOf(settings, turns, estimate, loaded) {
608
+ let value
609
+ let green
610
+ let yellow
611
+ if (settings.metric === 'cost') {
612
+ if (!estimate.hasContext || !estimate.priced || estimate.extraCny === undefined) return 'idle'
613
+ value = estimate.extraCny
614
+ green = settings.costGreen
615
+ yellow = settings.costYellow
616
+ } else {
617
+ if (!loaded) return 'idle'
618
+ value = turns
619
+ green = settings.turnsGreen
620
+ yellow = settings.turnsYellow
621
+ }
622
+ if (value <= green) return 'green'
623
+ if (value <= yellow) return 'yellow'
624
+ return 'red'
625
+ }
626
+
627
+ /**
628
+ * Build the browser bundle's factory.
629
+ * @param require - the module table's require.
630
+ * @returns the factory the module loader registers.
631
+ */
632
+ function makeFactory() {
633
+ return (require) => {
634
+ const module = { exports: {} }
635
+ const React = require('react')
636
+ const { createElement: h, useState, useEffect, useRef, useSyncExternalStore } = React
637
+
638
+ /** The last table remembered by this browser, applied before the fetch lands. */
639
+ const cachedPrice = readCachedPrices()
640
+ /** One shared price-table snapshot; components re-render when it changes. */
641
+ let priceSnapshot = {
642
+ source: cachedPrice === undefined ? 'builtin' : 'cache',
643
+ fetchedAt: cachedPrice === undefined ? undefined : cachedPrice.fetchedAt,
644
+ revision: 0,
645
+ }
646
+ const priceListeners = new Set()
647
+ let priceInflight = null
648
+
649
+ /** @param listener - price change callback. @returns unsubscribe. */
650
+ function subscribePrices(listener) {
651
+ priceListeners.add(listener)
652
+ return () => {
653
+ priceListeners.delete(listener)
654
+ }
655
+ }
656
+
657
+ /** @returns the current price-table snapshot. */
658
+ function getPriceSnapshot() {
659
+ return priceSnapshot
660
+ }
661
+
662
+ /** @returns current price-table metadata, re-rendering on update. */
663
+ function usePrices() {
664
+ return useSyncExternalStore(subscribePrices, getPriceSnapshot)
665
+ }
666
+
667
+ /**
668
+ * Ask the Host to fetch the official pricing Markdown and merge any
669
+ * validated model prices. Failure leaves the built-in/cached table in
670
+ * place and stays silent; this is an enhancement, not a prerequisite.
671
+ * @returns a promise settling after the attempt.
672
+ */
673
+ function refreshPrices() {
674
+ if (priceInflight !== null) return priceInflight
675
+ priceInflight = (async () => {
676
+ try {
677
+ const response = await fetch(PRICE_PATH, {
678
+ headers: { accept: 'application/json' },
679
+ })
680
+ if (!response.ok) return
681
+ const body = await response.json()
682
+ if (body === null || typeof body !== 'object' || body.ok !== true) return
683
+ const accepted = mergePriceModels(body.models)
684
+ if (accepted === 0) return
685
+ const fetchedAt = typeof body.fetchedAt === 'number' ? body.fetchedAt : Date.now()
686
+ writeCachedPrices(fetchedAt)
687
+ priceSnapshot = {
688
+ source: 'online',
689
+ fetchedAt,
690
+ revision: priceSnapshot.revision + 1,
691
+ }
692
+ for (const listener of priceListeners) listener()
693
+ } catch {
694
+ /* offline or no Host route: keep the built-in/cached table */
695
+ } finally {
696
+ priceInflight = null
697
+ }
698
+ })()
699
+ return priceInflight
700
+ }
701
+
702
+ /** The last official holiday schedule remembered by this browser. */
703
+ const cachedHoliday = readCachedHolidays()
704
+ /** One shared holiday-table snapshot; components re-render when it changes. */
705
+ let holidaySnapshot = {
706
+ source: cachedHoliday === undefined ? 'builtin' : 'cache',
707
+ fetchedAt: cachedHoliday === undefined ? undefined : cachedHoliday.fetchedAt,
708
+ revision: 0,
709
+ }
710
+ const holidayListeners = new Set()
711
+ let holidayInflight = null
712
+
713
+ /** @param listener - holiday change callback. @returns unsubscribe. */
714
+ function subscribeHolidays(listener) {
715
+ holidayListeners.add(listener)
716
+ return () => {
717
+ holidayListeners.delete(listener)
718
+ }
719
+ }
720
+
721
+ /** @returns the current holiday-table snapshot. */
722
+ function getHolidaySnapshot() {
723
+ return holidaySnapshot
724
+ }
725
+
726
+ /** @returns current holiday-table metadata, re-rendering on update. */
727
+ function useHolidays() {
728
+ return useSyncExternalStore(subscribeHolidays, getHolidaySnapshot)
729
+ }
730
+
731
+ /**
732
+ * Ask the Host to discover and parse the current/next year's State
733
+ * Council holiday notice. A failure keeps the built-in/cached schedule.
734
+ * @returns a promise settling after the attempt.
735
+ */
736
+ function refreshHolidays() {
737
+ if (holidayInflight !== null) return holidayInflight
738
+ holidayInflight = (async () => {
739
+ try {
740
+ const response = await fetch(HOLIDAY_PATH, {
741
+ headers: { accept: 'application/json' },
742
+ })
743
+ if (!response.ok) return
744
+ const body = await response.json()
745
+ if (body === null || typeof body !== 'object' || body.ok !== true) return
746
+ if (body.years === null || typeof body.years !== 'object') return
747
+ const dates = Object.values(body.years).flatMap((value) => Array.isArray(value) ? value : [])
748
+ const valid = dates.filter((date) => isHolidayDate(date))
749
+ if (valid.length === 0) return
750
+ mergeHolidayDates(valid)
751
+ const fetchedAt = typeof body.fetchedAt === 'number' ? body.fetchedAt : Date.now()
752
+ writeCachedHolidays(fetchedAt)
753
+ holidaySnapshot = {
754
+ source: 'online',
755
+ fetchedAt,
756
+ revision: holidaySnapshot.revision + 1,
757
+ }
758
+ for (const listener of holidayListeners) listener()
759
+ } catch {
760
+ /* offline or no Host route: keep the built-in/cached schedule */
761
+ } finally {
762
+ holidayInflight = null
763
+ }
764
+ })()
765
+ return holidayInflight
766
+ }
767
+
768
+ /** Chip geometry and panel styling; every color is a host theme token. */
769
+ const CSS = `
770
+ .dshTurnCost_anchor { position: relative; display: inline-flex; align-items: center; }
771
+ .dshTurnCost_chip {
772
+ box-sizing: border-box;
773
+ display: inline-flex;
774
+ align-items: stretch;
775
+ height: 28px;
776
+ max-width: 200px;
777
+ padding: 0;
778
+ border: 1px solid var(--dsw-alias-border-l1);
779
+ border-radius: var(--dsw-radius-sm);
780
+ background: transparent;
781
+ color: var(--dsw-alias-label-secondary);
782
+ font-family: inherit;
783
+ font-size: 12px;
784
+ font-weight: 500;
785
+ line-height: 18px;
786
+ white-space: nowrap;
787
+ overflow: hidden;
788
+ }
789
+ .dshTurnCost_chip:hover { background: var(--dsw-alias-bg-layer-2); }
790
+ .dshTurnCost_chip[data-tone="green"] { color: var(--dsw-alias-label-primary); }
791
+ .dshTurnCost_chip[data-tone="yellow"] { color: var(--dsw-alias-label-primary); }
792
+ .dshTurnCost_chip[data-tone="red"] { color: var(--dsw-alias-label-primary); }
793
+ .dshTurnCost_chip:focus-within { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
794
+ .dshTurnCost_main {
795
+ display: inline-flex;
796
+ align-items: center;
797
+ gap: 6px;
798
+ min-width: 0;
799
+ padding: 0 8px;
800
+ border: 0;
801
+ background: transparent;
802
+ color: inherit;
803
+ font: inherit;
804
+ cursor: pointer;
805
+ }
806
+ .dshTurnCost_main:focus-visible { outline: none; }
807
+ .dshTurnCost_dot {
808
+ width: 6px;
809
+ height: 6px;
810
+ border-radius: 50%;
811
+ flex: none;
812
+ background: var(--dsw-alias-state-idle-primary);
813
+ }
814
+ .dshTurnCost_chip[data-tone="green"] .dshTurnCost_dot { background: var(--dsw-alias-state-success-primary); }
815
+ .dshTurnCost_chip[data-tone="yellow"] .dshTurnCost_dot { background: var(--dsw-alias-state-warn-primary); }
816
+ .dshTurnCost_chip[data-tone="red"] .dshTurnCost_dot { background: var(--dsw-alias-state-error-primary); }
817
+ .dshTurnCost_amount { font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
818
+ .dshTurnCost_tariff {
819
+ flex: none;
820
+ align-self: center;
821
+ padding: 1px 3px;
822
+ border-radius: 3px;
823
+ background: var(--dsw-alias-bg-layer-2);
824
+ color: var(--dsw-alias-label-secondary);
825
+ font-size: 10px;
826
+ line-height: 12px;
827
+ letter-spacing: .02em;
828
+ }
829
+ .dshTurnCost_tariff[data-tariff="peak"] { color: var(--dsw-alias-label-primary); }
830
+ .dshTurnCost_panel {
831
+ position: absolute;
832
+ bottom: calc(100% + 8px);
833
+ right: 0;
834
+ z-index: 1400;
835
+ box-sizing: border-box;
836
+ width: 292px;
837
+ max-width: min(292px, calc(100vw - 24px));
838
+ max-height: min(70vh, calc(100vh - 88px));
839
+ overflow-y: auto;
840
+ overscroll-behavior: contain;
841
+ padding: 10px 12px;
842
+ border-radius: var(--dsw-radius-md);
843
+ background: var(--dsw-alias-bg-overlay);
844
+ box-shadow: var(--dsw-elevation-panel);
845
+ color: var(--dsw-alias-label-primary);
846
+ font-family: inherit;
847
+ font-size: 12px;
848
+ line-height: 18px;
849
+ text-align: left;
850
+ pointer-events: auto;
851
+ }
852
+ .dshTurnCost_header {
853
+ display: flex;
854
+ align-items: baseline;
855
+ justify-content: space-between;
856
+ gap: 10px;
857
+ margin-bottom: 4px;
858
+ color: var(--dsw-alias-label-secondary);
859
+ }
860
+ .dshTurnCost_headerTitle { font-weight: 500; }
861
+ .dshTurnCost_unpin {
862
+ padding: 0;
863
+ border: 0;
864
+ background: transparent;
865
+ color: var(--dsw-alias-brand-primary);
866
+ font: inherit;
867
+ cursor: pointer;
868
+ }
869
+ .dshTurnCost_unpin:hover { text-decoration: underline; }
870
+ .dshTurnCost_unpin:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
871
+ .dshTurnCost_line { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }
872
+ .dshTurnCost_label { color: var(--dsw-alias-label-secondary); }
873
+ .dshTurnCost_value { font-variant-numeric: tabular-nums; text-align: right; }
874
+ .dshTurnCost_line[data-emphasis="true"] { margin: 3px 0; font-size: 13px; font-weight: 600; }
875
+ .dshTurnCost_line[data-emphasis="true"] .dshTurnCost_label { color: var(--dsw-alias-label-primary); }
876
+ .dshTurnCost_divider { margin: 7px 0; border-top: .5px solid var(--dsw-alias-border-l1); }
877
+ .dshTurnCost_alert { color: var(--dsw-alias-state-warn-primary); }
878
+ .dshTurnCost_note { margin-top: 6px; color: var(--dsw-alias-label-secondary); }
879
+ .dshTurnCost_stage {
880
+ margin-top: 8px;
881
+ padding-top: 7px;
882
+ border-top: .5px solid var(--dsw-alias-border-l1);
883
+ }
884
+ .dshTurnCost_stageText { margin-top: 2px; color: var(--dsw-alias-label-secondary); }
885
+ .dshTurnCost_pinHint { margin-top: 7px; color: var(--dsw-alias-brand-primary); }
886
+ .dshTurnCost_displayRow {
887
+ display: flex;
888
+ align-items: center;
889
+ justify-content: space-between;
890
+ gap: 10px;
891
+ margin-bottom: 7px;
892
+ padding-bottom: 7px;
893
+ border-bottom: .5px solid var(--dsw-alias-border-l1);
894
+ }
895
+ .dshTurnCost_displayLabel { color: var(--dsw-alias-label-secondary); }
896
+ .dshTurnCost_displayRow .dshTurnCost_seg { margin-bottom: 0; }
897
+ .dshTurnCost_settings {
898
+ margin-top: 9px;
899
+ padding-top: 8px;
900
+ border-top: .5px solid var(--dsw-alias-border-l1);
901
+ }
902
+ .dshTurnCost_settingsTitle { margin-bottom: 6px; font-weight: 500; }
903
+ .dshTurnCost_seg {
904
+ display: inline-flex;
905
+ margin-bottom: 7px;
906
+ border: 1px solid var(--dsw-alias-border-l1);
907
+ border-radius: 6px;
908
+ overflow: hidden;
909
+ }
910
+ .dshTurnCost_segBtn {
911
+ padding: 3px 9px;
912
+ border: 0;
913
+ background: transparent;
914
+ color: var(--dsw-alias-label-secondary);
915
+ font: inherit;
916
+ cursor: pointer;
917
+ }
918
+ .dshTurnCost_segBtn[data-active="true"] {
919
+ background: var(--dsw-alias-bg-layer-2);
920
+ color: var(--dsw-alias-label-primary);
921
+ }
922
+ .dshTurnCost_segBtn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -2px; }
923
+ .dshTurnCost_field {
924
+ display: flex;
925
+ align-items: center;
926
+ justify-content: space-between;
927
+ gap: 10px;
928
+ margin-top: 5px;
929
+ }
930
+ .dshTurnCost_fieldLabel { color: var(--dsw-alias-label-secondary); }
931
+ .dshTurnCost_inputWrap { display: inline-flex; align-items: center; gap: 4px; }
932
+ .dshTurnCost_input {
933
+ box-sizing: border-box;
934
+ width: 74px;
935
+ height: 25px;
936
+ padding: 0 6px;
937
+ border: 1px solid var(--dsw-alias-border-l1);
938
+ border-radius: 5px;
939
+ background: var(--dsw-alias-bg-layer-1);
940
+ color: var(--dsw-alias-label-primary);
941
+ font: inherit;
942
+ font-variant-numeric: tabular-nums;
943
+ }
944
+ .dshTurnCost_input:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
945
+ .dshTurnCost_unit { color: var(--dsw-alias-label-secondary); }
946
+ .dshTurnCost_settingsFoot {
947
+ display: flex;
948
+ align-items: flex-start;
949
+ justify-content: space-between;
950
+ gap: 10px;
951
+ margin-top: 7px;
952
+ color: var(--dsw-alias-label-secondary);
953
+ }
954
+ .dshTurnCost_reset {
955
+ flex: none;
956
+ padding: 0;
957
+ border: 0;
958
+ background: transparent;
959
+ color: var(--dsw-alias-brand-primary);
960
+ font: inherit;
961
+ cursor: pointer;
962
+ }
963
+ .dshTurnCost_reset:hover { text-decoration: underline; }
964
+ .dshTurnCost_reset:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
965
+ `.trim()
966
+
967
+ /** One shared settings store, so two session chips stay in sync. */
968
+ let settings = readSettings()
969
+ const settingsListeners = new Set()
970
+
971
+ /** @param next - complete settings to normalize, persist, and publish. */
972
+ function publishSettings(next) {
973
+ settings = normalizeSettings(next)
974
+ try {
975
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(settings))
976
+ } catch {
977
+ /* private mode or a full quota: the in-memory value still works */
978
+ }
979
+ for (const listener of settingsListeners) listener()
980
+ }
981
+
982
+ /** @param listener - change callback. @returns unsubscribe. */
983
+ function subscribeSettings(listener) {
984
+ settingsListeners.add(listener)
985
+ return () => {
986
+ settingsListeners.delete(listener)
987
+ }
988
+ }
989
+
990
+ /** @returns the current settings (stable reference between changes). */
991
+ function getSettings() {
992
+ return settings
993
+ }
994
+
995
+ /** @returns current settings, re-rendering on change. */
996
+ function useSettings() {
997
+ return useSyncExternalStore(subscribeSettings, getSettings)
998
+ }
999
+
1000
+ /** @param amount - non-negative CNY. @returns display text. */
1001
+ function formatCny(amount) {
1002
+ if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
1003
+ const digits = amount > 0 && amount < 0.0001 ? 5 : amount > 0 && amount < 0.01 ? 4 : 2
1004
+ try {
1005
+ return new Intl.NumberFormat(undefined, {
1006
+ style: 'currency',
1007
+ currency: 'CNY',
1008
+ minimumFractionDigits: digits,
1009
+ maximumFractionDigits: digits,
1010
+ }).format(amount)
1011
+ } catch {
1012
+ return `¥${amount.toFixed(digits)}`
1013
+ }
1014
+ }
1015
+
1016
+ /** @param amount - non-negative CNY. @returns a cost value with four decimals (five below ¥0.0001). */
1017
+ function formatCost(amount) {
1018
+ if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
1019
+ const digits = amount > 0 && amount < 0.0001 ? 5 : 4
1020
+ try {
1021
+ return new Intl.NumberFormat(undefined, {
1022
+ style: 'currency',
1023
+ currency: 'CNY',
1024
+ minimumFractionDigits: digits,
1025
+ maximumFractionDigits: digits,
1026
+ }).format(amount)
1027
+ } catch {
1028
+ return `¥${amount.toFixed(digits)}`
1029
+ }
1030
+ }
1031
+
1032
+ /** @param tokens - non-negative count. @returns display text. */
1033
+ function formatTokens(tokens) {
1034
+ if (typeof tokens !== 'number' || !Number.isFinite(tokens)) return '—'
1035
+ try {
1036
+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(tokens)
1037
+ } catch {
1038
+ return String(Math.round(tokens))
1039
+ }
1040
+ }
1041
+
1042
+ /** @param rate - CNY per million tokens. @returns CNY per million tokens. */
1043
+ function formatRate(rate) {
1044
+ return formatCny(rate)
1045
+ }
1046
+
1047
+ /** @param value - threshold number. @returns a plain editable string. */
1048
+ function formatInput(value, metric) {
1049
+ return metric === 'cost' ? String(value) : String(Math.round(value))
1050
+ }
1051
+
1052
+ /** The bundle's stylesheet as one React element, removed with the surface. */
1053
+ function StyleTag() {
1054
+ return h('style', { 'data-plugin-css': NAME }, CSS)
1055
+ }
1056
+
1057
+ /** One label/value row of the panel. */
1058
+ function Line({ label, value, emphasis }) {
1059
+ return h(
1060
+ 'div',
1061
+ { className: 'dshTurnCost_line', 'data-emphasis': emphasis === true ? 'true' : undefined },
1062
+ h('span', { className: 'dshTurnCost_label' }, label),
1063
+ h('span', { className: 'dshTurnCost_value' }, value),
1064
+ )
1065
+ }
1066
+
1067
+ /** One threshold number field; commits a valid value on blur or Enter. */
1068
+ function NumberField({ label, value, unit, metric, onCommit }) {
1069
+ const [draft, setDraft] = useState(() => formatInput(value, metric))
1070
+ const cancelRef = useRef(false)
1071
+ useEffect(() => {
1072
+ setDraft(formatInput(value, metric))
1073
+ }, [value, metric])
1074
+ const reset = () => {
1075
+ setDraft(formatInput(value, metric))
1076
+ }
1077
+ const commit = () => {
1078
+ if (cancelRef.current) {
1079
+ cancelRef.current = false
1080
+ reset()
1081
+ return
1082
+ }
1083
+ const text = draft.trim()
1084
+ if (text === '') {
1085
+ reset()
1086
+ return
1087
+ }
1088
+ const parsed = Number(text.replace(',', '.'))
1089
+ if (Number.isFinite(parsed) && parsed >= 0) {
1090
+ onCommit(parsed)
1091
+ } else {
1092
+ reset()
1093
+ }
1094
+ }
1095
+ return h(
1096
+ 'label',
1097
+ { className: 'dshTurnCost_field' },
1098
+ h('span', { className: 'dshTurnCost_fieldLabel' }, label),
1099
+ h(
1100
+ 'span',
1101
+ { className: 'dshTurnCost_inputWrap' },
1102
+ h('input', {
1103
+ className: 'dshTurnCost_input',
1104
+ type: 'number',
1105
+ min: '0',
1106
+ step: metric === 'cost' ? '0.01' : '1',
1107
+ inputMode: 'decimal',
1108
+ value: draft,
1109
+ onChange: (event) => {
1110
+ cancelRef.current = false
1111
+ setDraft(event.target.value)
1112
+ },
1113
+ onBlur: commit,
1114
+ onKeyDown: (event) => {
1115
+ if (event.key === 'Enter') {
1116
+ event.preventDefault()
1117
+ event.currentTarget.blur()
1118
+ } else if (event.key === 'Escape') {
1119
+ event.preventDefault()
1120
+ event.stopPropagation()
1121
+ cancelRef.current = true
1122
+ reset()
1123
+ event.currentTarget.blur()
1124
+ }
1125
+ },
1126
+ }),
1127
+ h('span', { className: 'dshTurnCost_unit' }, unit),
1128
+ ),
1129
+ )
1130
+ }
1131
+
1132
+ /** One option of the metric switch. */
1133
+ function MetricButton({ active, children, onClick }) {
1134
+ return h(
1135
+ 'button',
1136
+ {
1137
+ type: 'button',
1138
+ className: 'dshTurnCost_segBtn',
1139
+ 'data-active': active ? 'true' : 'false',
1140
+ 'aria-pressed': active,
1141
+ onClick,
1142
+ },
1143
+ children,
1144
+ )
1145
+ }
1146
+
1147
+ /**
1148
+ * The hover/focus panel: the selected display value, the next-turn
1149
+ * context estimate, the continue/fresh split, and (when pinned) the
1150
+ * display switch and thresholds.
1151
+ */
1152
+ function Panel({
1153
+ estimate,
1154
+ turnsLabel,
1155
+ settings,
1156
+ priceSource,
1157
+ holidaySource,
1158
+ tariffTime,
1159
+ t,
1160
+ pinned,
1161
+ onUnpin,
1162
+ onMetric,
1163
+ onThreshold,
1164
+ onReset,
1165
+ onMouseEnter,
1166
+ onMouseLeave,
1167
+ }) {
1168
+ const metricLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
1169
+ const green = settings.metric === 'cost' ? settings.costGreen : settings.turnsGreen
1170
+ const yellow = settings.metric === 'cost' ? settings.costYellow : settings.turnsYellow
1171
+ const greenText =
1172
+ settings.metric === 'cost'
1173
+ ? formatCny(green)
1174
+ : `${Math.round(green)} ${t('settings.unitTurns')}`
1175
+ const yellowText =
1176
+ settings.metric === 'cost'
1177
+ ? formatCny(yellow)
1178
+ : `${Math.round(yellow)} ${t('settings.unitTurns')}`
1179
+ const current =
1180
+ settings.metric === 'cost'
1181
+ ? estimate.priced && estimate.extraCny !== undefined
1182
+ ? `≈ ${formatCost(estimate.extraCny)}`
1183
+ : '—'
1184
+ : turnsLabel
1185
+ const tariff = estimate.peak ? t('tariff.peak') : t('tariff.off')
1186
+ const modelText =
1187
+ estimate.model === undefined
1188
+ ? t('panel.noModel')
1189
+ : estimate.priced
1190
+ ? `${estimate.model} · ${tariff}`
1191
+ : estimate.model
1192
+
1193
+ const rows = [
1194
+ h(Line, { key: 'turns', label: t('panel.turns'), value: turnsLabel }),
1195
+ h(Line, {
1196
+ key: 'extra',
1197
+ label: t('panel.extra'),
1198
+ value:
1199
+ estimate.priced && estimate.extraCny !== undefined
1200
+ ? `≈ ${formatCost(estimate.extraCny)}`
1201
+ : '—',
1202
+ emphasis: true,
1203
+ }),
1204
+ h('div', { key: 'split', className: 'dshTurnCost_divider' }),
1205
+ h(Line, {
1206
+ key: 'continue',
1207
+ label: t('panel.continue'),
1208
+ value: estimate.totalCny === undefined ? '—' : `≈ ${formatCost(estimate.totalCny)}`,
1209
+ }),
1210
+ h(Line, {
1211
+ key: 'fresh',
1212
+ label: t('panel.fresh'),
1213
+ value: estimate.freshCny === undefined ? '—' : `≈ ${formatCost(estimate.freshCny)}`,
1214
+ }),
1215
+ h('div', { key: 'factDivider', className: 'dshTurnCost_divider' }),
1216
+ h(Line, {
1217
+ key: 'history',
1218
+ label: t('panel.history'),
1219
+ value: estimate.hasContext ? `≈ ${formatTokens(estimate.historyTokens)} ${t('panel.tokens')}` : '—',
1220
+ }),
1221
+ h(Line, {
1222
+ key: 'prompt',
1223
+ label: t('panel.prompt'),
1224
+ value: estimate.hasContext ? `${formatTokens(estimate.promptTokens)} ${t('panel.tokens')}` : '—',
1225
+ }),
1226
+ h(Line, {
1227
+ key: 'rate',
1228
+ label: estimate.measured ? t('panel.rateMeasured') : t('panel.rateReference'),
1229
+ value: estimate.rate === undefined ? '—' : `${formatRate(estimate.rate)} ${t('panel.perMillion')}`,
1230
+ }),
1231
+ h(Line, { key: 'model', label: t('panel.model'), value: modelText }),
1232
+ h(Line, {
1233
+ key: 'tariff',
1234
+ label: t('panel.tariff'),
1235
+ value: `${tariff} · ${t('panel.beijingTime')} ${tariffTime}`,
1236
+ }),
1237
+ h('div', { key: 'tariffRule', className: 'dshTurnCost_note' }, t('panel.tariffRule')),
1238
+ h(Line, {
1239
+ key: 'priceSource',
1240
+ label: t('panel.priceTable'),
1241
+ value:
1242
+ priceSource === 'online'
1243
+ ? t('panel.priceOnline')
1244
+ : priceSource === 'cache'
1245
+ ? t('panel.priceCache')
1246
+ : t('panel.priceBuiltin'),
1247
+ }),
1248
+ h(Line, {
1249
+ key: 'holidaySource',
1250
+ label: t('panel.holidayTable'),
1251
+ value:
1252
+ holidaySource === 'online'
1253
+ ? t('panel.holidayOnline')
1254
+ : holidaySource === 'cache'
1255
+ ? t('panel.holidayCache')
1256
+ : t('panel.holidayBuiltin'),
1257
+ }),
1258
+ ]
1259
+
1260
+ const displaySwitch = pinned
1261
+ ? h(
1262
+ 'div',
1263
+ { className: 'dshTurnCost_displayRow' },
1264
+ h('span', { className: 'dshTurnCost_displayLabel' }, t('panel.colorBy')),
1265
+ h(
1266
+ 'div',
1267
+ { className: 'dshTurnCost_seg', role: 'group', 'aria-label': t('panel.colorBy') },
1268
+ h(
1269
+ MetricButton,
1270
+ {
1271
+ active: settings.metric === 'turns',
1272
+ onClick: () => {
1273
+ onMetric('turns')
1274
+ },
1275
+ },
1276
+ t('settings.turns'),
1277
+ ),
1278
+ h(
1279
+ MetricButton,
1280
+ {
1281
+ active: settings.metric === 'cost',
1282
+ onClick: () => {
1283
+ onMetric('cost')
1284
+ },
1285
+ },
1286
+ t('settings.cost'),
1287
+ ),
1288
+ ),
1289
+ )
1290
+ : null
1291
+
1292
+ const settingsBlock = pinned
1293
+ ? h(
1294
+ 'div',
1295
+ { className: 'dshTurnCost_settings' },
1296
+ h('div', { className: 'dshTurnCost_settingsTitle' }, t('settings.title')),
1297
+ h(NumberField, {
1298
+ key: `green-${settings.metric}`,
1299
+ label: t('settings.green'),
1300
+ value: green,
1301
+ unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
1302
+ metric: settings.metric,
1303
+ onCommit: (value) => {
1304
+ onThreshold('green', value)
1305
+ },
1306
+ }),
1307
+ h(NumberField, {
1308
+ key: `yellow-${settings.metric}`,
1309
+ label: t('settings.yellow'),
1310
+ value: yellow,
1311
+ unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
1312
+ metric: settings.metric,
1313
+ onCommit: (value) => {
1314
+ onThreshold('yellow', value)
1315
+ },
1316
+ }),
1317
+ h(
1318
+ 'div',
1319
+ { className: 'dshTurnCost_settingsFoot' },
1320
+ h('span', null, t('settings.hint')),
1321
+ h(
1322
+ 'button',
1323
+ {
1324
+ type: 'button',
1325
+ className: 'dshTurnCost_reset',
1326
+ onClick: onReset,
1327
+ },
1328
+ t('settings.reset'),
1329
+ ),
1330
+ ),
1331
+ )
1332
+ : null
1333
+
1334
+ return h(
1335
+ 'div',
1336
+ {
1337
+ className: 'dshTurnCost_panel',
1338
+ id: 'dsh-turn-cost-detail',
1339
+ role: pinned ? 'dialog' : 'tooltip',
1340
+ 'aria-label': t('chip.title'),
1341
+ 'data-pinned': pinned ? 'true' : 'false',
1342
+ onMouseEnter,
1343
+ onMouseLeave,
1344
+ },
1345
+ h(
1346
+ 'div',
1347
+ { className: 'dshTurnCost_header' },
1348
+ h('span', { className: 'dshTurnCost_headerTitle' }, t('panel.title')),
1349
+ pinned
1350
+ ? h(
1351
+ 'button',
1352
+ { type: 'button', className: 'dshTurnCost_unpin', onClick: onUnpin },
1353
+ t('settings.unpin'),
1354
+ )
1355
+ : null,
1356
+ ),
1357
+ displaySwitch,
1358
+ ...rows,
1359
+ estimate.hasContext
1360
+ ? !estimate.priced && estimate.model !== undefined
1361
+ ? h('div', { className: 'dshTurnCost_note dshTurnCost_alert' }, t('panel.noPrice'))
1362
+ : null
1363
+ : h('div', { className: 'dshTurnCost_note dshTurnCost_alert' }, t('panel.noContext')),
1364
+ estimate.hasContext && estimate.priced && !estimate.hasUsage
1365
+ ? h('div', { className: 'dshTurnCost_note' }, t('panel.waiting'))
1366
+ : null,
1367
+ h(
1368
+ 'div',
1369
+ { className: 'dshTurnCost_stage' },
1370
+ h(Line, { label: t('panel.colorBy'), value: metricLabel }),
1371
+ h(Line, { label: t('panel.current'), value: current }),
1372
+ h(
1373
+ 'div',
1374
+ { className: 'dshTurnCost_stageText' },
1375
+ `${t('panel.leq')}${greenText} ${t('tone.green')} · ${t('panel.leq')}${yellowText} ${t(
1376
+ 'tone.yellow',
1377
+ )} · ${t('panel.gt')}${yellowText} ${t('tone.red')}`,
1378
+ ),
1379
+ ),
1380
+ h('div', { className: 'dshTurnCost_note' }, t('panel.note')),
1381
+ pinned ? settingsBlock : h('div', { className: 'dshTurnCost_pinHint' }, t('settings.pinHint')),
1382
+ )
1383
+ }
1384
+
1385
+ /**
1386
+ * Compact chip plus its hover panel. Clicking the chip pins the panel so
1387
+ * the threshold fields can receive pointer and keyboard input.
1388
+ */
1389
+ function TurnCostChip({ useProjection, t }) {
1390
+ const settings = useSettings()
1391
+ const priceInfo = usePrices()
1392
+ const holidayInfo = useHolidays()
1393
+ const [hovered, setHovered] = useState(false)
1394
+ const [pinned, setPinned] = useState(false)
1395
+ const [focusWithin, setFocusWithin] = useState(false)
1396
+ const [, setClock] = useState(0)
1397
+ const anchorRef = useRef(null)
1398
+ const chipRef = useRef(null)
1399
+ const closeTimer = useRef(0)
1400
+ const suppressFocus = useRef(false)
1401
+
1402
+ useEffect(
1403
+ () => () => {
1404
+ if (closeTimer.current !== 0) window.clearTimeout(closeTimer.current)
1405
+ },
1406
+ [],
1407
+ )
1408
+
1409
+ const dismiss = () => {
1410
+ if (closeTimer.current !== 0) {
1411
+ window.clearTimeout(closeTimer.current)
1412
+ closeTimer.current = 0
1413
+ }
1414
+ setPinned(false)
1415
+ setHovered(false)
1416
+ setFocusWithin(false)
1417
+ const chip = chipRef.current
1418
+ if (chip !== null && document.activeElement !== chip) {
1419
+ suppressFocus.current = true
1420
+ chip.focus()
1421
+ }
1422
+ }
1423
+
1424
+ useEffect(() => {
1425
+ if (!pinned) return undefined
1426
+ const onPointerDown = (event) => {
1427
+ const anchor = anchorRef.current
1428
+ if (anchor !== null && !anchor.contains(event.target)) {
1429
+ setPinned(false)
1430
+ setHovered(false)
1431
+ setFocusWithin(false)
1432
+ }
1433
+ }
1434
+ const onKeyDown = (event) => {
1435
+ if (event.key === 'Escape') dismiss()
1436
+ }
1437
+ document.addEventListener('pointerdown', onPointerDown, true)
1438
+ document.addEventListener('keydown', onKeyDown)
1439
+ return () => {
1440
+ document.removeEventListener('pointerdown', onPointerDown, true)
1441
+ document.removeEventListener('keydown', onKeyDown)
1442
+ }
1443
+ }, [pinned])
1444
+
1445
+ const cancelClose = () => {
1446
+ if (closeTimer.current !== 0) {
1447
+ window.clearTimeout(closeTimer.current)
1448
+ closeTimer.current = 0
1449
+ }
1450
+ if (priceInfo.source !== 'online') void refreshPrices()
1451
+ if (holidayInfo.source !== 'online') void refreshHolidays()
1452
+ setHovered(true)
1453
+ }
1454
+ const scheduleClose = () => {
1455
+ if (closeTimer.current !== 0) window.clearTimeout(closeTimer.current)
1456
+ closeTimer.current = window.setTimeout(() => {
1457
+ closeTimer.current = 0
1458
+ setHovered(false)
1459
+ }, 240)
1460
+ }
1461
+
1462
+ const useP = typeof useProjection === 'function' ? useProjection : () => undefined
1463
+ const stats = useP('sessionStats')
1464
+ const usage = useP('tokenUsage')
1465
+ const breakdown = useP('contextBreakdown')
1466
+ const pressure = useP('contextPressure')
1467
+ const selection = useP('modelSelection')
1468
+
1469
+ const rawTurns = stats?.turns
1470
+ const turns = typeof rawTurns === 'number' && Number.isFinite(rawTurns) && rawTurns >= 0 ? Math.floor(rawTurns) : 0
1471
+ const now = new Date()
1472
+ const peak = isPeakTariff(now)
1473
+ let tariffTime = ''
1474
+ try {
1475
+ tariffTime = beijingClock(now).timeKey
1476
+ } catch {
1477
+ tariffTime = ''
1478
+ }
1479
+ const estimate = estimateNextTurn({ usage, breakdown, pressure, selection, peak })
1480
+ const tone = toneOf(settings, turns, estimate, stats !== undefined)
1481
+ const open = hovered || pinned || focusWithin
1482
+ /**
1483
+ * Keep the displayed tariff honest without polling blindly: wake up at
1484
+ * the exact next change (window edge or midnight, so weekends and
1485
+ * holidays flip too), fall back to a 30 s poll, and recompute as soon
1486
+ * as the window is visible again after sleep, minimise or a background
1487
+ * tab — the case where a stale "谷价" used to survive into peak hours.
1488
+ */
1489
+ useEffect(() => {
1490
+ let timer = 0
1491
+ let disposed = false
1492
+ const schedule = () => {
1493
+ if (disposed) return
1494
+ if (timer !== 0) window.clearTimeout(timer)
1495
+ const delay = Math.min(30_000, Math.max(500, msUntilNextTariffChange() + 400))
1496
+ timer = window.setTimeout(() => {
1497
+ if (disposed) return
1498
+ setClock((value) => value + 1)
1499
+ schedule()
1500
+ }, delay)
1501
+ }
1502
+ const refreshNow = () => {
1503
+ setClock((value) => value + 1)
1504
+ schedule()
1505
+ }
1506
+ const onVisibility = () => {
1507
+ if (document.visibilityState === 'visible') refreshNow()
1508
+ }
1509
+ document.addEventListener('visibilitychange', onVisibility)
1510
+ window.addEventListener('focus', refreshNow)
1511
+ window.addEventListener('pageshow', refreshNow)
1512
+ schedule()
1513
+ return () => {
1514
+ disposed = true
1515
+ if (timer !== 0) window.clearTimeout(timer)
1516
+ document.removeEventListener('visibilitychange', onVisibility)
1517
+ window.removeEventListener('focus', refreshNow)
1518
+ window.removeEventListener('pageshow', refreshNow)
1519
+ }
1520
+ }, [])
1521
+ const turnsLabel = stats === undefined ? t('chip.turnsLoading') : `${turns} ${t('chip.unit')}`
1522
+ const costLabel =
1523
+ estimate.hasContext && estimate.priced && estimate.extraCny !== undefined
1524
+ ? `≈ ${formatCost(estimate.extraCny)}`
1525
+ : t('chip.costUnknown')
1526
+ const valueLabel = settings.metric === 'cost' ? costLabel : turnsLabel
1527
+ const toneText =
1528
+ tone === 'green'
1529
+ ? t('tone.green')
1530
+ : tone === 'yellow'
1531
+ ? t('tone.yellow')
1532
+ : tone === 'red'
1533
+ ? t('tone.red')
1534
+ : t('tone.idle')
1535
+ const basisLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
1536
+ const tariffLabel = peak ? t('tariff.peak') : t('tariff.off')
1537
+ const tariffBadge = peak ? t('tariff.peakShort') : t('tariff.offShort')
1538
+ const summary = `${t('chip.title')} · ${valueLabel} · ${tariffLabel} · ${t('panel.colorBy')}: ${basisLabel} (${toneText}) · ${t('chip.pinHint')}`
1539
+
1540
+ const updateMetric = (metric) => {
1541
+ publishSettings({ ...settings, metric })
1542
+ }
1543
+ const updateThreshold = (field, value) => {
1544
+ if (settings.metric === 'cost') {
1545
+ if (field === 'green') {
1546
+ publishSettings({
1547
+ ...settings,
1548
+ costGreen: value,
1549
+ costYellow: Math.max(settings.costYellow, value),
1550
+ })
1551
+ } else {
1552
+ publishSettings({
1553
+ ...settings,
1554
+ costYellow: Math.max(settings.costGreen, value),
1555
+ })
1556
+ }
1557
+ } else if (field === 'green') {
1558
+ publishSettings({
1559
+ ...settings,
1560
+ turnsGreen: value,
1561
+ turnsYellow: Math.max(settings.turnsYellow, value),
1562
+ })
1563
+ } else {
1564
+ publishSettings({
1565
+ ...settings,
1566
+ turnsYellow: Math.max(settings.turnsGreen, value),
1567
+ })
1568
+ }
1569
+ }
1570
+ const resetSettings = () => {
1571
+ publishSettings({ ...DEFAULT_SETTINGS, metric: settings.metric })
1572
+ }
1573
+
1574
+ return h(
1575
+ 'span',
1576
+ {
1577
+ ref: anchorRef,
1578
+ className: 'dshTurnCost_anchor',
1579
+ onMouseEnter: cancelClose,
1580
+ onMouseLeave: scheduleClose,
1581
+ onFocusCapture: () => {
1582
+ if (suppressFocus.current) {
1583
+ suppressFocus.current = false
1584
+ return
1585
+ }
1586
+ setFocusWithin(true)
1587
+ cancelClose()
1588
+ },
1589
+ onBlurCapture: (event) => {
1590
+ if (!event.currentTarget.contains(event.relatedTarget)) setFocusWithin(false)
1591
+ },
1592
+ onKeyDown: (event) => {
1593
+ if (event.key === 'Escape') dismiss()
1594
+ },
1595
+ },
1596
+ h(StyleTag, { key: 'style' }),
1597
+ h(
1598
+ 'span',
1599
+ {
1600
+ key: 'chip',
1601
+ className: 'dshTurnCost_chip',
1602
+ 'data-tone': tone,
1603
+ },
1604
+ h(
1605
+ 'button',
1606
+ {
1607
+ ref: chipRef,
1608
+ type: 'button',
1609
+ className: 'dshTurnCost_main',
1610
+ title: summary,
1611
+ 'aria-label': summary,
1612
+ 'aria-expanded': open,
1613
+ 'aria-controls': open ? 'dsh-turn-cost-detail' : undefined,
1614
+ 'aria-describedby': open ? 'dsh-turn-cost-detail' : undefined,
1615
+ onClick: () => {
1616
+ if (pinned) {
1617
+ dismiss()
1618
+ } else {
1619
+ setPinned(true)
1620
+ cancelClose()
1621
+ }
1622
+ },
1623
+ },
1624
+ h('span', { className: 'dshTurnCost_dot', 'aria-hidden': true }),
1625
+ h('span', { className: 'dshTurnCost_amount' }, valueLabel),
1626
+ h(
1627
+ 'span',
1628
+ {
1629
+ className: 'dshTurnCost_tariff',
1630
+ 'data-tariff': peak ? 'peak' : 'off',
1631
+ 'aria-hidden': true,
1632
+ },
1633
+ tariffBadge,
1634
+ ),
1635
+ ),
1636
+ ),
1637
+ open
1638
+ ? h(Panel, {
1639
+ key: 'panel',
1640
+ estimate,
1641
+ turnsLabel,
1642
+ settings,
1643
+ priceSource: priceInfo.source,
1644
+ holidaySource: holidayInfo.source,
1645
+ tariffTime,
1646
+ t,
1647
+ pinned,
1648
+ onUnpin: dismiss,
1649
+ onMetric: updateMetric,
1650
+ onThreshold: updateThreshold,
1651
+ onReset: resetSettings,
1652
+ onMouseEnter: cancelClose,
1653
+ onMouseLeave: scheduleClose,
1654
+ })
1655
+ : null,
1656
+ )
1657
+ }
1658
+
1659
+ const inject = ['slots', 'locale']
1660
+
1661
+ /** @param ctx - the page plugin's context (slots, locale, effects). */
1662
+ function apply(ctx) {
1663
+ ctx.effect(() => ctx.locale.register(NS, 'zh', ZH), 'dsh-continue-cost: zh dictionary')
1664
+ ctx.effect(() => ctx.locale.register(NS, 'en', EN), 'dsh-continue-cost: en dictionary')
1665
+ const t = ctx.locale.bind(NS)
1666
+
1667
+ /* Thresholds are shared through localStorage, so a second window or tab
1668
+ * picks up a change without a reload. Echo suppression comes from
1669
+ * comparing the normalized value before writing again. */
1670
+ ctx.effect(() => {
1671
+ const onStorage = (event) => {
1672
+ if (event.key !== STORAGE_KEY) return
1673
+ let parsed
1674
+ try {
1675
+ parsed = event.newValue === null ? undefined : JSON.parse(event.newValue)
1676
+ } catch {
1677
+ return
1678
+ }
1679
+ const next = normalizeSettings(parsed)
1680
+ if (JSON.stringify(next) === JSON.stringify(getSettings())) return
1681
+ publishSettings(next)
1682
+ }
1683
+ window.addEventListener('storage', onStorage)
1684
+ return () => {
1685
+ window.removeEventListener('storage', onStorage)
1686
+ }
1687
+ }, 'dsh-continue-cost: threshold sync')
1688
+
1689
+ ctx.effect(() => {
1690
+ void refreshPrices()
1691
+ void refreshHolidays()
1692
+ const timer = window.setInterval(() => {
1693
+ void refreshPrices()
1694
+ void refreshHolidays()
1695
+ }, 24 * 60 * 60 * 1000)
1696
+ return () => {
1697
+ window.clearInterval(timer)
1698
+ }
1699
+ }, 'dsh-continue-cost: official price and holiday refresh')
1700
+
1701
+ ctx.slots.inject('conversation.input.right', function* () {
1702
+ yield ctx.slots.register(
1703
+ {
1704
+ name: 'conversation.input.right',
1705
+ id: 'turn-cost-meter',
1706
+ order: 21,
1707
+ label: () => t('chip.title'),
1708
+ inject: () => ({ t }),
1709
+ },
1710
+ TurnCostChip,
1711
+ )
1712
+ })
1713
+ }
1714
+
1715
+ module.exports = { apply, inject, name: NAME }
1716
+ return module.exports
1717
+ }
1718
+ }
1719
+
1720
+ window.__ModuleLoader__.load({
1721
+ id: NAME,
1722
+ factory: makeFactory(),
1723
+ })
1724
+ })()