dsh-continue-cost 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +131 -2
- package/client.js +1549 -0
- package/cordis.patch.yml +9 -0
- package/host-1.2.0.js +512 -0
- package/host.js +6 -0
- package/icon.svg +8 -0
- package/index.js +4 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +62 -4
package/client.js
ADDED
|
@@ -0,0 +1,1549 @@
|
|
|
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.noPrice': '未收录该模型价格',
|
|
268
|
+
'panel.noContext': '上下文数据还没准备好,暂时无法估算历史占比。',
|
|
269
|
+
'panel.waiting': '还没有可用的 token 用量,先按未命中缓存的单价估算。',
|
|
270
|
+
'panel.note': '分别估算继续和新开的上下文费用(系统提示、工具 schema、历史消息);回答本身费用两边相同,所以差额来自历史消息。按缓存命中比例估算,实际可能更低;以账单为准。',
|
|
271
|
+
'panel.colorBy': '显示与着色',
|
|
272
|
+
'panel.current': '当前显示值',
|
|
273
|
+
'panel.leq': '≤',
|
|
274
|
+
'panel.gt': '>',
|
|
275
|
+
'tone.green': '绿',
|
|
276
|
+
'tone.yellow': '黄',
|
|
277
|
+
'tone.red': '红',
|
|
278
|
+
'tone.idle': '等待数据',
|
|
279
|
+
'tariff.peak': '峰时',
|
|
280
|
+
'tariff.off': '谷时',
|
|
281
|
+
'settings.title': '阈值设置',
|
|
282
|
+
'settings.turns': '对话轮数',
|
|
283
|
+
'settings.cost': '多花金额',
|
|
284
|
+
'settings.green': '绿色上限',
|
|
285
|
+
'settings.yellow': '黄色上限',
|
|
286
|
+
'settings.unitTurns': '轮',
|
|
287
|
+
'settings.unitCost': '元',
|
|
288
|
+
'settings.hint': '胶囊显示所选项,并按同一个数值着色:不超过绿色上限为绿,不超过黄色上限为黄,超过为红;两项自动保持先后顺序。',
|
|
289
|
+
'settings.reset': '恢复默认',
|
|
290
|
+
'settings.unpin': '收起',
|
|
291
|
+
'settings.pinHint': '点击胶囊固定面板后即可切换显示和调整阈值。',
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const EN = {
|
|
295
|
+
'chip.title': 'Turn count & carry-over delta',
|
|
296
|
+
'chip.unit': 'turns',
|
|
297
|
+
'chip.turnsLoading': 'Turns …',
|
|
298
|
+
'chip.costUnknown': '¥ —',
|
|
299
|
+
'chip.pinHint': 'Hover for the estimate; click the chip to pin and adjust display/thresholds',
|
|
300
|
+
'panel.title': 'Carry-over delta estimate',
|
|
301
|
+
'panel.turns': 'Completed turns',
|
|
302
|
+
'panel.extra': 'Delta (continue − fresh)',
|
|
303
|
+
'panel.continue': 'Continue this chat (next-turn context)',
|
|
304
|
+
'panel.fresh': 'Fresh chat (same-turn context)',
|
|
305
|
+
'panel.history': 'History context',
|
|
306
|
+
'panel.prompt': 'Next-turn context estimate',
|
|
307
|
+
'panel.tokens': 'tokens',
|
|
308
|
+
'panel.rateMeasured': 'Session average token rate',
|
|
309
|
+
'panel.rateReference': 'Reference token rate (cache miss)',
|
|
310
|
+
'panel.model': 'Priced model',
|
|
311
|
+
'panel.noModel': 'No model selected',
|
|
312
|
+
'panel.priceTable': 'Price table',
|
|
313
|
+
'panel.priceOnline': 'Official online',
|
|
314
|
+
'panel.priceCache': 'Local cache',
|
|
315
|
+
'panel.priceBuiltin': 'Built-in',
|
|
316
|
+
'panel.holidayTable': 'Holiday table',
|
|
317
|
+
'panel.holidayOnline': 'Official online',
|
|
318
|
+
'panel.holidayCache': 'Local cache',
|
|
319
|
+
'panel.holidayBuiltin': 'Built-in',
|
|
320
|
+
'panel.perMillion': '/ 1M tokens',
|
|
321
|
+
'panel.noPrice': 'No listed price for this model',
|
|
322
|
+
'panel.noContext': 'Context data is not ready yet; the history share is unknown for now.',
|
|
323
|
+
'panel.waiting': 'No token usage yet; pricing the history at the cache-miss rate.',
|
|
324
|
+
'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.',
|
|
325
|
+
'panel.colorBy': 'Display & color',
|
|
326
|
+
'panel.current': 'Current display',
|
|
327
|
+
'panel.leq': '≤',
|
|
328
|
+
'panel.gt': '>',
|
|
329
|
+
'tone.green': 'green',
|
|
330
|
+
'tone.yellow': 'yellow',
|
|
331
|
+
'tone.red': 'red',
|
|
332
|
+
'tone.idle': 'waiting for data',
|
|
333
|
+
'tariff.peak': 'peak',
|
|
334
|
+
'tariff.off': 'off-peak',
|
|
335
|
+
'settings.title': 'Thresholds',
|
|
336
|
+
'settings.turns': 'Turns',
|
|
337
|
+
'settings.cost': 'Extra cost',
|
|
338
|
+
'settings.green': 'Green up to',
|
|
339
|
+
'settings.yellow': 'Yellow up to',
|
|
340
|
+
'settings.unitTurns': 'turns',
|
|
341
|
+
'settings.unitCost': 'CNY',
|
|
342
|
+
'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.',
|
|
343
|
+
'settings.reset': 'Reset',
|
|
344
|
+
'settings.unpin': 'Close',
|
|
345
|
+
'settings.pinHint': 'Click the chip to pin the panel, then switch the display and adjust thresholds.',
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** @param value - candidate number. @returns a finite non-negative number, else the fallback. */
|
|
349
|
+
function nonNegative(value, fallback) {
|
|
350
|
+
const parsed = typeof value === 'number' ? value : Number(value)
|
|
351
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Coerce one stored settings object, keeping every threshold valid and the
|
|
356
|
+
* yellow limit at or above the green one.
|
|
357
|
+
* @param raw - parsed localStorage value.
|
|
358
|
+
* @returns complete settings.
|
|
359
|
+
*/
|
|
360
|
+
function normalizeSettings(raw) {
|
|
361
|
+
const source = raw !== null && typeof raw === 'object' ? raw : {}
|
|
362
|
+
const metric = source.metric === 'cost' ? 'cost' : 'turns'
|
|
363
|
+
const turnsGreen = Math.round(nonNegative(source.turnsGreen, DEFAULT_SETTINGS.turnsGreen))
|
|
364
|
+
const turnsYellow = Math.max(
|
|
365
|
+
turnsGreen,
|
|
366
|
+
Math.round(nonNegative(source.turnsYellow, DEFAULT_SETTINGS.turnsYellow)),
|
|
367
|
+
)
|
|
368
|
+
const costGreen = nonNegative(source.costGreen, DEFAULT_SETTINGS.costGreen)
|
|
369
|
+
const costYellow = Math.max(costGreen, nonNegative(source.costYellow, DEFAULT_SETTINGS.costYellow))
|
|
370
|
+
return { metric, turnsGreen, turnsYellow, costGreen, costYellow }
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** @returns settings remembered by this browser, or the defaults. */
|
|
374
|
+
function readSettings() {
|
|
375
|
+
try {
|
|
376
|
+
const raw = window.localStorage.getItem(STORAGE_KEY)
|
|
377
|
+
return raw === null ? normalizeSettings(undefined) : normalizeSettings(JSON.parse(raw))
|
|
378
|
+
} catch {
|
|
379
|
+
return normalizeSettings(undefined)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Read one non-negative finite count out of a projection value that crossed
|
|
385
|
+
* the wire, so a malformed bucket cannot become a fake cost.
|
|
386
|
+
* @param value - candidate from the projection.
|
|
387
|
+
* @returns the count, or 0.
|
|
388
|
+
*/
|
|
389
|
+
function countOf(value) {
|
|
390
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Resolve the list price of the route serving this conversation. The route
|
|
395
|
+
* may be addressed with a provider prefix, so both spellings resolve.
|
|
396
|
+
* @param selection - `modelSelection` projection.
|
|
397
|
+
* @returns that model's tariffs, or undefined.
|
|
398
|
+
*/
|
|
399
|
+
function pricingOf(selection) {
|
|
400
|
+
const raw = selection?.next?.model ?? selection?.lastUsed?.model
|
|
401
|
+
if (typeof raw !== 'string' || raw === '') return undefined
|
|
402
|
+
const slash = raw.lastIndexOf('/')
|
|
403
|
+
const bare = slash === -1 ? raw : raw.slice(slash + 1)
|
|
404
|
+
const bareKey = bare.toLowerCase()
|
|
405
|
+
const fullKey = raw.toLowerCase()
|
|
406
|
+
const id = PRICING[bareKey] === undefined ? fullKey : bareKey
|
|
407
|
+
const alias = PRICING_ALIASES[id]
|
|
408
|
+
return PRICING[id] ?? (alias === undefined ? undefined : PRICING[alias])
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** @returns the bare model id serving the conversation, or undefined. */
|
|
412
|
+
function modelOf(selection) {
|
|
413
|
+
const raw = selection?.next?.model ?? selection?.lastUsed?.model
|
|
414
|
+
if (typeof raw !== 'string' || raw === '') return undefined
|
|
415
|
+
const slash = raw.lastIndexOf('/')
|
|
416
|
+
return slash === -1 ? raw : raw.slice(slash + 1)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Which provider tariff is in force now: peak 09:00-12:00 and 14:00-18:00
|
|
421
|
+
* Beijing time on weekdays, off-peak on weekends, make-up working weekends,
|
|
422
|
+
* and Chinese public holidays. The holiday table covers 2026 plus the fixed
|
|
423
|
+
* New Year / Labour Day / National Day dates for later years.
|
|
424
|
+
* @param now - instant to classify.
|
|
425
|
+
* @returns true for peak.
|
|
426
|
+
*/
|
|
427
|
+
function isPeakTariff(now = new Date()) {
|
|
428
|
+
try {
|
|
429
|
+
const beijing = new Date(now.getTime() + 8 * 60 * 60 * 1000)
|
|
430
|
+
const day = beijing.getUTCDay()
|
|
431
|
+
if (day === 0 || day === 6) return false
|
|
432
|
+
const dateKey = beijing.toISOString().slice(0, 10)
|
|
433
|
+
if (isChineseHoliday(dateKey)) return false
|
|
434
|
+
const hour = beijing.getUTCHours()
|
|
435
|
+
return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
|
|
436
|
+
} catch {
|
|
437
|
+
return true
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Estimate the next turn's input side and the extra part caused by carrying
|
|
443
|
+
* the current history into it.
|
|
444
|
+
*
|
|
445
|
+
* `historyTokens` comes from the heuristic composition of the next request,
|
|
446
|
+
* scaled to the provider-anchored next-request pressure when one is present.
|
|
447
|
+
* If neither context projection has arrived, the history share is unknown
|
|
448
|
+
* rather than guessed from cumulative usage: one turn can contain many
|
|
449
|
+
* tool/model steps, so an average input per turn would overstate it badly.
|
|
450
|
+
* The per-million-token rate is the session's observed cache-hit/cache-miss
|
|
451
|
+
* mix at the current tariff; with no usage yet it falls back to the
|
|
452
|
+
* cache-miss rate. Output is identical between continuing and starting
|
|
453
|
+
* fresh, so it is left out.
|
|
454
|
+
*
|
|
455
|
+
* @param params - live projections and the current tariff.
|
|
456
|
+
* @returns the estimate and the figures behind it.
|
|
457
|
+
*/
|
|
458
|
+
function estimateNextTurn(params) {
|
|
459
|
+
const { usage, breakdown, pressure, selection, peak } = params
|
|
460
|
+
const tariffs = pricingOf(selection)
|
|
461
|
+
const tariff = tariffs === undefined ? undefined : tariffs[peak ? 'peak' : 'off']
|
|
462
|
+
const systemTokens = countOf(breakdown?.systemTokens)
|
|
463
|
+
const toolsTokens = countOf(breakdown?.toolsTokens)
|
|
464
|
+
const baseTokens = systemTokens + toolsTokens
|
|
465
|
+
const hit = countOf(usage?.cacheReadTokens)
|
|
466
|
+
const miss = countOf(usage?.uncachedInputTokens) + countOf(usage?.cacheWriteTokens)
|
|
467
|
+
const inputTokens = hit + miss
|
|
468
|
+
const projected = countOf(pressure?.projectedTokens)
|
|
469
|
+
const lastPressure = countOf(pressure?.pressureTokens)
|
|
470
|
+
const anchor = projected > 0 ? projected : lastPressure
|
|
471
|
+
const heuristicHistory = countOf(breakdown?.messageTokens)
|
|
472
|
+
const heuristicTotal = baseTokens + heuristicHistory
|
|
473
|
+
const inferredHistory = anchor > baseTokens ? anchor - baseTokens : 0
|
|
474
|
+
const hasContext = anchor > 0 || breakdown !== undefined
|
|
475
|
+
// `projectedTokens`/`pressureTokens` are provider-anchored while the
|
|
476
|
+
// composition is heuristic. When both exist, scale the message share to
|
|
477
|
+
// the anchored total so a systematic CJK/JSON undercount does not shrink
|
|
478
|
+
// the history.
|
|
479
|
+
const historyTokens =
|
|
480
|
+
anchor > 0 && heuristicHistory > 0 && heuristicTotal > 0
|
|
481
|
+
? anchor * (heuristicHistory / heuristicTotal)
|
|
482
|
+
: heuristicHistory > 0
|
|
483
|
+
? heuristicHistory
|
|
484
|
+
: inferredHistory
|
|
485
|
+
const promptTokens = anchor > 0 ? anchor : historyTokens + baseTokens
|
|
486
|
+
|
|
487
|
+
const ratePerMillion =
|
|
488
|
+
tariff === undefined
|
|
489
|
+
? undefined
|
|
490
|
+
: inputTokens > 0
|
|
491
|
+
? (hit * tariff.cacheHit + miss * tariff.cacheMiss) / inputTokens
|
|
492
|
+
: tariff.cacheMiss
|
|
493
|
+
|
|
494
|
+
const priced = tariff !== undefined && ratePerMillion !== undefined
|
|
495
|
+
const extraCny = priced && hasContext ? (historyTokens / 1e6) * ratePerMillion : undefined
|
|
496
|
+
const totalCny = priced && hasContext ? (promptTokens / 1e6) * ratePerMillion : undefined
|
|
497
|
+
const freshCny =
|
|
498
|
+
priced && hasContext ? (Math.max(0, promptTokens - historyTokens) / 1e6) * ratePerMillion : undefined
|
|
499
|
+
return {
|
|
500
|
+
priced,
|
|
501
|
+
hasContext,
|
|
502
|
+
measured: inputTokens > 0,
|
|
503
|
+
historyTokens,
|
|
504
|
+
promptTokens,
|
|
505
|
+
baseTokens,
|
|
506
|
+
extraCny,
|
|
507
|
+
totalCny,
|
|
508
|
+
freshCny,
|
|
509
|
+
rate: ratePerMillion,
|
|
510
|
+
model: modelOf(selection),
|
|
511
|
+
peak,
|
|
512
|
+
hasUsage: inputTokens > 0,
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Pick the dot tone from the configured metric and thresholds.
|
|
518
|
+
* @param settings - normalized settings.
|
|
519
|
+
* @param turns - completed turns.
|
|
520
|
+
* @param estimate - the current estimate.
|
|
521
|
+
* @param loaded - whether the turn projection has arrived.
|
|
522
|
+
* @returns `green`, `yellow`, `red`, or `idle`.
|
|
523
|
+
*/
|
|
524
|
+
function toneOf(settings, turns, estimate, loaded) {
|
|
525
|
+
let value
|
|
526
|
+
let green
|
|
527
|
+
let yellow
|
|
528
|
+
if (settings.metric === 'cost') {
|
|
529
|
+
if (!estimate.hasContext || !estimate.priced || estimate.extraCny === undefined) return 'idle'
|
|
530
|
+
value = estimate.extraCny
|
|
531
|
+
green = settings.costGreen
|
|
532
|
+
yellow = settings.costYellow
|
|
533
|
+
} else {
|
|
534
|
+
if (!loaded) return 'idle'
|
|
535
|
+
value = turns
|
|
536
|
+
green = settings.turnsGreen
|
|
537
|
+
yellow = settings.turnsYellow
|
|
538
|
+
}
|
|
539
|
+
if (value <= green) return 'green'
|
|
540
|
+
if (value <= yellow) return 'yellow'
|
|
541
|
+
return 'red'
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Build the browser bundle's factory.
|
|
546
|
+
* @param require - the module table's require.
|
|
547
|
+
* @returns the factory the module loader registers.
|
|
548
|
+
*/
|
|
549
|
+
function makeFactory() {
|
|
550
|
+
return (require) => {
|
|
551
|
+
const module = { exports: {} }
|
|
552
|
+
const React = require('react')
|
|
553
|
+
const { createElement: h, useState, useEffect, useRef, useSyncExternalStore } = React
|
|
554
|
+
|
|
555
|
+
/** The last table remembered by this browser, applied before the fetch lands. */
|
|
556
|
+
const cachedPrice = readCachedPrices()
|
|
557
|
+
/** One shared price-table snapshot; components re-render when it changes. */
|
|
558
|
+
let priceSnapshot = {
|
|
559
|
+
source: cachedPrice === undefined ? 'builtin' : 'cache',
|
|
560
|
+
fetchedAt: cachedPrice === undefined ? undefined : cachedPrice.fetchedAt,
|
|
561
|
+
revision: 0,
|
|
562
|
+
}
|
|
563
|
+
const priceListeners = new Set()
|
|
564
|
+
let priceInflight = null
|
|
565
|
+
|
|
566
|
+
/** @param listener - price change callback. @returns unsubscribe. */
|
|
567
|
+
function subscribePrices(listener) {
|
|
568
|
+
priceListeners.add(listener)
|
|
569
|
+
return () => {
|
|
570
|
+
priceListeners.delete(listener)
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** @returns the current price-table snapshot. */
|
|
575
|
+
function getPriceSnapshot() {
|
|
576
|
+
return priceSnapshot
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** @returns current price-table metadata, re-rendering on update. */
|
|
580
|
+
function usePrices() {
|
|
581
|
+
return useSyncExternalStore(subscribePrices, getPriceSnapshot)
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Ask the Host to fetch the official pricing Markdown and merge any
|
|
586
|
+
* validated model prices. Failure leaves the built-in/cached table in
|
|
587
|
+
* place and stays silent; this is an enhancement, not a prerequisite.
|
|
588
|
+
* @returns a promise settling after the attempt.
|
|
589
|
+
*/
|
|
590
|
+
function refreshPrices() {
|
|
591
|
+
if (priceInflight !== null) return priceInflight
|
|
592
|
+
priceInflight = (async () => {
|
|
593
|
+
try {
|
|
594
|
+
const response = await fetch(PRICE_PATH, {
|
|
595
|
+
headers: { accept: 'application/json' },
|
|
596
|
+
})
|
|
597
|
+
if (!response.ok) return
|
|
598
|
+
const body = await response.json()
|
|
599
|
+
if (body === null || typeof body !== 'object' || body.ok !== true) return
|
|
600
|
+
const accepted = mergePriceModels(body.models)
|
|
601
|
+
if (accepted === 0) return
|
|
602
|
+
const fetchedAt = typeof body.fetchedAt === 'number' ? body.fetchedAt : Date.now()
|
|
603
|
+
writeCachedPrices(fetchedAt)
|
|
604
|
+
priceSnapshot = {
|
|
605
|
+
source: 'online',
|
|
606
|
+
fetchedAt,
|
|
607
|
+
revision: priceSnapshot.revision + 1,
|
|
608
|
+
}
|
|
609
|
+
for (const listener of priceListeners) listener()
|
|
610
|
+
} catch {
|
|
611
|
+
/* offline or no Host route: keep the built-in/cached table */
|
|
612
|
+
} finally {
|
|
613
|
+
priceInflight = null
|
|
614
|
+
}
|
|
615
|
+
})()
|
|
616
|
+
return priceInflight
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** The last official holiday schedule remembered by this browser. */
|
|
620
|
+
const cachedHoliday = readCachedHolidays()
|
|
621
|
+
/** One shared holiday-table snapshot; components re-render when it changes. */
|
|
622
|
+
let holidaySnapshot = {
|
|
623
|
+
source: cachedHoliday === undefined ? 'builtin' : 'cache',
|
|
624
|
+
fetchedAt: cachedHoliday === undefined ? undefined : cachedHoliday.fetchedAt,
|
|
625
|
+
revision: 0,
|
|
626
|
+
}
|
|
627
|
+
const holidayListeners = new Set()
|
|
628
|
+
let holidayInflight = null
|
|
629
|
+
|
|
630
|
+
/** @param listener - holiday change callback. @returns unsubscribe. */
|
|
631
|
+
function subscribeHolidays(listener) {
|
|
632
|
+
holidayListeners.add(listener)
|
|
633
|
+
return () => {
|
|
634
|
+
holidayListeners.delete(listener)
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** @returns the current holiday-table snapshot. */
|
|
639
|
+
function getHolidaySnapshot() {
|
|
640
|
+
return holidaySnapshot
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** @returns current holiday-table metadata, re-rendering on update. */
|
|
644
|
+
function useHolidays() {
|
|
645
|
+
return useSyncExternalStore(subscribeHolidays, getHolidaySnapshot)
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* Ask the Host to discover and parse the current/next year's State
|
|
650
|
+
* Council holiday notice. A failure keeps the built-in/cached schedule.
|
|
651
|
+
* @returns a promise settling after the attempt.
|
|
652
|
+
*/
|
|
653
|
+
function refreshHolidays() {
|
|
654
|
+
if (holidayInflight !== null) return holidayInflight
|
|
655
|
+
holidayInflight = (async () => {
|
|
656
|
+
try {
|
|
657
|
+
const response = await fetch(HOLIDAY_PATH, {
|
|
658
|
+
headers: { accept: 'application/json' },
|
|
659
|
+
})
|
|
660
|
+
if (!response.ok) return
|
|
661
|
+
const body = await response.json()
|
|
662
|
+
if (body === null || typeof body !== 'object' || body.ok !== true) return
|
|
663
|
+
if (body.years === null || typeof body.years !== 'object') return
|
|
664
|
+
const dates = Object.values(body.years).flatMap((value) => Array.isArray(value) ? value : [])
|
|
665
|
+
const valid = dates.filter((date) => isHolidayDate(date))
|
|
666
|
+
if (valid.length === 0) return
|
|
667
|
+
mergeHolidayDates(valid)
|
|
668
|
+
const fetchedAt = typeof body.fetchedAt === 'number' ? body.fetchedAt : Date.now()
|
|
669
|
+
writeCachedHolidays(fetchedAt)
|
|
670
|
+
holidaySnapshot = {
|
|
671
|
+
source: 'online',
|
|
672
|
+
fetchedAt,
|
|
673
|
+
revision: holidaySnapshot.revision + 1,
|
|
674
|
+
}
|
|
675
|
+
for (const listener of holidayListeners) listener()
|
|
676
|
+
} catch {
|
|
677
|
+
/* offline or no Host route: keep the built-in/cached schedule */
|
|
678
|
+
} finally {
|
|
679
|
+
holidayInflight = null
|
|
680
|
+
}
|
|
681
|
+
})()
|
|
682
|
+
return holidayInflight
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** Chip geometry and panel styling; every color is a host theme token. */
|
|
686
|
+
const CSS = `
|
|
687
|
+
.dshTurnCost_anchor { position: relative; display: inline-flex; align-items: center; }
|
|
688
|
+
.dshTurnCost_chip {
|
|
689
|
+
box-sizing: border-box;
|
|
690
|
+
display: inline-flex;
|
|
691
|
+
align-items: stretch;
|
|
692
|
+
height: 28px;
|
|
693
|
+
max-width: 180px;
|
|
694
|
+
padding: 0;
|
|
695
|
+
border: 1px solid var(--dsw-alias-border-l1);
|
|
696
|
+
border-radius: var(--dsw-radius-sm);
|
|
697
|
+
background: transparent;
|
|
698
|
+
color: var(--dsw-alias-label-secondary);
|
|
699
|
+
font-family: inherit;
|
|
700
|
+
font-size: 12px;
|
|
701
|
+
font-weight: 500;
|
|
702
|
+
line-height: 18px;
|
|
703
|
+
white-space: nowrap;
|
|
704
|
+
overflow: hidden;
|
|
705
|
+
}
|
|
706
|
+
.dshTurnCost_chip:hover { background: var(--dsw-alias-bg-layer-2); }
|
|
707
|
+
.dshTurnCost_chip[data-tone="green"] { color: var(--dsw-alias-label-primary); }
|
|
708
|
+
.dshTurnCost_chip[data-tone="yellow"] { color: var(--dsw-alias-label-primary); }
|
|
709
|
+
.dshTurnCost_chip[data-tone="red"] { color: var(--dsw-alias-label-primary); }
|
|
710
|
+
.dshTurnCost_chip:focus-within { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
|
|
711
|
+
.dshTurnCost_main {
|
|
712
|
+
display: inline-flex;
|
|
713
|
+
align-items: center;
|
|
714
|
+
gap: 6px;
|
|
715
|
+
min-width: 0;
|
|
716
|
+
padding: 0 8px;
|
|
717
|
+
border: 0;
|
|
718
|
+
background: transparent;
|
|
719
|
+
color: inherit;
|
|
720
|
+
font: inherit;
|
|
721
|
+
cursor: pointer;
|
|
722
|
+
}
|
|
723
|
+
.dshTurnCost_main:focus-visible { outline: none; }
|
|
724
|
+
.dshTurnCost_dot {
|
|
725
|
+
width: 6px;
|
|
726
|
+
height: 6px;
|
|
727
|
+
border-radius: 50%;
|
|
728
|
+
flex: none;
|
|
729
|
+
background: var(--dsw-alias-state-idle-primary);
|
|
730
|
+
}
|
|
731
|
+
.dshTurnCost_chip[data-tone="green"] .dshTurnCost_dot { background: var(--dsw-alias-state-success-primary); }
|
|
732
|
+
.dshTurnCost_chip[data-tone="yellow"] .dshTurnCost_dot { background: var(--dsw-alias-state-warn-primary); }
|
|
733
|
+
.dshTurnCost_chip[data-tone="red"] .dshTurnCost_dot { background: var(--dsw-alias-state-error-primary); }
|
|
734
|
+
.dshTurnCost_amount { font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
|
|
735
|
+
.dshTurnCost_panel {
|
|
736
|
+
position: absolute;
|
|
737
|
+
bottom: calc(100% + 8px);
|
|
738
|
+
right: 0;
|
|
739
|
+
z-index: 1400;
|
|
740
|
+
box-sizing: border-box;
|
|
741
|
+
width: 292px;
|
|
742
|
+
max-width: min(292px, calc(100vw - 24px));
|
|
743
|
+
max-height: min(70vh, calc(100vh - 88px));
|
|
744
|
+
overflow-y: auto;
|
|
745
|
+
overscroll-behavior: contain;
|
|
746
|
+
padding: 10px 12px;
|
|
747
|
+
border-radius: var(--dsw-radius-md);
|
|
748
|
+
background: var(--dsw-alias-bg-overlay);
|
|
749
|
+
box-shadow: var(--dsw-elevation-panel);
|
|
750
|
+
color: var(--dsw-alias-label-primary);
|
|
751
|
+
font-family: inherit;
|
|
752
|
+
font-size: 12px;
|
|
753
|
+
line-height: 18px;
|
|
754
|
+
text-align: left;
|
|
755
|
+
pointer-events: auto;
|
|
756
|
+
}
|
|
757
|
+
.dshTurnCost_header {
|
|
758
|
+
display: flex;
|
|
759
|
+
align-items: baseline;
|
|
760
|
+
justify-content: space-between;
|
|
761
|
+
gap: 10px;
|
|
762
|
+
margin-bottom: 4px;
|
|
763
|
+
color: var(--dsw-alias-label-secondary);
|
|
764
|
+
}
|
|
765
|
+
.dshTurnCost_headerTitle { font-weight: 500; }
|
|
766
|
+
.dshTurnCost_unpin {
|
|
767
|
+
padding: 0;
|
|
768
|
+
border: 0;
|
|
769
|
+
background: transparent;
|
|
770
|
+
color: var(--dsw-alias-brand-primary);
|
|
771
|
+
font: inherit;
|
|
772
|
+
cursor: pointer;
|
|
773
|
+
}
|
|
774
|
+
.dshTurnCost_unpin:hover { text-decoration: underline; }
|
|
775
|
+
.dshTurnCost_unpin:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
|
|
776
|
+
.dshTurnCost_line { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }
|
|
777
|
+
.dshTurnCost_label { color: var(--dsw-alias-label-secondary); }
|
|
778
|
+
.dshTurnCost_value { font-variant-numeric: tabular-nums; text-align: right; }
|
|
779
|
+
.dshTurnCost_line[data-emphasis="true"] { margin: 3px 0; font-size: 13px; font-weight: 600; }
|
|
780
|
+
.dshTurnCost_line[data-emphasis="true"] .dshTurnCost_label { color: var(--dsw-alias-label-primary); }
|
|
781
|
+
.dshTurnCost_divider { margin: 7px 0; border-top: .5px solid var(--dsw-alias-border-l1); }
|
|
782
|
+
.dshTurnCost_alert { color: var(--dsw-alias-state-warn-primary); }
|
|
783
|
+
.dshTurnCost_note { margin-top: 6px; color: var(--dsw-alias-label-secondary); }
|
|
784
|
+
.dshTurnCost_stage {
|
|
785
|
+
margin-top: 8px;
|
|
786
|
+
padding-top: 7px;
|
|
787
|
+
border-top: .5px solid var(--dsw-alias-border-l1);
|
|
788
|
+
}
|
|
789
|
+
.dshTurnCost_stageText { margin-top: 2px; color: var(--dsw-alias-label-secondary); }
|
|
790
|
+
.dshTurnCost_pinHint { margin-top: 7px; color: var(--dsw-alias-brand-primary); }
|
|
791
|
+
.dshTurnCost_displayRow {
|
|
792
|
+
display: flex;
|
|
793
|
+
align-items: center;
|
|
794
|
+
justify-content: space-between;
|
|
795
|
+
gap: 10px;
|
|
796
|
+
margin-bottom: 7px;
|
|
797
|
+
padding-bottom: 7px;
|
|
798
|
+
border-bottom: .5px solid var(--dsw-alias-border-l1);
|
|
799
|
+
}
|
|
800
|
+
.dshTurnCost_displayLabel { color: var(--dsw-alias-label-secondary); }
|
|
801
|
+
.dshTurnCost_displayRow .dshTurnCost_seg { margin-bottom: 0; }
|
|
802
|
+
.dshTurnCost_settings {
|
|
803
|
+
margin-top: 9px;
|
|
804
|
+
padding-top: 8px;
|
|
805
|
+
border-top: .5px solid var(--dsw-alias-border-l1);
|
|
806
|
+
}
|
|
807
|
+
.dshTurnCost_settingsTitle { margin-bottom: 6px; font-weight: 500; }
|
|
808
|
+
.dshTurnCost_seg {
|
|
809
|
+
display: inline-flex;
|
|
810
|
+
margin-bottom: 7px;
|
|
811
|
+
border: 1px solid var(--dsw-alias-border-l1);
|
|
812
|
+
border-radius: 6px;
|
|
813
|
+
overflow: hidden;
|
|
814
|
+
}
|
|
815
|
+
.dshTurnCost_segBtn {
|
|
816
|
+
padding: 3px 9px;
|
|
817
|
+
border: 0;
|
|
818
|
+
background: transparent;
|
|
819
|
+
color: var(--dsw-alias-label-secondary);
|
|
820
|
+
font: inherit;
|
|
821
|
+
cursor: pointer;
|
|
822
|
+
}
|
|
823
|
+
.dshTurnCost_segBtn[data-active="true"] {
|
|
824
|
+
background: var(--dsw-alias-bg-layer-2);
|
|
825
|
+
color: var(--dsw-alias-label-primary);
|
|
826
|
+
}
|
|
827
|
+
.dshTurnCost_segBtn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -2px; }
|
|
828
|
+
.dshTurnCost_field {
|
|
829
|
+
display: flex;
|
|
830
|
+
align-items: center;
|
|
831
|
+
justify-content: space-between;
|
|
832
|
+
gap: 10px;
|
|
833
|
+
margin-top: 5px;
|
|
834
|
+
}
|
|
835
|
+
.dshTurnCost_fieldLabel { color: var(--dsw-alias-label-secondary); }
|
|
836
|
+
.dshTurnCost_inputWrap { display: inline-flex; align-items: center; gap: 4px; }
|
|
837
|
+
.dshTurnCost_input {
|
|
838
|
+
box-sizing: border-box;
|
|
839
|
+
width: 74px;
|
|
840
|
+
height: 25px;
|
|
841
|
+
padding: 0 6px;
|
|
842
|
+
border: 1px solid var(--dsw-alias-border-l1);
|
|
843
|
+
border-radius: 5px;
|
|
844
|
+
background: var(--dsw-alias-bg-layer-1);
|
|
845
|
+
color: var(--dsw-alias-label-primary);
|
|
846
|
+
font: inherit;
|
|
847
|
+
font-variant-numeric: tabular-nums;
|
|
848
|
+
}
|
|
849
|
+
.dshTurnCost_input:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
|
|
850
|
+
.dshTurnCost_unit { color: var(--dsw-alias-label-secondary); }
|
|
851
|
+
.dshTurnCost_settingsFoot {
|
|
852
|
+
display: flex;
|
|
853
|
+
align-items: flex-start;
|
|
854
|
+
justify-content: space-between;
|
|
855
|
+
gap: 10px;
|
|
856
|
+
margin-top: 7px;
|
|
857
|
+
color: var(--dsw-alias-label-secondary);
|
|
858
|
+
}
|
|
859
|
+
.dshTurnCost_reset {
|
|
860
|
+
flex: none;
|
|
861
|
+
padding: 0;
|
|
862
|
+
border: 0;
|
|
863
|
+
background: transparent;
|
|
864
|
+
color: var(--dsw-alias-brand-primary);
|
|
865
|
+
font: inherit;
|
|
866
|
+
cursor: pointer;
|
|
867
|
+
}
|
|
868
|
+
.dshTurnCost_reset:hover { text-decoration: underline; }
|
|
869
|
+
.dshTurnCost_reset:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 2px; }
|
|
870
|
+
`.trim()
|
|
871
|
+
|
|
872
|
+
/** One shared settings store, so two session chips stay in sync. */
|
|
873
|
+
let settings = readSettings()
|
|
874
|
+
const settingsListeners = new Set()
|
|
875
|
+
|
|
876
|
+
/** @param next - complete settings to normalize, persist, and publish. */
|
|
877
|
+
function publishSettings(next) {
|
|
878
|
+
settings = normalizeSettings(next)
|
|
879
|
+
try {
|
|
880
|
+
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(settings))
|
|
881
|
+
} catch {
|
|
882
|
+
/* private mode or a full quota: the in-memory value still works */
|
|
883
|
+
}
|
|
884
|
+
for (const listener of settingsListeners) listener()
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/** @param listener - change callback. @returns unsubscribe. */
|
|
888
|
+
function subscribeSettings(listener) {
|
|
889
|
+
settingsListeners.add(listener)
|
|
890
|
+
return () => {
|
|
891
|
+
settingsListeners.delete(listener)
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** @returns the current settings (stable reference between changes). */
|
|
896
|
+
function getSettings() {
|
|
897
|
+
return settings
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/** @returns current settings, re-rendering on change. */
|
|
901
|
+
function useSettings() {
|
|
902
|
+
return useSyncExternalStore(subscribeSettings, getSettings)
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** @param amount - non-negative CNY. @returns display text. */
|
|
906
|
+
function formatCny(amount) {
|
|
907
|
+
if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
|
|
908
|
+
const digits = amount > 0 && amount < 0.0001 ? 5 : amount > 0 && amount < 0.01 ? 4 : 2
|
|
909
|
+
try {
|
|
910
|
+
return new Intl.NumberFormat(undefined, {
|
|
911
|
+
style: 'currency',
|
|
912
|
+
currency: 'CNY',
|
|
913
|
+
minimumFractionDigits: digits,
|
|
914
|
+
maximumFractionDigits: digits,
|
|
915
|
+
}).format(amount)
|
|
916
|
+
} catch {
|
|
917
|
+
return `¥${amount.toFixed(digits)}`
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** @param amount - non-negative CNY. @returns a cost value with a stable four decimals. */
|
|
922
|
+
function formatCost(amount) {
|
|
923
|
+
if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
|
|
924
|
+
try {
|
|
925
|
+
return new Intl.NumberFormat(undefined, {
|
|
926
|
+
style: 'currency',
|
|
927
|
+
currency: 'CNY',
|
|
928
|
+
minimumFractionDigits: 4,
|
|
929
|
+
maximumFractionDigits: 4,
|
|
930
|
+
}).format(amount)
|
|
931
|
+
} catch {
|
|
932
|
+
return `¥${amount.toFixed(4)}`
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/** @param tokens - non-negative count. @returns display text. */
|
|
937
|
+
function formatTokens(tokens) {
|
|
938
|
+
if (typeof tokens !== 'number' || !Number.isFinite(tokens)) return '—'
|
|
939
|
+
try {
|
|
940
|
+
return new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(tokens)
|
|
941
|
+
} catch {
|
|
942
|
+
return String(Math.round(tokens))
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/** @param rate - CNY per million tokens. @returns CNY per million tokens. */
|
|
947
|
+
function formatRate(rate) {
|
|
948
|
+
return formatCny(rate)
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** @param value - threshold number. @returns a plain editable string. */
|
|
952
|
+
function formatInput(value, metric) {
|
|
953
|
+
return metric === 'cost' ? String(value) : String(Math.round(value))
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** The bundle's stylesheet as one React element, removed with the surface. */
|
|
957
|
+
function StyleTag() {
|
|
958
|
+
return h('style', { 'data-plugin-css': NAME }, CSS)
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/** One label/value row of the panel. */
|
|
962
|
+
function Line({ label, value, emphasis }) {
|
|
963
|
+
return h(
|
|
964
|
+
'div',
|
|
965
|
+
{ className: 'dshTurnCost_line', 'data-emphasis': emphasis === true ? 'true' : undefined },
|
|
966
|
+
h('span', { className: 'dshTurnCost_label' }, label),
|
|
967
|
+
h('span', { className: 'dshTurnCost_value' }, value),
|
|
968
|
+
)
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/** One threshold number field; commits a valid value on blur or Enter. */
|
|
972
|
+
function NumberField({ label, value, unit, metric, onCommit }) {
|
|
973
|
+
const [draft, setDraft] = useState(() => formatInput(value, metric))
|
|
974
|
+
const cancelRef = useRef(false)
|
|
975
|
+
useEffect(() => {
|
|
976
|
+
setDraft(formatInput(value, metric))
|
|
977
|
+
}, [value, metric])
|
|
978
|
+
const reset = () => {
|
|
979
|
+
setDraft(formatInput(value, metric))
|
|
980
|
+
}
|
|
981
|
+
const commit = () => {
|
|
982
|
+
if (cancelRef.current) {
|
|
983
|
+
cancelRef.current = false
|
|
984
|
+
reset()
|
|
985
|
+
return
|
|
986
|
+
}
|
|
987
|
+
const text = draft.trim()
|
|
988
|
+
if (text === '') {
|
|
989
|
+
reset()
|
|
990
|
+
return
|
|
991
|
+
}
|
|
992
|
+
const parsed = Number(text.replace(',', '.'))
|
|
993
|
+
if (Number.isFinite(parsed) && parsed >= 0) {
|
|
994
|
+
onCommit(parsed)
|
|
995
|
+
} else {
|
|
996
|
+
reset()
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
return h(
|
|
1000
|
+
'label',
|
|
1001
|
+
{ className: 'dshTurnCost_field' },
|
|
1002
|
+
h('span', { className: 'dshTurnCost_fieldLabel' }, label),
|
|
1003
|
+
h(
|
|
1004
|
+
'span',
|
|
1005
|
+
{ className: 'dshTurnCost_inputWrap' },
|
|
1006
|
+
h('input', {
|
|
1007
|
+
className: 'dshTurnCost_input',
|
|
1008
|
+
type: 'number',
|
|
1009
|
+
min: '0',
|
|
1010
|
+
step: metric === 'cost' ? '0.01' : '1',
|
|
1011
|
+
inputMode: 'decimal',
|
|
1012
|
+
value: draft,
|
|
1013
|
+
onChange: (event) => {
|
|
1014
|
+
cancelRef.current = false
|
|
1015
|
+
setDraft(event.target.value)
|
|
1016
|
+
},
|
|
1017
|
+
onBlur: commit,
|
|
1018
|
+
onKeyDown: (event) => {
|
|
1019
|
+
if (event.key === 'Enter') {
|
|
1020
|
+
event.preventDefault()
|
|
1021
|
+
event.currentTarget.blur()
|
|
1022
|
+
} else if (event.key === 'Escape') {
|
|
1023
|
+
event.preventDefault()
|
|
1024
|
+
event.stopPropagation()
|
|
1025
|
+
cancelRef.current = true
|
|
1026
|
+
reset()
|
|
1027
|
+
event.currentTarget.blur()
|
|
1028
|
+
}
|
|
1029
|
+
},
|
|
1030
|
+
}),
|
|
1031
|
+
h('span', { className: 'dshTurnCost_unit' }, unit),
|
|
1032
|
+
),
|
|
1033
|
+
)
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
/** One option of the metric switch. */
|
|
1037
|
+
function MetricButton({ active, children, onClick }) {
|
|
1038
|
+
return h(
|
|
1039
|
+
'button',
|
|
1040
|
+
{
|
|
1041
|
+
type: 'button',
|
|
1042
|
+
className: 'dshTurnCost_segBtn',
|
|
1043
|
+
'data-active': active ? 'true' : 'false',
|
|
1044
|
+
'aria-pressed': active,
|
|
1045
|
+
onClick,
|
|
1046
|
+
},
|
|
1047
|
+
children,
|
|
1048
|
+
)
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
/**
|
|
1052
|
+
* The hover/focus panel: the selected display value, the next-turn
|
|
1053
|
+
* context estimate, the continue/fresh split, and (when pinned) the
|
|
1054
|
+
* display switch and thresholds.
|
|
1055
|
+
*/
|
|
1056
|
+
function Panel({
|
|
1057
|
+
estimate,
|
|
1058
|
+
turnsLabel,
|
|
1059
|
+
settings,
|
|
1060
|
+
priceSource,
|
|
1061
|
+
holidaySource,
|
|
1062
|
+
t,
|
|
1063
|
+
pinned,
|
|
1064
|
+
onUnpin,
|
|
1065
|
+
onMetric,
|
|
1066
|
+
onThreshold,
|
|
1067
|
+
onReset,
|
|
1068
|
+
onMouseEnter,
|
|
1069
|
+
onMouseLeave,
|
|
1070
|
+
}) {
|
|
1071
|
+
const metricLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
|
|
1072
|
+
const green = settings.metric === 'cost' ? settings.costGreen : settings.turnsGreen
|
|
1073
|
+
const yellow = settings.metric === 'cost' ? settings.costYellow : settings.turnsYellow
|
|
1074
|
+
const greenText =
|
|
1075
|
+
settings.metric === 'cost'
|
|
1076
|
+
? formatCny(green)
|
|
1077
|
+
: `${Math.round(green)} ${t('settings.unitTurns')}`
|
|
1078
|
+
const yellowText =
|
|
1079
|
+
settings.metric === 'cost'
|
|
1080
|
+
? formatCny(yellow)
|
|
1081
|
+
: `${Math.round(yellow)} ${t('settings.unitTurns')}`
|
|
1082
|
+
const current =
|
|
1083
|
+
settings.metric === 'cost'
|
|
1084
|
+
? estimate.priced && estimate.extraCny !== undefined
|
|
1085
|
+
? `≈ ${formatCost(estimate.extraCny)}`
|
|
1086
|
+
: '—'
|
|
1087
|
+
: turnsLabel
|
|
1088
|
+
const tariff = estimate.peak ? t('tariff.peak') : t('tariff.off')
|
|
1089
|
+
const modelText =
|
|
1090
|
+
estimate.model === undefined
|
|
1091
|
+
? t('panel.noModel')
|
|
1092
|
+
: estimate.priced
|
|
1093
|
+
? `${estimate.model} · ${tariff}`
|
|
1094
|
+
: estimate.model
|
|
1095
|
+
|
|
1096
|
+
const rows = [
|
|
1097
|
+
h(Line, { key: 'turns', label: t('panel.turns'), value: turnsLabel }),
|
|
1098
|
+
h(Line, {
|
|
1099
|
+
key: 'extra',
|
|
1100
|
+
label: t('panel.extra'),
|
|
1101
|
+
value:
|
|
1102
|
+
estimate.priced && estimate.extraCny !== undefined
|
|
1103
|
+
? `≈ ${formatCost(estimate.extraCny)}`
|
|
1104
|
+
: '—',
|
|
1105
|
+
emphasis: true,
|
|
1106
|
+
}),
|
|
1107
|
+
h('div', { key: 'split', className: 'dshTurnCost_divider' }),
|
|
1108
|
+
h(Line, {
|
|
1109
|
+
key: 'continue',
|
|
1110
|
+
label: t('panel.continue'),
|
|
1111
|
+
value: estimate.totalCny === undefined ? '—' : `≈ ${formatCost(estimate.totalCny)}`,
|
|
1112
|
+
}),
|
|
1113
|
+
h(Line, {
|
|
1114
|
+
key: 'fresh',
|
|
1115
|
+
label: t('panel.fresh'),
|
|
1116
|
+
value: estimate.freshCny === undefined ? '—' : `≈ ${formatCost(estimate.freshCny)}`,
|
|
1117
|
+
}),
|
|
1118
|
+
h('div', { key: 'factDivider', className: 'dshTurnCost_divider' }),
|
|
1119
|
+
h(Line, {
|
|
1120
|
+
key: 'history',
|
|
1121
|
+
label: t('panel.history'),
|
|
1122
|
+
value: estimate.hasContext ? `≈ ${formatTokens(estimate.historyTokens)} ${t('panel.tokens')}` : '—',
|
|
1123
|
+
}),
|
|
1124
|
+
h(Line, {
|
|
1125
|
+
key: 'prompt',
|
|
1126
|
+
label: t('panel.prompt'),
|
|
1127
|
+
value: estimate.hasContext ? `${formatTokens(estimate.promptTokens)} ${t('panel.tokens')}` : '—',
|
|
1128
|
+
}),
|
|
1129
|
+
h(Line, {
|
|
1130
|
+
key: 'rate',
|
|
1131
|
+
label: estimate.measured ? t('panel.rateMeasured') : t('panel.rateReference'),
|
|
1132
|
+
value: estimate.rate === undefined ? '—' : `${formatRate(estimate.rate)} ${t('panel.perMillion')}`,
|
|
1133
|
+
}),
|
|
1134
|
+
h(Line, { key: 'model', label: t('panel.model'), value: modelText }),
|
|
1135
|
+
h(Line, {
|
|
1136
|
+
key: 'priceSource',
|
|
1137
|
+
label: t('panel.priceTable'),
|
|
1138
|
+
value:
|
|
1139
|
+
priceSource === 'online'
|
|
1140
|
+
? t('panel.priceOnline')
|
|
1141
|
+
: priceSource === 'cache'
|
|
1142
|
+
? t('panel.priceCache')
|
|
1143
|
+
: t('panel.priceBuiltin'),
|
|
1144
|
+
}),
|
|
1145
|
+
h(Line, {
|
|
1146
|
+
key: 'holidaySource',
|
|
1147
|
+
label: t('panel.holidayTable'),
|
|
1148
|
+
value:
|
|
1149
|
+
holidaySource === 'online'
|
|
1150
|
+
? t('panel.holidayOnline')
|
|
1151
|
+
: holidaySource === 'cache'
|
|
1152
|
+
? t('panel.holidayCache')
|
|
1153
|
+
: t('panel.holidayBuiltin'),
|
|
1154
|
+
}),
|
|
1155
|
+
]
|
|
1156
|
+
|
|
1157
|
+
const displaySwitch = pinned
|
|
1158
|
+
? h(
|
|
1159
|
+
'div',
|
|
1160
|
+
{ className: 'dshTurnCost_displayRow' },
|
|
1161
|
+
h('span', { className: 'dshTurnCost_displayLabel' }, t('panel.colorBy')),
|
|
1162
|
+
h(
|
|
1163
|
+
'div',
|
|
1164
|
+
{ className: 'dshTurnCost_seg', role: 'group', 'aria-label': t('panel.colorBy') },
|
|
1165
|
+
h(
|
|
1166
|
+
MetricButton,
|
|
1167
|
+
{
|
|
1168
|
+
active: settings.metric === 'turns',
|
|
1169
|
+
onClick: () => {
|
|
1170
|
+
onMetric('turns')
|
|
1171
|
+
},
|
|
1172
|
+
},
|
|
1173
|
+
t('settings.turns'),
|
|
1174
|
+
),
|
|
1175
|
+
h(
|
|
1176
|
+
MetricButton,
|
|
1177
|
+
{
|
|
1178
|
+
active: settings.metric === 'cost',
|
|
1179
|
+
onClick: () => {
|
|
1180
|
+
onMetric('cost')
|
|
1181
|
+
},
|
|
1182
|
+
},
|
|
1183
|
+
t('settings.cost'),
|
|
1184
|
+
),
|
|
1185
|
+
),
|
|
1186
|
+
)
|
|
1187
|
+
: null
|
|
1188
|
+
|
|
1189
|
+
const settingsBlock = pinned
|
|
1190
|
+
? h(
|
|
1191
|
+
'div',
|
|
1192
|
+
{ className: 'dshTurnCost_settings' },
|
|
1193
|
+
h('div', { className: 'dshTurnCost_settingsTitle' }, t('settings.title')),
|
|
1194
|
+
h(NumberField, {
|
|
1195
|
+
key: `green-${settings.metric}`,
|
|
1196
|
+
label: t('settings.green'),
|
|
1197
|
+
value: green,
|
|
1198
|
+
unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
|
|
1199
|
+
metric: settings.metric,
|
|
1200
|
+
onCommit: (value) => {
|
|
1201
|
+
onThreshold('green', value)
|
|
1202
|
+
},
|
|
1203
|
+
}),
|
|
1204
|
+
h(NumberField, {
|
|
1205
|
+
key: `yellow-${settings.metric}`,
|
|
1206
|
+
label: t('settings.yellow'),
|
|
1207
|
+
value: yellow,
|
|
1208
|
+
unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
|
|
1209
|
+
metric: settings.metric,
|
|
1210
|
+
onCommit: (value) => {
|
|
1211
|
+
onThreshold('yellow', value)
|
|
1212
|
+
},
|
|
1213
|
+
}),
|
|
1214
|
+
h(
|
|
1215
|
+
'div',
|
|
1216
|
+
{ className: 'dshTurnCost_settingsFoot' },
|
|
1217
|
+
h('span', null, t('settings.hint')),
|
|
1218
|
+
h(
|
|
1219
|
+
'button',
|
|
1220
|
+
{
|
|
1221
|
+
type: 'button',
|
|
1222
|
+
className: 'dshTurnCost_reset',
|
|
1223
|
+
onClick: onReset,
|
|
1224
|
+
},
|
|
1225
|
+
t('settings.reset'),
|
|
1226
|
+
),
|
|
1227
|
+
),
|
|
1228
|
+
)
|
|
1229
|
+
: null
|
|
1230
|
+
|
|
1231
|
+
return h(
|
|
1232
|
+
'div',
|
|
1233
|
+
{
|
|
1234
|
+
className: 'dshTurnCost_panel',
|
|
1235
|
+
id: 'dsh-turn-cost-detail',
|
|
1236
|
+
role: pinned ? 'dialog' : 'tooltip',
|
|
1237
|
+
'aria-label': t('chip.title'),
|
|
1238
|
+
'data-pinned': pinned ? 'true' : 'false',
|
|
1239
|
+
onMouseEnter,
|
|
1240
|
+
onMouseLeave,
|
|
1241
|
+
},
|
|
1242
|
+
h(
|
|
1243
|
+
'div',
|
|
1244
|
+
{ className: 'dshTurnCost_header' },
|
|
1245
|
+
h('span', { className: 'dshTurnCost_headerTitle' }, t('panel.title')),
|
|
1246
|
+
pinned
|
|
1247
|
+
? h(
|
|
1248
|
+
'button',
|
|
1249
|
+
{ type: 'button', className: 'dshTurnCost_unpin', onClick: onUnpin },
|
|
1250
|
+
t('settings.unpin'),
|
|
1251
|
+
)
|
|
1252
|
+
: null,
|
|
1253
|
+
),
|
|
1254
|
+
displaySwitch,
|
|
1255
|
+
...rows,
|
|
1256
|
+
estimate.hasContext
|
|
1257
|
+
? !estimate.priced && estimate.model !== undefined
|
|
1258
|
+
? h('div', { className: 'dshTurnCost_note dshTurnCost_alert' }, t('panel.noPrice'))
|
|
1259
|
+
: null
|
|
1260
|
+
: h('div', { className: 'dshTurnCost_note dshTurnCost_alert' }, t('panel.noContext')),
|
|
1261
|
+
estimate.hasContext && estimate.priced && !estimate.hasUsage
|
|
1262
|
+
? h('div', { className: 'dshTurnCost_note' }, t('panel.waiting'))
|
|
1263
|
+
: null,
|
|
1264
|
+
h(
|
|
1265
|
+
'div',
|
|
1266
|
+
{ className: 'dshTurnCost_stage' },
|
|
1267
|
+
h(Line, { label: t('panel.colorBy'), value: metricLabel }),
|
|
1268
|
+
h(Line, { label: t('panel.current'), value: current }),
|
|
1269
|
+
h(
|
|
1270
|
+
'div',
|
|
1271
|
+
{ className: 'dshTurnCost_stageText' },
|
|
1272
|
+
`${t('panel.leq')}${greenText} ${t('tone.green')} · ${t('panel.leq')}${yellowText} ${t(
|
|
1273
|
+
'tone.yellow',
|
|
1274
|
+
)} · ${t('panel.gt')}${yellowText} ${t('tone.red')}`,
|
|
1275
|
+
),
|
|
1276
|
+
),
|
|
1277
|
+
h('div', { className: 'dshTurnCost_note' }, t('panel.note')),
|
|
1278
|
+
pinned ? settingsBlock : h('div', { className: 'dshTurnCost_pinHint' }, t('settings.pinHint')),
|
|
1279
|
+
)
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/**
|
|
1283
|
+
* Compact chip plus its hover panel. Clicking the chip pins the panel so
|
|
1284
|
+
* the threshold fields can receive pointer and keyboard input.
|
|
1285
|
+
*/
|
|
1286
|
+
function TurnCostChip({ useProjection, t }) {
|
|
1287
|
+
const settings = useSettings()
|
|
1288
|
+
const priceInfo = usePrices()
|
|
1289
|
+
const holidayInfo = useHolidays()
|
|
1290
|
+
const [hovered, setHovered] = useState(false)
|
|
1291
|
+
const [pinned, setPinned] = useState(false)
|
|
1292
|
+
const [focusWithin, setFocusWithin] = useState(false)
|
|
1293
|
+
const [, setClock] = useState(0)
|
|
1294
|
+
const anchorRef = useRef(null)
|
|
1295
|
+
const chipRef = useRef(null)
|
|
1296
|
+
const closeTimer = useRef(0)
|
|
1297
|
+
const suppressFocus = useRef(false)
|
|
1298
|
+
|
|
1299
|
+
useEffect(
|
|
1300
|
+
() => () => {
|
|
1301
|
+
if (closeTimer.current !== 0) window.clearTimeout(closeTimer.current)
|
|
1302
|
+
},
|
|
1303
|
+
[],
|
|
1304
|
+
)
|
|
1305
|
+
|
|
1306
|
+
const dismiss = () => {
|
|
1307
|
+
if (closeTimer.current !== 0) {
|
|
1308
|
+
window.clearTimeout(closeTimer.current)
|
|
1309
|
+
closeTimer.current = 0
|
|
1310
|
+
}
|
|
1311
|
+
setPinned(false)
|
|
1312
|
+
setHovered(false)
|
|
1313
|
+
setFocusWithin(false)
|
|
1314
|
+
const chip = chipRef.current
|
|
1315
|
+
if (chip !== null && document.activeElement !== chip) {
|
|
1316
|
+
suppressFocus.current = true
|
|
1317
|
+
chip.focus()
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
useEffect(() => {
|
|
1322
|
+
if (!pinned) return undefined
|
|
1323
|
+
const onPointerDown = (event) => {
|
|
1324
|
+
const anchor = anchorRef.current
|
|
1325
|
+
if (anchor !== null && !anchor.contains(event.target)) {
|
|
1326
|
+
setPinned(false)
|
|
1327
|
+
setHovered(false)
|
|
1328
|
+
setFocusWithin(false)
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
const onKeyDown = (event) => {
|
|
1332
|
+
if (event.key === 'Escape') dismiss()
|
|
1333
|
+
}
|
|
1334
|
+
document.addEventListener('pointerdown', onPointerDown, true)
|
|
1335
|
+
document.addEventListener('keydown', onKeyDown)
|
|
1336
|
+
return () => {
|
|
1337
|
+
document.removeEventListener('pointerdown', onPointerDown, true)
|
|
1338
|
+
document.removeEventListener('keydown', onKeyDown)
|
|
1339
|
+
}
|
|
1340
|
+
}, [pinned])
|
|
1341
|
+
|
|
1342
|
+
const cancelClose = () => {
|
|
1343
|
+
if (closeTimer.current !== 0) {
|
|
1344
|
+
window.clearTimeout(closeTimer.current)
|
|
1345
|
+
closeTimer.current = 0
|
|
1346
|
+
}
|
|
1347
|
+
if (priceInfo.source !== 'online') void refreshPrices()
|
|
1348
|
+
if (holidayInfo.source !== 'online') void refreshHolidays()
|
|
1349
|
+
setHovered(true)
|
|
1350
|
+
}
|
|
1351
|
+
const scheduleClose = () => {
|
|
1352
|
+
if (closeTimer.current !== 0) window.clearTimeout(closeTimer.current)
|
|
1353
|
+
closeTimer.current = window.setTimeout(() => {
|
|
1354
|
+
closeTimer.current = 0
|
|
1355
|
+
setHovered(false)
|
|
1356
|
+
}, 240)
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
const useP = typeof useProjection === 'function' ? useProjection : () => undefined
|
|
1360
|
+
const stats = useP('sessionStats')
|
|
1361
|
+
const usage = useP('tokenUsage')
|
|
1362
|
+
const breakdown = useP('contextBreakdown')
|
|
1363
|
+
const pressure = useP('contextPressure')
|
|
1364
|
+
const selection = useP('modelSelection')
|
|
1365
|
+
|
|
1366
|
+
const rawTurns = stats?.turns
|
|
1367
|
+
const turns = typeof rawTurns === 'number' && Number.isFinite(rawTurns) && rawTurns >= 0 ? Math.floor(rawTurns) : 0
|
|
1368
|
+
const peak = isPeakTariff()
|
|
1369
|
+
const estimate = estimateNextTurn({ usage, breakdown, pressure, selection, peak })
|
|
1370
|
+
const tone = toneOf(settings, turns, estimate, stats !== undefined)
|
|
1371
|
+
const open = hovered || pinned || focusWithin
|
|
1372
|
+
useEffect(() => {
|
|
1373
|
+
const timer = window.setInterval(() => {
|
|
1374
|
+
setClock((value) => value + 1)
|
|
1375
|
+
}, 30_000)
|
|
1376
|
+
return () => {
|
|
1377
|
+
window.clearInterval(timer)
|
|
1378
|
+
}
|
|
1379
|
+
}, [])
|
|
1380
|
+
const turnsLabel = stats === undefined ? t('chip.turnsLoading') : `${turns} ${t('chip.unit')}`
|
|
1381
|
+
const costLabel =
|
|
1382
|
+
estimate.hasContext && estimate.priced && estimate.extraCny !== undefined
|
|
1383
|
+
? `≈ ${formatCost(estimate.extraCny)}`
|
|
1384
|
+
: t('chip.costUnknown')
|
|
1385
|
+
const valueLabel = settings.metric === 'cost' ? costLabel : turnsLabel
|
|
1386
|
+
const toneText =
|
|
1387
|
+
tone === 'green'
|
|
1388
|
+
? t('tone.green')
|
|
1389
|
+
: tone === 'yellow'
|
|
1390
|
+
? t('tone.yellow')
|
|
1391
|
+
: tone === 'red'
|
|
1392
|
+
? t('tone.red')
|
|
1393
|
+
: t('tone.idle')
|
|
1394
|
+
const basisLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
|
|
1395
|
+
const summary = `${t('chip.title')} · ${valueLabel} · ${t('panel.colorBy')}: ${basisLabel} (${toneText}) · ${t('chip.pinHint')}`
|
|
1396
|
+
|
|
1397
|
+
const updateMetric = (metric) => {
|
|
1398
|
+
publishSettings({ ...settings, metric })
|
|
1399
|
+
}
|
|
1400
|
+
const updateThreshold = (field, value) => {
|
|
1401
|
+
if (settings.metric === 'cost') {
|
|
1402
|
+
if (field === 'green') {
|
|
1403
|
+
publishSettings({
|
|
1404
|
+
...settings,
|
|
1405
|
+
costGreen: value,
|
|
1406
|
+
costYellow: Math.max(settings.costYellow, value),
|
|
1407
|
+
})
|
|
1408
|
+
} else {
|
|
1409
|
+
publishSettings({
|
|
1410
|
+
...settings,
|
|
1411
|
+
costYellow: Math.max(settings.costGreen, value),
|
|
1412
|
+
})
|
|
1413
|
+
}
|
|
1414
|
+
} else if (field === 'green') {
|
|
1415
|
+
publishSettings({
|
|
1416
|
+
...settings,
|
|
1417
|
+
turnsGreen: value,
|
|
1418
|
+
turnsYellow: Math.max(settings.turnsYellow, value),
|
|
1419
|
+
})
|
|
1420
|
+
} else {
|
|
1421
|
+
publishSettings({
|
|
1422
|
+
...settings,
|
|
1423
|
+
turnsYellow: Math.max(settings.turnsGreen, value),
|
|
1424
|
+
})
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
const resetSettings = () => {
|
|
1428
|
+
publishSettings({ ...DEFAULT_SETTINGS, metric: settings.metric })
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
return h(
|
|
1432
|
+
'span',
|
|
1433
|
+
{
|
|
1434
|
+
ref: anchorRef,
|
|
1435
|
+
className: 'dshTurnCost_anchor',
|
|
1436
|
+
onMouseEnter: cancelClose,
|
|
1437
|
+
onMouseLeave: scheduleClose,
|
|
1438
|
+
onFocusCapture: () => {
|
|
1439
|
+
if (suppressFocus.current) {
|
|
1440
|
+
suppressFocus.current = false
|
|
1441
|
+
return
|
|
1442
|
+
}
|
|
1443
|
+
setFocusWithin(true)
|
|
1444
|
+
cancelClose()
|
|
1445
|
+
},
|
|
1446
|
+
onBlurCapture: (event) => {
|
|
1447
|
+
if (!event.currentTarget.contains(event.relatedTarget)) setFocusWithin(false)
|
|
1448
|
+
},
|
|
1449
|
+
onKeyDown: (event) => {
|
|
1450
|
+
if (event.key === 'Escape') dismiss()
|
|
1451
|
+
},
|
|
1452
|
+
},
|
|
1453
|
+
h(StyleTag, { key: 'style' }),
|
|
1454
|
+
h(
|
|
1455
|
+
'span',
|
|
1456
|
+
{
|
|
1457
|
+
key: 'chip',
|
|
1458
|
+
className: 'dshTurnCost_chip',
|
|
1459
|
+
'data-tone': tone,
|
|
1460
|
+
},
|
|
1461
|
+
h(
|
|
1462
|
+
'button',
|
|
1463
|
+
{
|
|
1464
|
+
ref: chipRef,
|
|
1465
|
+
type: 'button',
|
|
1466
|
+
className: 'dshTurnCost_main',
|
|
1467
|
+
title: summary,
|
|
1468
|
+
'aria-label': summary,
|
|
1469
|
+
'aria-expanded': open,
|
|
1470
|
+
'aria-controls': open ? 'dsh-turn-cost-detail' : undefined,
|
|
1471
|
+
'aria-describedby': open ? 'dsh-turn-cost-detail' : undefined,
|
|
1472
|
+
onClick: () => {
|
|
1473
|
+
if (pinned) {
|
|
1474
|
+
dismiss()
|
|
1475
|
+
} else {
|
|
1476
|
+
setPinned(true)
|
|
1477
|
+
cancelClose()
|
|
1478
|
+
}
|
|
1479
|
+
},
|
|
1480
|
+
},
|
|
1481
|
+
h('span', { className: 'dshTurnCost_dot', 'aria-hidden': true }),
|
|
1482
|
+
h('span', { className: 'dshTurnCost_amount' }, valueLabel),
|
|
1483
|
+
),
|
|
1484
|
+
),
|
|
1485
|
+
open
|
|
1486
|
+
? h(Panel, {
|
|
1487
|
+
key: 'panel',
|
|
1488
|
+
estimate,
|
|
1489
|
+
turnsLabel,
|
|
1490
|
+
settings,
|
|
1491
|
+
priceSource: priceInfo.source,
|
|
1492
|
+
holidaySource: holidayInfo.source,
|
|
1493
|
+
t,
|
|
1494
|
+
pinned,
|
|
1495
|
+
onUnpin: dismiss,
|
|
1496
|
+
onMetric: updateMetric,
|
|
1497
|
+
onThreshold: updateThreshold,
|
|
1498
|
+
onReset: resetSettings,
|
|
1499
|
+
onMouseEnter: cancelClose,
|
|
1500
|
+
onMouseLeave: scheduleClose,
|
|
1501
|
+
})
|
|
1502
|
+
: null,
|
|
1503
|
+
)
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
const inject = ['slots', 'locale']
|
|
1507
|
+
|
|
1508
|
+
/** @param ctx - the page plugin's context (slots, locale, effects). */
|
|
1509
|
+
function apply(ctx) {
|
|
1510
|
+
ctx.effect(() => ctx.locale.register(NS, 'zh', ZH), 'dsh-continue-cost: zh dictionary')
|
|
1511
|
+
ctx.effect(() => ctx.locale.register(NS, 'en', EN), 'dsh-continue-cost: en dictionary')
|
|
1512
|
+
const t = ctx.locale.bind(NS)
|
|
1513
|
+
|
|
1514
|
+
ctx.effect(() => {
|
|
1515
|
+
void refreshPrices()
|
|
1516
|
+
void refreshHolidays()
|
|
1517
|
+
const timer = window.setInterval(() => {
|
|
1518
|
+
void refreshPrices()
|
|
1519
|
+
void refreshHolidays()
|
|
1520
|
+
}, 24 * 60 * 60 * 1000)
|
|
1521
|
+
return () => {
|
|
1522
|
+
window.clearInterval(timer)
|
|
1523
|
+
}
|
|
1524
|
+
}, 'dsh-continue-cost: official price and holiday refresh')
|
|
1525
|
+
|
|
1526
|
+
ctx.slots.inject('conversation.input.right', function* () {
|
|
1527
|
+
yield ctx.slots.register(
|
|
1528
|
+
{
|
|
1529
|
+
name: 'conversation.input.right',
|
|
1530
|
+
id: 'turn-cost-meter',
|
|
1531
|
+
order: 21,
|
|
1532
|
+
label: () => t('chip.title'),
|
|
1533
|
+
inject: () => ({ t }),
|
|
1534
|
+
},
|
|
1535
|
+
TurnCostChip,
|
|
1536
|
+
)
|
|
1537
|
+
})
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
module.exports = { apply, inject, name: NAME }
|
|
1541
|
+
return module.exports
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
window.__ModuleLoader__.load({
|
|
1546
|
+
id: NAME,
|
|
1547
|
+
factory: makeFactory(),
|
|
1548
|
+
})
|
|
1549
|
+
})()
|