dsh-model-billing 0.1.2 → 0.3.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/client.js CHANGED
@@ -1,1787 +1,2281 @@
1
- window.__ModuleLoader__.load({
2
- id: 'dsh-model-billing',
3
- factory(require) {
4
- const React = require('react')
5
- const ReactDOM = require('react-dom')
6
- const h = React.createElement
7
- const {
8
- Fragment,
9
- useEffect,
10
- useId,
11
- useLayoutEffect,
12
- useMemo,
13
- useRef,
14
- useState,
15
- useSyncExternalStore,
16
- } = React
17
-
18
- // ---------------------------------------------------------------------
19
- // Locale
20
- // ---------------------------------------------------------------------
21
-
22
- const STRINGS = {
23
- zh: {
24
- nav: '模型与费用',
25
- title: '模型与费用',
26
- intro: '调整已配置模型的顺序,并填写每百万 tokens 的价格。金额根据会话日志估算所有模型;DeepSeek 使用内置峰谷价。',
27
- loading: '正在加载模型目录…',
28
- loadFailed: '模型目录加载失败',
29
- retry: '重试',
30
- modelsCount: '{count} 个模型',
31
- save: '保存',
32
- saving: '保存中…',
33
- saved: '已保存',
34
- unsaved: '有未保存的修改',
35
- undo: '撤销修改',
36
- orderHint: '用 ↑ / ↓ 调整顺序;顺序直接决定对话框右下角模型选择器中的排列,也用于费用明细。',
37
- noModels: '当前没有可用的已配置模型。',
38
- up: '上移',
39
- down: '下移',
40
- cacheHitPrice: '输入 · 缓存命中',
41
- cacheMissPrice: '输入 · 缓存未命中',
42
- outputPrice: '输出',
43
- perMillion: '元 / 百万 tokens',
44
- deepseekTag: 'DeepSeek',
45
- deepseekNote: '官方峰谷价只读;DeepSeek 已按事件发生时间自动计入估算。',
46
- officialPrice: '官方定价(只读)',
47
- peak: '高峰',
48
- offPeak: '空闲',
49
- deepseekSchedule: '高峰为北京时间周一至周五 9:00–12:00、14:00–18:00(法定节假日除外);其余时段为空闲。',
50
- pricePlaceholder: '未设置',
51
- priceUnset: '未定价',
52
- priceHitShort: '命中',
53
- priceMissShort: '未命中',
54
- priceOutShort: '输出',
55
- priceUnit: '元/M',
56
- invalidPrice: '价格必须是非负数字,或留空表示未设置。',
57
- saveFailed: '保存失败:{message}',
58
- savedAt: '已保存于 {time}',
59
- formula: '估算公式:缓存命中输入 × 命中价 +(未缓存输入 + 缓存写入)× 未命中价 + 输出 × 输出价。',
60
- formulaNote: '价格按每百万 tokens 计。缓存写入按缓存未命中价计算;未配置价格的模型不产生金额。',
61
- singlePrice: '价格',
62
- settingsOpen: '在设置中编辑',
63
- costEstimate: '费用估算',
64
- costDetails: '费用明细',
65
- close: '关闭',
66
- thisTurn: '本轮',
67
- sessionTotal: '本会话',
68
- cacheHit: '缓存命中率',
69
- tokens: '输入 / 输出',
70
- turn: '轮次',
71
- content: '内容',
72
- time: '时间',
73
- model: '使用模型',
74
- cost: '费用',
75
- byModel: '按模型',
76
- excludedShort: '不计入',
77
- partial: '部分未定价',
78
- partialShort: '部分未定价',
79
- partialNote: '有非 DeepSeek 调用尚未配置完整价格,合计只包含已定价部分。',
80
- estimateNote: '金额由会话日志中的 token 用量和缓存命中估算;DeepSeek 按事件时间使用内置峰谷价,实际账单以提供方为准。',
81
- listSep: '、',
82
- turnCost: '费用',
83
- turnTokens: '本轮 Token',
84
- displaySection: '轮尾显示',
85
- displayHint: '控制每轮结束后在对话尾部显示的内容;修改后点“保存”生效。',
86
- displayModels: '使用模型',
87
- displayProvider: '模型提供商',
88
- displayCost: '本轮费用',
89
- displayTokens: 'Token 用量',
90
- displayCacheHit: '缓存命中率',
91
- displayLabels: '显示文字标签',
92
- displayFontSize: '字号',
93
- displayDensity: '间距',
94
- displayWeight: '字重',
95
- fontSizeSmall: '小',
96
- fontSizeNormal: '标准',
97
- fontSizeLarge: '大',
98
- densityCompact: '紧凑',
99
- densityComfortable: '舒适',
100
- weightNormal: '常规',
101
- weightBold: '加粗',
102
- pickerSection: '模型选择器',
103
- takeoverPicker: '接管模型选择器',
104
- takeoverHint: '开启后使用本插件按自定义顺序排列的模型选择器;关闭后恢复 DSH 内置选择器。',
105
- chooseModel: '选择模型',
106
- loadingModels: '加载模型…',
107
- searchModel: '搜索模型',
108
- noMatch: '没有匹配的模型',
109
- pickerEmpty: '暂无可用模型',
110
- reasoningEffort: '推理强度',
111
- providerDefault: '提供方默认',
112
- switching: '切换中…',
113
- pickerRetry: '重新加载',
114
- pickerAria: '选择模型与推理强度',
115
- pickerUnavailable: '模型目录尚未就绪,请刷新页面',
116
- },
117
- en: {
118
- nav: 'Models & Cost',
119
- title: 'Models & Cost',
120
- intro: 'Reorder configured models and enter prices per million tokens. Amounts estimate every model from the session log; DeepSeek uses its built-in peak/off-peak prices.',
121
- loading: 'Loading the model catalog…',
122
- loadFailed: 'Could not load the model catalog',
123
- retry: 'Retry',
124
- modelsCount: '{count} models',
125
- save: 'Save',
126
- saving: 'Saving…',
127
- saved: 'Saved',
128
- unsaved: 'Unsaved changes',
129
- undo: 'Discard changes',
130
- orderHint: 'Use ↑ / ↓ to reorder. This order is used directly by the model picker at the bottom-right of the composer, and by the cost details.',
131
- noModels: 'No configured models are available.',
132
- up: 'Move up',
133
- down: 'Move down',
134
- cacheHitPrice: 'Input · cache hit',
135
- cacheMissPrice: 'Input · cache miss',
136
- outputPrice: 'Output',
137
- perMillion: 'CNY / million tokens',
138
- deepseekTag: 'DeepSeek',
139
- deepseekNote: 'Official peak/off-peak prices are read-only; DeepSeek is now billed automatically at the event time.',
140
- officialPrice: 'Official prices (read-only)',
141
- peak: 'Peak',
142
- offPeak: 'Off-peak',
143
- deepseekSchedule: 'Peak: Beijing time Mon–Fri 09:00–12:00 and 14:00–18:00, excluding Chinese statutory holidays; all other times are off-peak.',
144
- pricePlaceholder: 'Not set',
145
- priceUnset: 'Not priced',
146
- priceHitShort: 'hit',
147
- priceMissShort: 'miss',
148
- priceOutShort: 'out',
149
- priceUnit: 'CNY/M',
150
- invalidPrice: 'Prices must be non-negative numbers, or blank when unset.',
151
- saveFailed: 'Save failed: {message}',
152
- savedAt: 'Saved at {time}',
153
- formula: 'Estimate: cached input × hit price + (uncached input + cache write) × miss price + output × output price.',
154
- formulaNote: 'Prices are per million tokens. Cache writes use the cache-miss price; models without a full price set produce no amount.',
155
- singlePrice: 'Prices',
156
- settingsOpen: 'Edit in Settings',
157
- costEstimate: 'Cost estimate',
158
- costDetails: 'Cost details',
159
- close: 'Close',
160
- thisTurn: 'Turn',
161
- sessionTotal: 'Session',
162
- cacheHit: 'Cache hit rate',
163
- tokens: 'Input / output',
164
- turn: 'Turn',
165
- content: 'Content',
166
- time: 'Time',
167
- model: 'Model',
168
- cost: 'Cost',
169
- byModel: 'By model',
170
- excludedShort: 'Excluded',
171
- partial: 'partly unpriced',
172
- partialShort: 'partly unpriced',
173
- partialNote: 'Some non-DeepSeek calls do not have a complete price set; the total includes only priced calls.',
174
- estimateNote: 'Amounts are estimated from token usage and cache hits in the session log; DeepSeek uses built-in peak/off-peak prices at the event time, and the provider bill is authoritative.',
175
- listSep: ', ',
176
- turnCost: 'Cost',
177
- turnTokens: 'Turn tokens',
178
- displaySection: 'Turn-tail display',
179
- displayHint: 'Choose what appears below each completed turn; click Save to apply.',
180
- displayModels: 'Models used',
181
- displayProvider: 'Model provider',
182
- displayCost: 'Turn cost',
183
- displayTokens: 'Token usage',
184
- displayCacheHit: 'Cache hit rate',
185
- displayLabels: 'Show text labels',
186
- displayFontSize: 'Font size',
187
- displayDensity: 'Spacing',
188
- displayWeight: 'Font weight',
189
- fontSizeSmall: 'Small',
190
- fontSizeNormal: 'Normal',
191
- fontSizeLarge: 'Large',
192
- densityCompact: 'Compact',
193
- densityComfortable: 'Comfortable',
194
- weightNormal: 'Regular',
195
- weightBold: 'Bold',
196
- pickerSection: 'Model picker',
197
- takeoverPicker: 'Take over the model picker',
198
- takeoverHint: 'On: use this plugin’s picker with your custom model order. Off: restore the built-in DSH picker.',
199
- chooseModel: 'Select model',
200
- loadingModels: 'Loading models…',
201
- searchModel: 'Search models',
202
- noMatch: 'No matching model',
203
- pickerEmpty: 'No model available',
204
- reasoningEffort: 'Reasoning effort',
205
- providerDefault: 'Provider default',
206
- switching: 'Switching…',
207
- pickerRetry: 'Reload',
208
- pickerAria: 'Select model and reasoning effort',
209
- pickerUnavailable: 'The model directory is not ready; reload the page',
210
- },
211
- }
212
-
213
- const t = (key, values) => {
214
- const active = localeService?.getSnapshot?.().active ?? 'zh'
215
- const dict = active.toLowerCase().startsWith('en') ? STRINGS.en : STRINGS.zh
216
- const template = dict[key] ?? STRINGS.zh[key] ?? key
217
- return values === undefined
218
- ? template
219
- : template.replace(/\{(\w+)\}/g, (match, name) => values[name] === undefined ? match : String(values[name]))
220
- }
221
-
222
- let localeService
223
- let modelDirectories
224
- let modelDirectoryRevision = 0
225
- const modelDirectoryListeners = new Set()
226
-
227
- function publishModelDirectories(next) {
228
- if (next === undefined || next === modelDirectories) return
229
- modelDirectories = next
230
- modelDirectoryRevision += 1
231
- for (const listener of [...modelDirectoryListeners]) listener()
232
- }
233
-
234
- function subscribeModelDirectories(listener) {
235
- modelDirectoryListeners.add(listener)
236
- return () => modelDirectoryListeners.delete(listener)
237
- }
238
-
239
- function useModelDirectoriesRevision() {
240
- return useSyncExternalStore(
241
- subscribeModelDirectories,
242
- () => modelDirectoryRevision,
243
- () => 0,
244
- )
245
- }
246
-
247
- function subscribeLocale(listener) {
248
- return localeService?.subscribe?.(listener) ?? (() => {})
249
- }
250
-
251
- function localeRevision() {
252
- return localeService?.getSnapshot?.().revision ?? 0
253
- }
254
-
255
- function useT() {
256
- useSyncExternalStore(subscribeLocale, localeRevision, () => 0)
257
- return t
258
- }
259
-
260
- const DISPLAY_DEFAULTS = Object.freeze({
261
- showModels: true,
262
- showProvider: false,
263
- showCost: true,
264
- showTokens: false,
265
- showCacheHit: false,
266
- showLabels: true,
267
- takeoverPicker: true,
268
- fontSize: 'normal',
269
- density: 'comfortable',
270
- fontWeight: 'normal',
271
- })
272
-
273
- const DISPLAY_STORAGE_KEY = 'dsh-model-billing.display'
274
-
275
- function readStoredDisplay() {
276
- try {
277
- const raw = localStorage.getItem(DISPLAY_STORAGE_KEY)
278
- if (raw === null) return null
279
- const parsed = JSON.parse(raw)
280
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null
281
- } catch {
282
- return null
283
- }
284
- }
285
-
286
- function writeStoredDisplay(value) {
287
- try {
288
- localStorage.setItem(DISPLAY_STORAGE_KEY, JSON.stringify(value))
289
- } catch {
290
- // Storage may be unavailable in restricted browser contexts.
291
- }
292
- }
293
-
294
- function clearStoredDisplay() {
295
- try {
296
- localStorage.removeItem(DISPLAY_STORAGE_KEY)
297
- } catch {
298
- // Ignore unavailable storage.
299
- }
300
- }
301
-
302
- function readDisplay(data) {
303
- const source = data?.display
304
- const server = source !== null && typeof source === 'object' && !Array.isArray(source)
305
- ? { ...DISPLAY_DEFAULTS, ...source }
306
- : { ...DISPLAY_DEFAULTS }
307
- const stored = readStoredDisplay()
308
- return stored === null ? server : { ...server, ...stored }
309
- }
310
-
311
- // ---------------------------------------------------------------------
312
- // Shared catalog state
313
- // ---------------------------------------------------------------------
314
-
315
- const catalog = {
316
- snap: { status: 'idle', data: null, error: null },
317
- listeners: new Set(),
318
- inflight: null,
319
- generation: 0,
320
- }
321
-
322
- async function requestJson(url, options) {
323
- const response = await fetch(url, {
324
- credentials: 'same-origin',
325
- cache: 'no-store',
326
- ...options,
327
- headers: {
328
- accept: 'application/json',
329
- ...(options?.headers ?? {}),
330
- },
331
- })
332
- let body
333
- try {
334
- body = await response.json()
335
- } catch {
336
- throw new Error(`HTTP ${response.status}`)
337
- }
338
- if (!response.ok || body?.ok === false) {
339
- throw new Error(body?.message ?? `HTTP ${response.status}`)
340
- }
341
- return body
342
- }
343
-
344
- function emitCatalog() {
345
- for (const listener of [...catalog.listeners]) listener()
346
- }
347
-
348
- function setCatalog(draft) {
349
- catalog.snap = { ...catalog.snap, ...draft }
350
- emitCatalog()
351
- }
352
-
353
- async function ensureCatalog(force = false) {
354
- if (!force && catalog.snap.status === 'ready') return catalog.snap.data
355
- if (catalog.inflight !== null && !force) return catalog.inflight
356
- catalog.generation += 1
357
- const generation = catalog.generation
358
- setCatalog({ status: 'loading', error: null })
359
- const operation = requestJson('/model-billing/catalog')
360
- .then((data) => {
361
- if (generation !== catalog.generation) return data
362
- setCatalog({ status: 'ready', data, error: null })
363
- return data
364
- })
365
- .catch((error) => {
366
- if (generation === catalog.generation) {
367
- setCatalog({ status: 'error', error: error instanceof Error ? error.message : String(error) })
368
- }
369
- return null
370
- })
371
- .finally(() => {
372
- if (catalog.inflight === operation) catalog.inflight = null
373
- })
374
- catalog.inflight = operation
375
- return operation
376
- }
377
-
378
- function subscribeCatalog(listener) {
379
- catalog.listeners.add(listener)
380
- if (catalog.snap.status === 'idle') void ensureCatalog()
381
- return () => catalog.listeners.delete(listener)
382
- }
383
-
384
- function catalogSnapshot() {
385
- return catalog.snap
386
- }
387
-
388
- function useCatalog() {
389
- return useSyncExternalStore(subscribeCatalog, catalogSnapshot, catalogSnapshot)
390
- }
391
-
392
- // ---------------------------------------------------------------------
393
- // Shared session usage state
394
- // ---------------------------------------------------------------------
395
-
396
- const usageSlots = new Map()
397
-
398
- function usageSlot(sessionId) {
399
- let slot = usageSlots.get(sessionId)
400
- if (slot === undefined) {
401
- slot = {
402
- snap: { status: 'idle', data: null, error: null },
403
- listeners: new Set(),
404
- inflight: null,
405
- generation: 0,
406
- revision: null,
407
- }
408
- usageSlots.set(sessionId, slot)
409
- }
410
- return slot
411
- }
412
-
413
- function emitUsage(slot) {
414
- for (const listener of [...slot.listeners]) listener()
415
- }
416
-
417
- function ensureUsage(sessionId, revision, force = false) {
418
- const slot = usageSlot(sessionId)
419
- if (!force && slot.revision === revision && slot.snap.status !== 'error') return
420
- if (slot.inflight !== null && slot.inflight === revision && !force) return
421
- slot.revision = revision
422
- slot.generation += 1
423
- const generation = slot.generation
424
- slot.snap = { ...slot.snap, status: 'loading', error: null }
425
- emitUsage(slot)
426
- const operation = requestJson(`/model-billing/usage?sessionId=${encodeURIComponent(sessionId)}`)
427
- .then((data) => {
428
- if (generation !== slot.generation) return
429
- slot.snap = { status: 'ready', data, error: null }
430
- emitUsage(slot)
431
- })
432
- .catch((error) => {
433
- if (generation !== slot.generation) return
434
- slot.snap = {
435
- status: 'error',
436
- data: slot.snap.data,
437
- error: error instanceof Error ? error.message : String(error),
438
- }
439
- emitUsage(slot)
440
- })
441
- .finally(() => {
442
- if (slot.inflight === operation) slot.inflight = null
443
- })
444
- slot.inflight = operation
445
- return operation
446
- }
447
-
448
- function useSessionUsage(sessionId, revision) {
449
- const slot = usageSlot(sessionId)
450
- const snap = useSyncExternalStore(
451
- (listener) => {
452
- slot.listeners.add(listener)
453
- return () => slot.listeners.delete(listener)
454
- },
455
- () => slot.snap,
456
- () => slot.snap,
457
- )
458
- useEffect(() => {
459
- if (sessionId !== undefined && revision !== null) ensureUsage(sessionId, revision)
460
- }, [sessionId, revision])
461
- return snap
462
- }
463
-
464
- function tokenUsageRevision(tokenUsage) {
465
- if (tokenUsage === undefined || tokenUsage === null) return 'none'
466
- return [
467
- tokenUsage.uncachedInputTokens ?? '',
468
- tokenUsage.outputTokens ?? '',
469
- tokenUsage.cacheReadTokens ?? '',
470
- tokenUsage.cacheWriteTokens ?? '',
471
- ].join(':')
472
- }
473
-
474
- // ---------------------------------------------------------------------
475
- // Formatting
476
- // ---------------------------------------------------------------------
477
-
478
- function formatMoney(value) {
479
- if (value === null || value === undefined || !Number.isFinite(value)) return '—'
480
- if (value === 0) return '¥0'
481
- const fixed = value.toFixed(2)
482
- return fixed === '0.00' ? '<¥0.01' : `¥${fixed}`
483
- }
484
-
485
- function formatTokens(value) {
486
- if (!Number.isFinite(value)) return '—'
487
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(2)}M`
488
- if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`
489
- return String(Math.round(value))
490
- }
491
-
492
- function formatPercent(value) {
493
- return value === null || value === undefined ? '—' : `${(value * 100).toFixed(1)}%`
494
- }
495
-
496
- function formatPrice(value) {
497
- if (value === null || value === undefined) return '—'
498
- return String(Number(value.toFixed(6)))
499
- }
500
-
501
- function PriceLines({ pricing, translate }) {
502
- if (pricing?.builtin === true) {
503
- const line = (label, prices) =>
504
- `${label} ${translate('priceHitShort')} ${formatPrice(prices?.cacheHit)} · ${translate('priceMissShort')} ${formatPrice(prices?.cacheMiss)} · ${translate('priceOutShort')} ${formatPrice(prices?.output)} ${translate('priceUnit')}`
505
- return h('div', { className: 'mb-picker-prices' },
506
- h('div', { className: 'mb-picker-price-line' }, line(translate('peak'), pricing.peak)),
507
- h('div', { className: 'mb-picker-price-line' }, line(translate('offPeak'), pricing.offPeak)))
508
- }
509
- const hasAny = pricing !== null && pricing !== undefined
510
- && [pricing.cacheHit, pricing.cacheMiss, pricing.output].some((value) => typeof value === 'number')
511
- if (!hasAny) {
512
- return h('div', { className: 'mb-picker-prices' }, translate('priceUnset'))
513
- }
514
- return h('div', { className: 'mb-picker-prices' },
515
- h('div', { className: 'mb-picker-price-line' },
516
- `${translate('priceHitShort')} ${formatPrice(pricing.cacheHit)} · ${translate('priceMissShort')} ${formatPrice(pricing.cacheMiss)} · ${translate('priceOutShort')} ${formatPrice(pricing.output)} ${translate('priceUnit')}`))
517
- }
518
-
519
- function timeText(timestamp) {
520
- if (!Number.isFinite(timestamp) || timestamp <= 0) return ''
521
- try {
522
- return new Date(timestamp).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
523
- } catch {
524
- return ''
525
- }
526
- }
527
-
528
- // ---------------------------------------------------------------------
529
- // Styles
530
- // ---------------------------------------------------------------------
531
-
532
- const CSS = `
533
- .mb-page { color: var(--dsw-alias-label-primary); font-size: 13px; line-height: 1.5; padding: 4px 0 28px; }
534
- .mb-page * { box-sizing: border-box; }
535
- .mb-title { margin: 0 0 4px; font-size: 18px; font-weight: 600; }
536
- .mb-intro { margin: 0 0 14px; color: var(--dsw-alias-label-secondary); max-width: 760px; }
537
- .mb-toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 14px 0; }
538
- .mb-muted { color: var(--dsw-alias-label-secondary); }
539
- .mb-spacer { flex: 1; }
540
- .mb-btn { appearance: none; border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); border-radius: 7px; height: 30px; padding: 0 12px; font: inherit; cursor: pointer; }
541
- .mb-btn:hover:not(:disabled) { background: var(--dsw-alias-bg-layer-2); }
542
- .mb-btn:disabled { opacity: .45; cursor: default; }
543
- .mb-btn-primary { background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-bg-base); font-weight: 600; }
544
- .mb-btn-primary:hover:not(:disabled) { background: var(--dsw-alias-brand-primary); opacity: .9; }
545
- .mb-btn-icon { width: 28px; height: 28px; padding: 0; font-size: 13px; }
546
- .mb-status { color: var(--dsw-alias-label-secondary); min-height: 18px; }
547
- .mb-status[data-tone="error"] { color: var(--dsw-alias-state-error-primary); }
548
- .mb-status[data-tone="success"] { color: var(--dsw-alias-state-success-primary); }
549
- .mb-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; max-width: 980px; }
550
- .mb-card { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); border-radius: 10px; padding: 12px 14px; }
551
- .mb-card-head { display: flex; align-items: flex-start; gap: 12px; }
552
- .mb-index { width: 26px; height: 26px; border-radius: 7px; background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-secondary); display: grid; place-items: center; font-variant-numeric: tabular-nums; flex: none; }
553
- .mb-name { font-weight: 600; font-size: 14px; }
554
- .mb-sub { color: var(--dsw-alias-label-secondary); font-size: 12px; overflow-wrap: anywhere; }
555
- .mb-head-actions { margin-left: auto; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; justify-content: flex-end; }
556
- .mb-tag { display: inline-block; margin-left: 6px; padding: 1px 6px; border-radius: 999px; background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-secondary); font-size: 11px; font-weight: 500; vertical-align: 1px; }
557
- .mb-tag-excluded { color: var(--dsw-alias-state-warn-primary); }
558
- .mb-prices { display: grid; gap: 10px; margin-top: 12px; }
559
- .mb-price-group { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; padding: 10px 12px 12px; }
560
- .mb-price-group-title { display: flex; gap: 8px; align-items: baseline; margin-bottom: 8px; font-weight: 600; }
561
- .mb-price-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
562
- .mb-field { display: grid; gap: 4px; min-width: 0; }
563
- .mb-field-label { color: var(--dsw-alias-label-secondary); font-size: 11px; }
564
- .mb-input { width: 100%; height: 30px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); padding: 0 8px; font: inherit; font-variant-numeric: tabular-nums; }
565
- .mb-input:focus { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -1px; }
566
- .mb-note { margin: 8px 0 0; color: var(--dsw-alias-label-secondary); font-size: 12px; }
567
- .mb-warn { margin: 6px 0 0; color: var(--dsw-alias-state-warn-primary); font-size: 12px; }
568
- .mb-empty { border: 1px dashed var(--dsw-alias-border-l2); border-radius: 10px; padding: 28px; text-align: center; color: var(--dsw-alias-label-secondary); }
569
- .mb-footer-note { max-width: 980px; margin-top: 14px; color: var(--dsw-alias-label-secondary); font-size: 12px; }
570
- .mb-dock { align-self: center; display: flex; flex-direction: column; align-items: flex-start; color: var(--dsw-alias-label-tertiary); font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px); line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px)); }
571
- .mb-dock-trigger { appearance: none; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; padding: 1px 8px; border-radius: var(--dsw-radius-sm); display: inline-flex; align-items: center; gap: 6px; cursor: pointer; text-align: left; max-width: 100%; flex-wrap: nowrap; }
572
- .mb-dock-trigger:hover, .mb-dock-trigger[aria-expanded="true"] { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-secondary); }
573
- .mb-dock-amount { color: var(--dsw-alias-label-secondary); font-weight: 500; font-variant-numeric: tabular-nums; }
574
- .mb-dock-sep { opacity: .55; }
575
- .mb-dock-icon { flex: none; width: 14px; height: 14px; }
576
- .mb-dock-caret { font-size: 10px; opacity: .7; }
577
- .mb-panel { box-sizing: border-box; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-menu-surface-fill, var(--dsw-alias-bg-layer-1)); border-radius: var(--dsw-radius-lg, 10px); padding: 10px 12px; color: var(--dsw-alias-label-primary); }
578
- .mb-panel-floating { position: fixed; z-index: 1200; max-width: calc(100vw - 24px); max-height: min(430px, calc(100vh - 96px)); overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: var(--dsw-alias-scrollbar-bg-l2, var(--dsw-alias-border-l2)) transparent; box-shadow: var(--dsw-elevation-prominent); backdrop-filter: var(--dsw-menu-backdrop-filter, none); }
579
- .mb-panel-head { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; }
580
- .mb-panel-title { font-weight: 600; }
581
- .mb-panel-close { margin-left: auto; width: 24px; height: 24px; border: 0; border-radius: var(--dsw-radius-sm); background: 0 0; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 18px; line-height: 20px; cursor: pointer; }
582
- .mb-panel-close:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
583
- .mb-summary { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-bottom: 10px; }
584
- .mb-summary-item { background: var(--dsw-alias-bg-layer-2); border-radius: 7px; padding: 7px 9px; min-width: 0; }
585
- .mb-summary-key { color: var(--dsw-alias-label-secondary); font-size: 11px; }
586
- .mb-summary-value { font-variant-numeric: tabular-nums; font-weight: 600; overflow-wrap: anywhere; }
587
- .mb-table { width: 100%; border-collapse: collapse; font-size: 12px; }
588
- .mb-table th, .mb-table td { text-align: left; padding: 4px 5px; border-bottom: 1px solid var(--dsw-alias-border-l1); vertical-align: top; }
589
- .mb-table th { color: var(--dsw-alias-label-secondary); font-weight: 500; font-size: 11px; }
590
- .mb-table td.num, .mb-table th.num { text-align: right; font-variant-numeric: tabular-nums; }
591
- .mb-table tr:last-child td { border-bottom: 0; }
592
- .mb-turn-table { table-layout: fixed; }
593
- .mb-turn-table th, .mb-turn-table td, .mb-turn-table th.num, .mb-turn-table td.num { text-align: left; }
594
- .mb-turn-table th:nth-child(1), .mb-turn-table td:nth-child(1) { width: 5%; }
595
- .mb-turn-table th:nth-child(2), .mb-turn-table td:nth-child(2) { width: 25.5%; }
596
- .mb-turn-table th:nth-child(3), .mb-turn-table td:nth-child(3) { width: 12.5%; }
597
- .mb-turn-table th:nth-child(4), .mb-turn-table td:nth-child(4) { width: 21%; }
598
- .mb-turn-table th:nth-child(5), .mb-turn-table td:nth-child(5) { width: 10%; }
599
- .mb-turn-table th:nth-child(6), .mb-turn-table td:nth-child(6) { width: 16%; }
600
- .mb-turn-table th:nth-child(7), .mb-turn-table td:nth-child(7) { width: 10%; }
601
- .mb-turn-preview, .mb-turn-model { color: var(--dsw-alias-label-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
602
- .mb-turn-model { color: var(--dsw-alias-label-primary); }
603
- .mb-panel-note { margin: 9px 0 0; color: var(--dsw-alias-label-secondary); font-size: 11px; }
604
- .mb-turn { color: var(--dsw-alias-label-secondary); font-size: 12px; font-variant-numeric: tabular-nums; display: inline-flex; flex-wrap: wrap; align-items: baseline; column-gap: 10px; row-gap: 2px; max-width: 100%; }
605
- .mb-turn[data-size="small"] { font-size: 11px; }
606
- .mb-turn[data-size="large"] { font-size: 13px; }
607
- .mb-turn[data-density="compact"] { column-gap: 6px; }
608
- .mb-turn-item { white-space: nowrap; }
609
- .mb-turn strong { color: inherit; font-weight: 600; }
610
- .mb-turn[data-weight="normal"] { font-weight: 400; }
611
- .mb-turn[data-weight="normal"] strong { font-weight: 400; }
612
- .mb-turn[data-weight="bold"] { font-weight: 600; }
613
- .mb-turn[data-weight="bold"] strong { font-weight: 600; }
614
- .mb-turn-partial { color: var(--dsw-alias-state-warn-primary); }
615
- .mb-display { border: 1px solid var(--dsw-alias-border-l1); border-radius: 10px; padding: 12px 14px; margin: 10px 0 14px; background: var(--dsw-alias-bg-layer-2); }
616
- .mb-display-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; }
617
- .mb-display-title { font-weight: 600; }
618
- .mb-display-hint { color: var(--dsw-alias-label-secondary); font-size: 12px; }
619
- .mb-check-grid { display: flex; flex-wrap: wrap; gap: 8px 18px; }
620
- .mb-check { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; }
621
- .mb-check.is-disabled { opacity: .55; cursor: default; }
622
- .mb-check input { width: 15px; height: 15px; accent-color: var(--dsw-alias-brand-primary); }
623
- .mb-display-controls { display: flex; flex-wrap: wrap; gap: 10px 18px; margin-top: 12px; }
624
- .mb-select { height: 30px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); padding: 0 8px; font: inherit; }
625
- .mb-select:focus { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -1px; }
626
- .mb-picker { position: relative; display: flex; min-width: 0; }
627
- .mb-picker-trigger { border-radius: var(--dsw-radius-sm); min-width: 0; max-width: min(360px, 45cqw); height: 28px; color: var(--dsw-alias-label-secondary); cursor: pointer; background: 0 0; border: none; outline: none; align-items: center; gap: 4px; padding: 0 4px 0 8px; font-size: 13px; font-weight: 400; line-height: 20px; display: flex; }
628
- .mb-picker-trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
629
- .mb-picker-trigger:focus-visible { box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }
630
- .mb-picker-trigger:disabled { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-secondary)); cursor: default; }
631
- .mb-picker-icon { display: var(--dsh-composer-model-icon-display, none); flex: none; }
632
- .mb-picker-name { color: inherit; text-overflow: ellipsis; white-space: nowrap; min-width: 0; overflow: hidden; display: var(--dsh-composer-model-text-display, block); }
633
- .mb-picker-trigger-effort { text-overflow: ellipsis; white-space: nowrap; min-width: 0; color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); flex-shrink: 1000; overflow: hidden; display: var(--dsh-composer-model-text-display, block); }
634
- .mb-picker-chevron { color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); flex: none; transition: transform .12s; }
635
- .mb-picker-chevron-open { transform: rotate(180deg); }
636
- .mb-picker-menu { box-sizing: border-box; z-index: 1100; width: min(360px, calc(100vw - 32px)); max-width: min(360px, calc(100vw - 32px)); max-height: min(480px, calc(100vh - 96px)); box-shadow: var(--dsw-elevation-prominent); background: var(--dsw-menu-surface-fill, var(--dsw-alias-bg-layer-1)); backdrop-filter: var(--dsw-menu-backdrop-filter, none); color: var(--dsw-alias-label-primary); border: 0; border-radius: var(--dsw-radius-lg, 10px); flex-direction: column; padding: 10px; display: flex; position: fixed; overflow: hidden; }
637
- .mb-picker-search { box-sizing: border-box; border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-layer-2); border: 1px solid var(--dsw-alias-border-l1); height: 32px; margin: 0 0 6px; padding: 0 9px; font: inherit; font-size: 13px; color: var(--dsw-alias-label-primary); width: 100%; flex: none; }
638
- .mb-picker-search::placeholder { color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); }
639
- .mb-picker-search:focus { border-color: var(--dsw-alias-state-business-primary); outline: none; }
640
- .mb-picker-list { min-height: 0; overflow-y: auto; padding: 0 2px; display: flex; flex-direction: column; }
641
- .mb-picker-group { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); background: var(--dsw-alias-menu-group-header-fill, var(--dsw-menu-surface-fill, var(--dsw-alias-bg-layer-1))); position: sticky; top: 0; z-index: 1; margin-top: 2px; padding: 10px 10px 6px; font-size: 11px; font-weight: 500; line-height: 16px; }
642
- .mb-picker-row { box-sizing: border-box; border-radius: var(--dsw-radius-md); width: auto; min-width: 100%; color: inherit; text-align: left; cursor: pointer; background: 0 0; border: none; outline: none; align-items: center; gap: 8px; padding: 10px; font: inherit; display: flex; }
643
- .mb-picker-row + .mb-picker-row { margin-top: 2px; }
644
- .mb-picker-row:hover:not(:disabled), .mb-picker-row:focus-visible { background: var(--dsw-alias-interactive-bg-hover); }
645
- .mb-picker-row:disabled { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-secondary)); cursor: default; }
646
- .mb-picker-option-copy { flex-direction: column; flex: 1; min-width: 0; gap: 4px; display: flex; }
647
- .mb-picker-model { color: inherit; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 400; line-height: 20px; overflow: hidden; }
648
- .mb-picker-prices { color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); font-size: 11px; line-height: 17px; font-variant-numeric: tabular-nums; }
649
- .mb-picker-price-line { white-space: normal; overflow-wrap: anywhere; }
650
- .mb-picker-check { color: var(--dsw-alias-label-primary); flex: 0 0 14px; place-items: center; display: grid; font-size: 12px; }
651
- .mb-picker-check svg { width: 14px; height: 14px; }
652
- .mb-picker-empty { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); padding: 8px; font-size: 12px; line-height: 18px; }
653
- .mb-picker-divider { border-top: 1px solid var(--dsw-alias-border-l1); margin: 3px 0; }
654
- .mb-picker-efforts { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; padding: 2px 4px 4px; }
655
- .mb-picker-efforts-label { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); font-size: 11px; margin-right: 2px; }
656
- .mb-picker-chip { appearance: none; border: 0; background: 0 0; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 11px; height: 24px; padding: 0 7px; border-radius: var(--dsw-radius-sm); cursor: pointer; }
657
- .mb-picker-chip:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
658
- .mb-picker-chip[aria-pressed="true"] { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
659
- .mb-picker-error { border-radius: var(--dsw-radius-md); background: var(--dsw-alias-interactive-bg-hover-danger); color: var(--dsw-alias-state-error-primary); margin-bottom: 3px; padding: 6px 7px; font-size: 11px; line-height: 16px; }
660
- .mb-picker-retry { align-self: flex-start; margin: 0 4px 2px; }
661
- .mb-picker-status { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); padding: 4px 7px; font-size: 11px; line-height: 16px; }
662
- .mb-fatal { border: 1px solid var(--dsw-alias-state-error-primary); color: var(--dsw-alias-state-error-primary); border-radius: 8px; padding: 12px; }
663
- @media (max-width: 720px) {
664
- .mb-price-grid { grid-template-columns: 1fr; }
665
- .mb-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
666
- .mb-head-actions { width: 100%; margin-left: 38px; justify-content: flex-start; }
667
- }
668
- `
669
-
670
- function Style() {
671
- return h('style', null, CSS)
672
- }
673
-
674
- // ---------------------------------------------------------------------
675
- // Settings section
676
- // ---------------------------------------------------------------------
677
-
678
- const PRICE_FIELDS = ['cacheHit', 'cacheMiss', 'output']
679
- const PRICE_LABEL_KEYS = {
680
- cacheHit: 'cacheHitPrice',
681
- cacheMiss: 'cacheMissPrice',
682
- output: 'outputPrice',
683
- }
684
-
685
- function toDraftPricing(pricing) {
686
- if (pricing?.builtin === true) return { ...pricing, peak: { ...pricing.peak }, offPeak: { ...pricing.offPeak } }
687
- const source = pricing ?? {}
688
- return Object.fromEntries(PRICE_FIELDS.map((field) => [
689
- field,
690
- source[field] === null || source[field] === undefined ? '' : String(source[field]),
691
- ]))
692
- }
693
-
694
- function toDraft(models) {
695
- return models.map((model) => ({
696
- provider: model.provider,
697
- providerName: model.providerName,
698
- model: model.model,
699
- name: model.name,
700
- isDeepSeek: model.isDeepSeek,
701
- pricing: toDraftPricing(model.pricing),
702
- }))
703
- }
704
-
705
- function parsePriceInput(value) {
706
- if (typeof value === 'string' && value.trim() === '') return null
707
- const number = Number(value)
708
- if (!Number.isFinite(number) || number < 0 || number > 1e12) return undefined
709
- return Math.round(number * 1e8) / 1e8
710
- }
711
-
712
- function SettingsSection() {
713
- const translate = useT()
714
- const snap = useCatalog()
715
- const [draft, setDraft] = useState(null)
716
- const [display, setDisplay] = useState(null)
717
- const [dirty, setDirty] = useState(false)
718
- const [saving, setSaving] = useState(false)
719
- const [status, setStatus] = useState(null)
720
-
721
- useEffect(() => {
722
- if (snap.data === null) return
723
- setDraft(toDraft(snap.data.models))
724
- setDisplay(readDisplay(snap.data))
725
- setDirty(false)
726
- }, [snap.data])
727
-
728
- const models = draft ?? []
729
- const update = (index, change) => {
730
- setDraft((current) => current === null ? current : current.map((entry, at) => at === index ? change(entry) : entry))
731
- setDirty(true)
732
- setStatus(null)
733
- }
734
-
735
- const updatePrice = (index, field, value) => {
736
- update(index, (entry) => ({
737
- ...entry,
738
- pricing: { ...entry.pricing, [field]: value },
739
- }))
740
- }
741
-
742
- const move = (index, delta) => {
743
- const target = index + delta
744
- if (target < 0 || target >= models.length) return
745
- setDraft((current) => {
746
- if (current === null) return current
747
- const next = [...current]
748
- const [item] = next.splice(index, 1)
749
- next.splice(target, 0, item)
750
- return next
751
- })
752
- setDirty(true)
753
- setStatus(null)
754
- }
755
-
756
- const reset = () => {
757
- clearStoredDisplay()
758
- emitCatalog()
759
- if (snap.data !== null) {
760
- setDraft(toDraft(snap.data.models))
761
- setDisplay(readDisplay(snap.data))
762
- }
763
- setDirty(false)
764
- setStatus(null)
765
- }
766
-
767
- const displayValue = display ?? readDisplay(snap.data)
768
-
769
- const updateDisplay = (change) => {
770
- setDisplay((current) => ({ ...(current ?? readDisplay(snap.data)), ...change }))
771
- setDirty(true)
772
- setStatus(null)
773
- }
774
-
775
- const renderDisplaySettings = () => h(Fragment, null,
776
- h('div', { className: 'mb-display' },
777
- h('div', { className: 'mb-display-head' },
778
- h('div', { className: 'mb-display-title' }, translate('displaySection')),
779
- h('div', { className: 'mb-display-hint' }, translate('displayHint'))),
780
- h('div', { className: 'mb-check-grid' },
781
- [
782
- ['showProvider', 'displayProvider'],
783
- ['showModels', 'displayModels'],
784
- ['showCost', 'displayCost'],
785
- ['showTokens', 'displayTokens'],
786
- ['showCacheHit', 'displayCacheHit'],
787
- ['showLabels', 'displayLabels'],
788
- ].map(([field, label]) => h('label', {
789
- className: `mb-check${field === 'showProvider' && displayValue.showModels !== true ? ' is-disabled' : ''}`,
790
- key: field,
791
- },
792
- h('input', {
793
- type: 'checkbox',
794
- checked: displayValue[field] === true,
795
- disabled: field === 'showProvider' && displayValue.showModels !== true,
796
- onChange: (event) => updateDisplay({ [field]: event.target.checked }),
797
- }),
798
- h('span', null, translate(label))))),
799
- h('div', { className: 'mb-display-controls' },
800
- h('label', { className: 'mb-field' },
801
- h('span', { className: 'mb-field-label' }, translate('displayFontSize')),
802
- h('select', {
803
- className: 'mb-select',
804
- value: displayValue.fontSize,
805
- onChange: (event) => updateDisplay({ fontSize: event.target.value }),
806
- },
807
- h('option', { value: 'small' }, translate('fontSizeSmall')),
808
- h('option', { value: 'normal' }, translate('fontSizeNormal')),
809
- h('option', { value: 'large' }, translate('fontSizeLarge')))),
810
- h('label', { className: 'mb-field' },
811
- h('span', { className: 'mb-field-label' }, translate('displayDensity')),
812
- h('select', {
813
- className: 'mb-select',
814
- value: displayValue.density,
815
- onChange: (event) => updateDisplay({ density: event.target.value }),
816
- },
817
- h('option', { value: 'compact' }, translate('densityCompact')),
818
- h('option', { value: 'comfortable' }, translate('densityComfortable')))),
819
- h('label', { className: 'mb-field' },
820
- h('span', { className: 'mb-field-label' }, translate('displayWeight')),
821
- h('select', {
822
- className: 'mb-select',
823
- value: displayValue.fontWeight,
824
- onChange: (event) => updateDisplay({ fontWeight: event.target.value }),
825
- },
826
- h('option', { value: 'normal' }, translate('weightNormal')),
827
- h('option', { value: 'bold' }, translate('weightBold')))))),
828
- h('div', { className: 'mb-display' },
829
- h('div', { className: 'mb-display-head' },
830
- h('div', { className: 'mb-display-title' }, translate('pickerSection')),
831
- h('div', { className: 'mb-display-hint' }, translate('takeoverHint'))),
832
- h('label', { className: 'mb-check' },
833
- h('input', {
834
- type: 'checkbox',
835
- checked: displayValue.takeoverPicker === true,
836
- onChange: (event) => updateDisplay({ takeoverPicker: event.target.checked }),
837
- }),
838
- h('span', null, translate('takeoverPicker')))))
839
-
840
- const save = async () => {
841
- if (draft === null) return
842
- const payload = []
843
- for (const entry of draft) {
844
- if (entry.pricing.builtin === true) {
845
- payload.push({ provider: entry.provider, model: entry.model, pricing: {} })
846
- continue
847
- }
848
- const pricing = {}
849
- for (const field of PRICE_FIELDS) {
850
- const parsed = parsePriceInput(entry.pricing[field])
851
- if (parsed === undefined) {
852
- setStatus({ tone: 'error', text: translate('invalidPrice') })
853
- return
854
- }
855
- pricing[field] = parsed
856
- }
857
- payload.push({ provider: entry.provider, model: entry.model, pricing })
858
- }
859
- setSaving(true)
860
- setStatus(null)
861
- try {
862
- await requestJson('/model-billing/save', {
863
- method: 'POST',
864
- headers: { 'content-type': 'application/json' },
865
- body: JSON.stringify({ models: payload, display: displayValue }),
866
- })
867
- writeStoredDisplay(displayValue)
868
- setDirty(false)
869
- setStatus({ tone: 'success', text: translate('saved') })
870
- await ensureCatalog(true)
871
- } catch (error) {
872
- setStatus({ tone: 'error', text: translate('saveFailed', { message: error instanceof Error ? error.message : String(error) }) })
873
- } finally {
874
- setSaving(false)
875
- }
876
- }
877
-
878
- if (snap.data === null) {
879
- return h(Fragment, null,
880
- h(Style),
881
- h('section', { className: 'mb-page' },
882
- h('h2', { className: 'mb-title' }, translate('title')),
883
- snap.status === 'error'
884
- ? h('div', { className: 'mb-fatal' },
885
- h('div', null, translate('loadFailed')),
886
- h('p', { className: 'mb-note' }, snap.error),
887
- h('button', { type: 'button', className: 'mb-btn', onClick: () => void ensureCatalog(true) }, translate('retry')))
888
- : h('p', { className: 'mb-muted' }, translate('loading'))))
889
- }
890
-
891
- if (draft === null) {
892
- return h(Fragment, null,
893
- h(Style),
894
- h('section', { className: 'mb-page' },
895
- h('h2', { className: 'mb-title' }, translate('title')),
896
- h('p', { className: 'mb-muted' }, translate('loading'))))
897
- }
898
-
899
- if (models.length === 0) {
900
- return h(Fragment, null,
901
- h(Style),
902
- h('section', { className: 'mb-page' },
903
- h('h2', { className: 'mb-title' }, translate('title')),
904
- h('p', { className: 'mb-intro' }, translate('intro')),
905
- renderDisplaySettings(),
906
- h('div', { className: 'mb-empty' }, translate('noModels'))))
907
- }
908
-
909
- return h(Fragment, null,
910
- h(Style),
911
- h('section', { className: 'mb-page' },
912
- h('h2', { className: 'mb-title' }, translate('title')),
913
- h('p', { className: 'mb-intro' }, translate('intro')),
914
- h('div', { className: 'mb-toolbar' },
915
- h('span', { className: 'mb-muted' }, translate('modelsCount', { count: models.length })),
916
- h('span', { className: 'mb-spacer' }),
917
- dirty ? h('span', { className: 'mb-muted' }, translate('unsaved')) : null,
918
- h('button', { type: 'button', className: 'mb-btn', disabled: !dirty || saving, onClick: reset }, translate('undo')),
919
- h('button', { type: 'button', className: 'mb-btn mb-btn-primary', disabled: !dirty || saving, onClick: () => void save() }, saving ? translate('saving') : translate('save'))),
920
- status === null ? null : h('div', { className: 'mb-status', 'data-tone': status.tone, role: 'status' }, status.text),
921
- renderDisplaySettings(),
922
- h('p', { className: 'mb-note' }, translate('orderHint')),
923
- h('ul', { className: 'mb-list' },
924
- models.map((entry, index) => h(SettingsModelCard, {
925
- key: `${entry.provider}\u0000${entry.model}`,
926
- entry,
927
- index,
928
- count: models.length,
929
- translate,
930
- onMove: move,
931
- onUpdatePrice: updatePrice,
932
- }))),
933
- h('p', { className: 'mb-footer-note' }, translate('formula')),
934
- h('p', { className: 'mb-footer-note' }, translate('formulaNote'))))
935
- }
936
-
937
- function SettingsModelCard({ entry, index, count, translate, onMove, onUpdatePrice }) {
938
- const id = useId()
939
- const pricing = entry.pricing
940
- const builtin = pricing.builtin === true
941
- const fields = builtin ? null : PRICE_FIELDS.map((field) => {
942
- const inputId = `${id}-${field}`
943
- return h('label', { className: 'mb-field', htmlFor: inputId, key: field },
944
- h('span', { className: 'mb-field-label' }, translate(PRICE_LABEL_KEYS[field])),
945
- h('input', {
946
- id: inputId,
947
- className: 'mb-input',
948
- type: 'text',
949
- inputMode: 'decimal',
950
- autoComplete: 'off',
951
- placeholder: translate('pricePlaceholder'),
952
- value: pricing[field],
953
- onChange: (event) => onUpdatePrice(index, field, event.target.value),
954
- }))
955
- })
956
-
957
- return h('li', { className: 'mb-card' },
958
- h('div', { className: 'mb-card-head' },
959
- h('div', { className: 'mb-index' }, index + 1),
960
- h('div', { style: { minWidth: 0 } },
961
- h('div', { className: 'mb-name' },
962
- entry.name,
963
- entry.isDeepSeek ? h('span', { className: 'mb-tag' }, translate('deepseekTag')) : null),
964
- h('div', { className: 'mb-sub' }, `${entry.providerName} · ${entry.provider} / ${entry.model}`)),
965
- h('div', { className: 'mb-head-actions' },
966
- h('button', {
967
- type: 'button',
968
- className: 'mb-btn mb-btn-icon',
969
- disabled: index === 0,
970
- title: translate('up'),
971
- 'aria-label': translate('up'),
972
- onClick: () => onMove(index, -1),
973
- }, '↑'),
974
- h('button', {
975
- type: 'button',
976
- className: 'mb-btn mb-btn-icon',
977
- disabled: index === count - 1,
978
- title: translate('down'),
979
- 'aria-label': translate('down'),
980
- onClick: () => onMove(index, 1),
981
- }, '↓'))),
982
- entry.isDeepSeek ? h('p', { className: 'mb-note' }, translate('deepseekNote')) : null,
983
- h('div', { className: 'mb-prices' },
984
- h('div', { className: 'mb-price-group' },
985
- h('div', { className: 'mb-price-group-title' },
986
- h('span', null, builtin ? translate('officialPrice') : translate('singlePrice')),
987
- h('span', { className: 'mb-muted', style: { fontWeight: 400, fontSize: '11px' } }, translate('perMillion'))),
988
- builtin
989
- ? h(Fragment, null,
990
- h(PriceLines, { pricing, translate }),
991
- h('p', { className: 'mb-note' }, translate('deepseekSchedule')))
992
- : h('div', { className: 'mb-price-grid' }, fields))))
993
- }
994
-
995
- // ---------------------------------------------------------------------
996
- // Composer dock cost summary
997
- // ---------------------------------------------------------------------
998
-
999
- function CostDock({ sessionId, useProjection }) {
1000
- const translate = useT()
1001
- const tokenUsage = useProjection('tokenUsage')
1002
- const revision = tokenUsageRevision(tokenUsage)
1003
- const usage = useSessionUsage(sessionId, revision)
1004
- const catalogSnap = useCatalog()
1005
- const [open, setOpen] = useState(false)
1006
- const [panelPos, setPanelPos] = useState(null)
1007
- const triggerRef = useRef(null)
1008
- const panelRef = useRef(null)
1009
-
1010
- useLayoutEffect(() => {
1011
- if (!open) {
1012
- setPanelPos(null)
1013
- return undefined
1014
- }
1015
- const place = () => {
1016
- const rect = triggerRef.current?.getBoundingClientRect()
1017
- if (rect === undefined) return
1018
- const width = Math.min(660, window.innerWidth - 24)
1019
- const naturalLeft = Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))
1020
- // The dock sits near the right edge; shift the whole detail panel left so
1021
- // the bottom-right whale widget cannot cover it.
1022
- const left = Math.max(12, naturalLeft - 120)
1023
- const spaceAbove = rect.top - 12
1024
- const spaceBelow = window.innerHeight - rect.bottom - 12
1025
- const above = spaceAbove > spaceBelow
1026
- const maxHeight = Math.min(430, Math.max(180, above ? spaceAbove : spaceBelow))
1027
- setPanelPos(above
1028
- ? { left, width, bottom: window.innerHeight - rect.top + 8, maxHeight }
1029
- : { left, width, top: rect.bottom + 8, maxHeight })
1030
- }
1031
- place()
1032
- window.addEventListener('resize', place)
1033
- window.addEventListener('scroll', place, true)
1034
- return () => {
1035
- window.removeEventListener('resize', place)
1036
- window.removeEventListener('scroll', place, true)
1037
- }
1038
- }, [open])
1039
-
1040
- useEffect(() => {
1041
- if (!open) return undefined
1042
- const closeOutside = (event) => {
1043
- if (triggerRef.current?.contains(event.target) === true) return
1044
- if (panelRef.current?.contains(event.target) === true) return
1045
- setOpen(false)
1046
- }
1047
- const closeOnEscape = (event) => {
1048
- if (event.key !== 'Escape') return
1049
- event.preventDefault()
1050
- setOpen(false)
1051
- triggerRef.current?.focus()
1052
- }
1053
- document.addEventListener('mousedown', closeOutside)
1054
- document.addEventListener('keydown', closeOnEscape)
1055
- return () => {
1056
- document.removeEventListener('mousedown', closeOutside)
1057
- document.removeEventListener('keydown', closeOnEscape)
1058
- }
1059
- }, [open])
1060
-
1061
- const data = usage.data
1062
- if (data === null || data === undefined || data.totals?.hasBillable !== true) {
1063
- return null
1064
- }
1065
- const totals = data.totals
1066
- const last = [...(data.turns ?? [])].reverse().find((entry) => entry.hasBillable) ?? null
1067
- const totalText = totals.costKnown
1068
- ? `≈ ${formatMoney(totals.cost)}`
1069
- : totals.pricedAttempts > 0 ? `≈ ${formatMoney(totals.cost)}*` : translate('pricePlaceholder')
1070
- const lastText = last === null || last === undefined || !last.hasBillable
1071
- ? null
1072
- : last.costKnown ? `≈ ${formatMoney(last.cost)}` : last.pricedAttempts > 0 ? `≈ ${formatMoney(last.cost)}*` : translate('pricePlaceholder')
1073
- const orderIndex = new Map((catalogSnap.data?.models ?? []).map((model) => [`${model.provider}\u0000${model.model}`, model.order]))
1074
- const byModel = [...(data.byModel ?? [])].sort((left, right) => {
1075
- const leftKey = left.provider === null ? '' : `${left.provider}\u0000${left.model}`
1076
- const rightKey = right.provider === null ? '' : `${right.provider}\u0000${right.model}`
1077
- return (orderIndex.get(leftKey) ?? Number.MAX_SAFE_INTEGER) - (orderIndex.get(rightKey) ?? Number.MAX_SAFE_INTEGER)
1078
- })
1079
-
1080
- const modelNameOf = (model) => {
1081
- const catalogRow = catalogSnap.data?.models?.find((entry) => entry.provider === model?.provider && entry.model === model?.model)
1082
- return catalogRow?.name ?? model?.name ?? model?.model ?? '—'
1083
- }
1084
- const turnModelNames = (turn) => {
1085
- const names = []
1086
- for (const model of turn.models ?? []) {
1087
- const name = modelNameOf(model)
1088
- if (!names.includes(name)) names.push(name)
1089
- }
1090
- return names
1091
- }
1092
-
1093
- const header = h('thead', null,
1094
- h('tr', null,
1095
- h('th', null, translate('turn')),
1096
- h('th', null, translate('content')),
1097
- h('th', null, translate('time')),
1098
- h('th', null, translate('model')),
1099
- h('th', { className: 'num' }, translate('cost')),
1100
- h('th', { className: 'num' }, translate('tokens')),
1101
- h('th', { className: 'num' }, translate('cacheHit'))))
1102
-
1103
- const turnRows = [...(data.turns ?? [])].reverse().slice(0, 20).map((turn) => {
1104
- const costText = turn.costKnown
1105
- ? `≈ ${formatMoney(turn.cost)}`
1106
- : turn.pricedAttempts > 0 ? `≈ ${formatMoney(turn.cost)}*` : translate('pricePlaceholder')
1107
- const modelNames = turnModelNames(turn)
1108
- const modelText = modelNames.length === 0
1109
- ? '—'
1110
- : modelNames.length === 1 ? modelNames[0] : `${modelNames[0]} +${modelNames.length - 1}`
1111
- return h('tr', { key: turn.turn },
1112
- h('td', null, `#${turn.turn}`),
1113
- h('td', { className: 'mb-turn-preview', title: turn.preview }, turn.preview || '—'),
1114
- h('td', null, `${timeText(turn.startTime)}–${timeText(turn.endTime)}`),
1115
- h('td', { className: 'mb-turn-model', title: modelNames.join(' / ') }, modelText),
1116
- h('td', { className: 'num' }, costText),
1117
- h('td', { className: 'num' }, `${formatTokens(turn.promptTokens)} / ${formatTokens(turn.outputTokens)}`),
1118
- h('td', { className: 'num' }, formatPercent(turn.cacheHit)))
1119
- })
1120
-
1121
- const turnTable = h('div', { style: { overflowX: 'auto' } },
1122
- h('table', { className: 'mb-table mb-turn-table' }, header, h('tbody', null, turnRows)))
1123
-
1124
- const modelRows = byModel.map((model) => {
1125
- const catalogRow = catalogSnap.data?.models?.find((entry) => entry.provider === model.provider && entry.model === model.model)
1126
- const modelName = catalogRow === undefined ? model.name : `${catalogRow.providerName} / ${catalogRow.name}`
1127
- return h('tr', { key: `${model.provider}\u0000${model.model}\u0000${model.name}` },
1128
- h('td', null,
1129
- modelName,
1130
- model.isDeepSeek ? h('span', { className: 'mb-tag' }, translate('deepseekTag')) : null),
1131
- h('td', { className: 'num' },
1132
- model.pricedAttempts > 0 ? `≈ ${formatMoney(model.cost)}` : translate('pricePlaceholder')),
1133
- h('td', { className: 'num', style: { color: 'var(--dsw-alias-label-secondary)' } },
1134
- `${formatTokens(model.promptTokens)} / ${formatTokens(model.outputTokens)}`))
1135
- })
1136
-
1137
- const modelTable = byModel.length === 0
1138
- ? null
1139
- : h('div', { style: { marginTop: '10px' } },
1140
- h('div', { className: 'mb-panel-title', style: { fontSize: '12px', marginBottom: '4px' } }, translate('byModel')),
1141
- h('div', { style: { overflowX: 'auto' } },
1142
- h('table', { className: 'mb-table' }, h('tbody', null, modelRows))))
1143
-
1144
- const panelStyle = panelPos === null
1145
- ? { left: 0, top: 0, width: 660, visibility: 'hidden' }
1146
- : {
1147
- left: panelPos.left,
1148
- width: panelPos.width,
1149
- maxHeight: panelPos.maxHeight,
1150
- ...panelPos.top === undefined ? { bottom: panelPos.bottom } : { top: panelPos.top },
1151
- }
1152
-
1153
- const panel = h('div', {
1154
- ref: panelRef,
1155
- className: 'mb-panel mb-panel-floating',
1156
- style: panelStyle,
1157
- role: 'dialog',
1158
- 'aria-label': translate('costDetails'),
1159
- tabIndex: -1,
1160
- },
1161
- h('div', { className: 'mb-panel-head' },
1162
- h('span', { className: 'mb-panel-title' }, translate('costDetails')),
1163
- h('span', { className: 'mb-muted' }, translate('sessionTotal')),
1164
- usage.status === 'error'
1165
- ? h('button', {
1166
- type: 'button',
1167
- className: 'mb-btn',
1168
- onClick: () => void ensureUsage(sessionId, revision, true),
1169
- }, translate('retry'))
1170
- : null,
1171
- h('button', {
1172
- type: 'button',
1173
- className: 'mb-panel-close',
1174
- 'aria-label': translate('close'),
1175
- title: translate('close'),
1176
- onClick: () => {
1177
- setOpen(false)
1178
- triggerRef.current?.focus()
1179
- },
1180
- }, '×')),
1181
- h('div', { className: 'mb-summary' },
1182
- summaryItem(translate('sessionTotal'), totalText),
1183
- summaryItem(translate('thisTurn'), lastText ?? '—'),
1184
- summaryItem(translate('cacheHit'), formatPercent(totals.cacheHit)),
1185
- summaryItem(translate('tokens'), `${formatTokens(totals.promptTokens)} / ${formatTokens(totals.outputTokens)}`)),
1186
- turnTable,
1187
- modelTable,
1188
- h('p', { className: 'mb-panel-note' }, translate('estimateNote')),
1189
- totals.partial ? h('p', { className: 'mb-warn' }, translate('partialNote')) : null)
1190
-
1191
- return h('div', { className: 'mb-dock' },
1192
- h(Style),
1193
- h('button', {
1194
- ref: triggerRef,
1195
- type: 'button',
1196
- className: 'mb-dock-trigger',
1197
- 'aria-expanded': open ? 'true' : 'false',
1198
- 'aria-haspopup': 'dialog',
1199
- onClick: () => setOpen((value) => !value),
1200
- title: translate('costEstimate'),
1201
- },
1202
- h('svg', {
1203
- className: 'mb-dock-icon',
1204
- viewBox: '0 0 16 16',
1205
- fill: 'none',
1206
- stroke: 'currentColor',
1207
- strokeWidth: 1.2,
1208
- 'aria-hidden': true,
1209
- },
1210
- h('circle', { cx: 8, cy: 8, r: 5.5 }),
1211
- h('path', { d: 'M8 5v6M6.2 6.8h3.6M6.2 9.2h3.6' })),
1212
- h('span', null, translate('costEstimate')),
1213
- h('span', { className: 'mb-dock-amount' }, totalText),
1214
- lastText === null ? null : h(Fragment, null,
1215
- h('span', { className: 'mb-dock-sep' }, '·'),
1216
- h('span', null, `${translate('thisTurn')} ${lastText}`)),
1217
- totals.partial ? h('span', { className: 'mb-warn', style: { margin: 0 } }, translate('partial')) : null),
1218
- open ? ReactDOM.createPortal(panel, document.body) : null)
1219
- }
1220
-
1221
- function summaryItem(label, value) {
1222
- return h('div', { className: 'mb-summary-item', key: label },
1223
- h('div', { className: 'mb-summary-key' }, label),
1224
- h('div', { className: 'mb-summary-value' }, value))
1225
- }
1226
-
1227
- // ---------------------------------------------------------------------
1228
- // Per-turn cost chip
1229
- // ---------------------------------------------------------------------
1230
-
1231
- function turnModelText(models, translate, showProvider, catalogModels) {
1232
- const findModel = (entry) => {
1233
- if (entry.provider === undefined || entry.model === undefined) return undefined
1234
- return (catalogModels ?? []).find((candidate) => candidate.provider === entry.provider && candidate.model === entry.model)
1235
- }
1236
- const names = (models ?? []).map((entry) => {
1237
- if (entry === undefined || entry === null) return null
1238
- const matched = findModel(entry)
1239
- const modelName = typeof matched?.name === 'string' && matched.name !== ''
1240
- ? matched.name
1241
- : typeof entry.name === 'string' && entry.name !== ''
1242
- ? entry.name
1243
- : typeof entry.model === 'string' && entry.model !== '' ? entry.model : null
1244
- if (modelName === null) return null
1245
- if (!showProvider) return modelName
1246
- const providerName = typeof matched?.providerName === 'string' && matched.providerName !== ''
1247
- ? matched.providerName
1248
- : typeof entry.providerName === 'string' && entry.providerName !== ''
1249
- ? entry.providerName
1250
- : typeof entry.provider === 'string' && entry.provider !== '' ? entry.provider : null
1251
- return providerName === null ? modelName : `${providerName} / ${modelName}`
1252
- }).filter((name) => name !== null)
1253
- if (names.length === 0) return null
1254
- return names.join(translate('listSep'))
1255
- }
1256
-
1257
- function TurnCost(props) {
1258
- const { turn } = props
1259
- // The turnTail owner hands over the whole folded turn life cycle, not just its number.
1260
- const turnNumber = turn === null || turn === undefined
1261
- ? undefined
1262
- : typeof turn === 'number' ? turn : turn.turn
1263
- const sessionId = props.sessionId
1264
- const useProjection = props.useProjection
1265
- const translate = useT()
1266
- const catalogSnap = useCatalog()
1267
- const display = readDisplay(catalogSnap.data)
1268
- const tokenUsage = typeof useProjection === 'function' ? useProjection('tokenUsage') : undefined
1269
- const revision = tokenUsageRevision(tokenUsage)
1270
- const usage = useSessionUsage(sessionId, revision)
1271
- const rows = usage.data?.turns
1272
- const row = rows?.find((entry) => entry.turn === turnNumber)
1273
- if (row === undefined) return null
1274
- const costText = row.costKnown
1275
- ? `≈ ${formatMoney(row.cost)}`
1276
- : row.pricedAttempts > 0 ? `≈ ${formatMoney(row.cost)}*` : translate('pricePlaceholder')
1277
- const modelText = turnModelText(row.models, translate, display.showProvider === true, catalogSnap.data?.models)
1278
- const label = (key) => display.showLabels ? `${translate(key)} ` : ''
1279
- const parts = []
1280
- if (display.showModels && modelText !== null) {
1281
- parts.push(h('span', { className: 'mb-turn-item', key: 'model' },
1282
- label('model'), h('strong', null, modelText)))
1283
- }
1284
- if (display.showCost) {
1285
- parts.push(h('span', { className: 'mb-turn-item', key: 'cost' },
1286
- label('turnCost'), h('strong', null, costText)))
1287
- }
1288
- const promptTokens = Number.isFinite(row.promptTokens) ? row.promptTokens : 0
1289
- const outputTokens = Number.isFinite(row.outputTokens) ? row.outputTokens : 0
1290
- if (display.showTokens && (promptTokens > 0 || outputTokens > 0)) {
1291
- parts.push(h('span', { className: 'mb-turn-item', key: 'tokens' },
1292
- label('turnTokens'), h('strong', null, `${formatTokens(promptTokens)} / ${formatTokens(outputTokens)}`)))
1293
- }
1294
- if (display.showCacheHit && row.cacheHit !== null && row.cacheHit !== undefined) {
1295
- parts.push(h('span', { className: 'mb-turn-item', key: 'cache' },
1296
- label('cacheHit'), h('strong', null, formatPercent(row.cacheHit))))
1297
- }
1298
- if (row.partial) {
1299
- parts.push(h('span', { className: 'mb-turn-item mb-turn-partial', key: 'partial' }, translate('partialShort')))
1300
- }
1301
- if (parts.length === 0) return null
1302
- return h('span', {
1303
- className: 'mb-turn',
1304
- 'data-size': display.fontSize,
1305
- 'data-density': display.density,
1306
- 'data-weight': display.fontWeight,
1307
- }, parts)
1308
- }
1309
-
1310
- // ---------------------------------------------------------------------
1311
- // Custom-ordered model picker in the composer seat
1312
- // ---------------------------------------------------------------------
1313
-
1314
- const MODEL_KEY_SEPARATOR = '\u0000'
1315
-
1316
- function OrderedModelPicker({ locked, sessionId, useProjection }) {
1317
- const translate = useT()
1318
- const catalogSnap = useCatalog()
1319
- const selectionProjection = useProjection('modelSelection')
1320
- const directoryRevision = useModelDirectoriesRevision()
1321
- const [directoryTick, setDirectoryTick] = useState(0)
1322
- const directory = useMemo(() => {
1323
- if (modelDirectories === undefined || sessionId === undefined) return null
1324
- try {
1325
- return modelDirectories.directoryFor(sessionId)
1326
- } catch {
1327
- return null
1328
- }
1329
- }, [sessionId, directoryRevision, directoryTick])
1330
-
1331
- const [state, setState] = useState(null)
1332
- const [open, setOpen] = useState(false)
1333
- const [query, setQuery] = useState('')
1334
- const [selecting, setSelecting] = useState(false)
1335
- const [failure, setFailure] = useState(null)
1336
- const [menuPos, setMenuPos] = useState(null)
1337
- const rootRef = useRef(null)
1338
- const triggerRef = useRef(null)
1339
- const menuRef = useRef(null)
1340
- const searchRef = useRef(null)
1341
- const id = useId()
1342
-
1343
- useEffect(() => {
1344
- if (directory === null) {
1345
- setState(null)
1346
- return undefined
1347
- }
1348
- const sync = () => setState(directory.store.getSnapshot())
1349
- sync()
1350
- const unsubscribe = directory.store.subscribe(sync)
1351
- directory.load().catch(() => {})
1352
- return unsubscribe
1353
- }, [directory])
1354
-
1355
- useEffect(() => {
1356
- if (directory !== null || directoryTick >= 20) return undefined
1357
- const timer = setTimeout(() => setDirectoryTick((value) => value + 1), 300)
1358
- return () => clearTimeout(timer)
1359
- }, [directory, directoryTick])
1360
-
1361
- useEffect(() => {
1362
- if (!open) return undefined
1363
- const closeOutside = (event) => {
1364
- if (rootRef.current?.contains(event.target) === true) return
1365
- if (menuRef.current?.contains(event.target) === true) return
1366
- setOpen(false)
1367
- }
1368
- document.addEventListener('mousedown', closeOutside)
1369
- return () => document.removeEventListener('mousedown', closeOutside)
1370
- }, [open])
1371
-
1372
- useEffect(() => {
1373
- if (!open) {
1374
- setQuery('')
1375
- return undefined
1376
- }
1377
- const closeOnEscape = (event) => {
1378
- if (event.key !== 'Escape') return
1379
- event.preventDefault()
1380
- setOpen(false)
1381
- queueMicrotask(() => triggerRef.current?.focus())
1382
- }
1383
- document.addEventListener('keydown', closeOnEscape)
1384
- return () => document.removeEventListener('keydown', closeOnEscape)
1385
- }, [open])
1386
-
1387
- useEffect(() => {
1388
- if (locked && open) setOpen(false)
1389
- }, [locked, open])
1390
-
1391
- const rank = useMemo(() => {
1392
- const map = new Map()
1393
- for (const model of catalogSnap.data?.models ?? []) {
1394
- map.set(`${model.provider}${MODEL_KEY_SEPARATOR}${model.model}`, model.order)
1395
- }
1396
- return map
1397
- }, [catalogSnap.data])
1398
-
1399
- const priceByKey = useMemo(() => {
1400
- const map = new Map()
1401
- for (const model of catalogSnap.data?.models ?? []) {
1402
- map.set(`${model.provider}${MODEL_KEY_SEPARATOR}${model.model}`, model.pricing)
1403
- }
1404
- return map
1405
- }, [catalogSnap.data])
1406
-
1407
- const groups = state?.groups
1408
- const catalogModels = catalogSnap.data?.models
1409
- const entries = useMemo(() => {
1410
- if (Array.isArray(groups) && groups.length > 0) {
1411
- const list = []
1412
- for (const [groupIndex, group] of groups.entries()) {
1413
- for (const [modelIndex, model] of group.models.entries()) {
1414
- list.push({ group, model, groupIndex, modelIndex })
1415
- }
1416
- }
1417
- list.sort((left, right) => {
1418
- const leftRank = rank.get(`${left.group.id}${MODEL_KEY_SEPARATOR}${left.model.id}`) ?? Number.MAX_SAFE_INTEGER
1419
- const rightRank = rank.get(`${right.group.id}${MODEL_KEY_SEPARATOR}${right.model.id}`) ?? Number.MAX_SAFE_INTEGER
1420
- return leftRank - rightRank || left.groupIndex - right.groupIndex || left.modelIndex - right.modelIndex
1421
- })
1422
- return list
1423
- }
1424
- return (catalogModels ?? []).map((model, index) => ({
1425
- group: { id: model.provider, name: model.providerName },
1426
- model: {
1427
- id: model.model,
1428
- name: model.name,
1429
- ...(model.reasoning === undefined ? {} : { reasoning: model.reasoning }),
1430
- },
1431
- groupIndex: model.order ?? index,
1432
- modelIndex: index,
1433
- }))
1434
- }, [groups, catalogModels, rank])
1435
-
1436
- const projected = selectionProjection?.next ?? selectionProjection?.lastUsed ?? null
1437
- const current = state?.current ?? projected
1438
- const currentEntry = current === null
1439
- ? undefined
1440
- : entries.find((entry) => entry.group.id === current.provider && entry.model.id === current.model)
1441
- const currentCatalog = current === null
1442
- ? undefined
1443
- : (catalogModels ?? []).find((model) => model.provider === current.provider && model.model === current.model)
1444
- const currentReasoning = currentEntry?.model.reasoning
1445
- const effectiveEffort = current?.reasoningEffort ?? currentReasoning?.defaultEffort
1446
- const effortLabel = current === null
1447
- ? undefined
1448
- : currentReasoning === undefined
1449
- ? state?.retainedEffort
1450
- : effectiveEffort === undefined
1451
- ? translate('providerDefault')
1452
- : currentReasoning.efforts.find((effort) => effort.id === effectiveEffort)?.name ?? effectiveEffort
1453
- const effortChoices = currentReasoning === undefined
1454
- ? []
1455
- : [
1456
- ...(currentReasoning.defaultEffort === undefined
1457
- ? [{ key: 'provider-default', effort: undefined, label: translate('providerDefault') }]
1458
- : []),
1459
- ...currentReasoning.efforts.map((effort) => ({
1460
- key: `effort:${effort.id}`,
1461
- effort: effort.id,
1462
- label: effort.name,
1463
- })),
1464
- ]
1465
-
1466
- const showSearch = entries.length > 4
1467
- const term = query.trim().toLowerCase()
1468
- const filtered = useMemo(() => {
1469
- if (term === '') return entries
1470
- return entries.filter((entry) => `${entry.model.name} ${entry.group.name}`.toLowerCase().includes(term))
1471
- }, [entries, term])
1472
-
1473
- useLayoutEffect(() => {
1474
- if (!open) {
1475
- setMenuPos(null)
1476
- return undefined
1477
- }
1478
- const place = () => {
1479
- const rect = triggerRef.current?.getBoundingClientRect()
1480
- if (rect === undefined) return
1481
- const width = Math.min(360, window.innerWidth - 24)
1482
- const left = Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))
1483
- const spaceAbove = rect.top - 12
1484
- const spaceBelow = window.innerHeight - rect.bottom - 12
1485
- const openBelow = spaceBelow > spaceAbove
1486
- const maxHeight = Math.min(480, Math.max(160, openBelow ? spaceBelow : spaceAbove))
1487
- setMenuPos(openBelow
1488
- ? { left, top: rect.bottom + 8, width, maxHeight }
1489
- : { left, bottom: window.innerHeight - rect.top + 8, width, maxHeight })
1490
- }
1491
- place()
1492
- window.addEventListener('scroll', place, true)
1493
- window.addEventListener('resize', place)
1494
- return () => {
1495
- window.removeEventListener('scroll', place, true)
1496
- window.removeEventListener('resize', place)
1497
- }
1498
- }, [open, filtered.length, state?.status])
1499
-
1500
- useEffect(() => {
1501
- if (!open) return undefined
1502
- const timer = setTimeout(() => {
1503
- if (showSearch) {
1504
- searchRef.current?.focus()
1505
- return
1506
- }
1507
- const first = menuRef.current?.querySelector('.mb-picker-row:not(:disabled)')
1508
- if (first instanceof HTMLElement) first.focus()
1509
- }, 0)
1510
- return () => clearTimeout(timer)
1511
- }, [open, showSearch])
1512
-
1513
- const loading = catalogSnap.data === null && (state === null || state.status === 'loading')
1514
- const busy = selecting || state?.status === 'selecting'
1515
- const currentName = currentEntry?.model.name ?? currentCatalog?.name
1516
- const triggerModel = currentName ?? (loading ? translate('loadingModels') : translate('chooseModel'))
1517
- const triggerAria = effortLabel === undefined ? triggerModel : `${triggerModel} · ${effortLabel}`
1518
-
1519
- const close = (restoreFocus) => {
1520
- setOpen(false)
1521
- setQuery('')
1522
- setFailure(null)
1523
- if (restoreFocus) queueMicrotask(() => triggerRef.current?.focus())
1524
- }
1525
-
1526
- const submit = async (selection) => {
1527
- if (busy) return
1528
- setSelecting(true)
1529
- setFailure(null)
1530
- try {
1531
- const result = directory !== null
1532
- ? await directory.select(selection)
1533
- : await requestJson('/model-billing/select', {
1534
- method: 'POST',
1535
- headers: { 'content-type': 'application/json' },
1536
- body: JSON.stringify({ sessionId, ...selection }),
1537
- })
1538
- if (result?.ok === false) {
1539
- setFailure(result.error?.message ?? translate('pickerEmpty'))
1540
- return
1541
- }
1542
- close(true)
1543
- } catch (error) {
1544
- setFailure(error instanceof Error ? error.message : String(error))
1545
- } finally {
1546
- setSelecting(false)
1547
- }
1548
- }
1549
-
1550
- const chooseModel = (entry) => {
1551
- if (current?.provider === entry.group.id && current?.model === entry.model.id) {
1552
- close(true)
1553
- return
1554
- }
1555
- void submit({ provider: entry.group.id, model: entry.model.id })
1556
- }
1557
-
1558
- const chooseEffort = (effort) => {
1559
- if (current === null) return
1560
- if (effectiveEffort === effort) {
1561
- close(true)
1562
- return
1563
- }
1564
- void submit({
1565
- provider: current.provider,
1566
- model: current.model,
1567
- ...effort === undefined ? {} : { reasoningEffort: effort },
1568
- })
1569
- }
1570
-
1571
- const toggle = () => {
1572
- if (open) {
1573
- close(true)
1574
- return
1575
- }
1576
- setFailure(null)
1577
- setOpen(true)
1578
- if (directory !== null) directory.load().catch(() => {})
1579
- }
1580
-
1581
- const menuStyle = menuPos === null
1582
- ? { left: 0, top: 0, width: 360, visibility: 'hidden' }
1583
- : {
1584
- left: menuPos.left,
1585
- width: menuPos.width,
1586
- maxHeight: menuPos.maxHeight,
1587
- ...menuPos.top === undefined ? { bottom: menuPos.bottom } : { top: menuPos.top },
1588
- }
1589
- const errorText = failure ?? (state?.status === 'error' ? state.error : null)
1590
-
1591
- const menu = h('div', {
1592
- ref: menuRef,
1593
- id: `${id}-menu`,
1594
- className: 'mb-picker-menu',
1595
- style: menuStyle,
1596
- role: 'dialog',
1597
- 'aria-label': translate('pickerAria'),
1598
- },
1599
- showSearch ? h('input', {
1600
- ref: searchRef,
1601
- className: 'mb-picker-search',
1602
- type: 'search',
1603
- value: query,
1604
- placeholder: translate('searchModel'),
1605
- 'aria-label': translate('searchModel'),
1606
- onChange: (event) => setQuery(event.target.value),
1607
- onKeyDown: (event) => {
1608
- if (event.key !== 'Enter' || filtered.length === 0 || busy) return
1609
- event.preventDefault()
1610
- chooseModel(filtered[0])
1611
- },
1612
- }) : null,
1613
- h('div', { className: 'mb-picker-list', role: 'menu' },
1614
- filtered.length === 0
1615
- ? h('div', { className: 'mb-picker-empty' }, term === '' ? translate('pickerEmpty') : translate('noMatch'))
1616
- : filtered.map((entry, index) => {
1617
- const selected = current?.provider === entry.group.id && current?.model === entry.model.id
1618
- const previous = filtered[index - 1]
1619
- const showGroup = previous === undefined || previous.group.id !== entry.group.id
1620
- const price = priceByKey.get(`${entry.group.id}${MODEL_KEY_SEPARATOR}${entry.model.id}`)
1621
- return h(Fragment, { key: `${entry.group.id}${MODEL_KEY_SEPARATOR}${entry.model.id}` },
1622
- showGroup ? h('div', { className: 'mb-picker-group' }, entry.group.name) : null,
1623
- h('button', {
1624
- type: 'button',
1625
- role: 'menuitemradio',
1626
- className: 'mb-picker-row',
1627
- 'aria-checked': selected ? 'true' : 'false',
1628
- title: entry.model.name,
1629
- disabled: busy,
1630
- onClick: () => chooseModel(entry),
1631
- },
1632
- h('span', { className: 'mb-picker-option-copy' },
1633
- h('span', { className: 'mb-picker-model' }, entry.model.name),
1634
- h(PriceLines, { pricing: price, translate })),
1635
- h('span', { className: 'mb-picker-check' },
1636
- selected
1637
- ? h('svg', {
1638
- viewBox: '0 0 16 16',
1639
- width: 14,
1640
- height: 14,
1641
- fill: 'none',
1642
- stroke: 'currentColor',
1643
- strokeWidth: 1.7,
1644
- 'aria-hidden': true,
1645
- },
1646
- h('path', { d: 'M3.5 8.5l3 3 6-7' }))
1647
- : null)))
1648
- })),
1649
- effortChoices.length === 0 ? null : h(Fragment, null,
1650
- h('div', { className: 'mb-picker-divider' }),
1651
- h('div', { className: 'mb-picker-efforts' },
1652
- h('span', { className: 'mb-picker-efforts-label' }, translate('reasoningEffort')),
1653
- effortChoices.map((choice) => h('button', {
1654
- type: 'button',
1655
- key: choice.key,
1656
- className: 'mb-picker-chip',
1657
- 'aria-pressed': effectiveEffort === choice.effort ? 'true' : 'false',
1658
- disabled: busy,
1659
- onClick: () => chooseEffort(choice.effort),
1660
- }, choice.label)))),
1661
- busy ? h('div', { className: 'mb-picker-status' }, translate('switching')) : null,
1662
- errorText === null ? null : h('div', { className: 'mb-picker-error' }, errorText),
1663
- state?.status === 'error'
1664
- ? h('button', {
1665
- type: 'button',
1666
- className: 'mb-btn mb-picker-retry',
1667
- onClick: () => {
1668
- setFailure(null)
1669
- directory.load().catch(() => {})
1670
- },
1671
- }, translate('pickerRetry'))
1672
- : null)
1673
-
1674
- return h('div', {
1675
- className: 'mb-picker',
1676
- ref: rootRef,
1677
- },
1678
- h(Style),
1679
- h('button', {
1680
- ref: triggerRef,
1681
- type: 'button',
1682
- className: 'mb-picker-trigger',
1683
- disabled: locked,
1684
- 'aria-label': triggerAria,
1685
- 'aria-haspopup': 'menu',
1686
- 'aria-controls': open ? `${id}-menu` : undefined,
1687
- 'aria-expanded': open ? 'true' : 'false',
1688
- 'aria-busy': busy ? 'true' : undefined,
1689
- title: triggerAria,
1690
- onClick: toggle,
1691
- },
1692
- h('svg', {
1693
- viewBox: '0 0 16 16',
1694
- width: 14,
1695
- height: 14,
1696
- fill: 'none',
1697
- stroke: 'currentColor',
1698
- strokeWidth: 1.3,
1699
- 'aria-hidden': true,
1700
- className: 'mb-picker-icon',
1701
- },
1702
- h('rect', { x: 2, y: 3, width: 12, height: 10, rx: 2 }),
1703
- h('path', { d: 'M2 6.5h12M6 6.5V13' })),
1704
- h('span', { className: 'mb-picker-name' }, triggerModel),
1705
- effortLabel === undefined ? null : h('span', { className: 'mb-picker-trigger-effort' }, effortLabel),
1706
- h('svg', {
1707
- className: open ? 'mb-picker-chevron mb-picker-chevron-open' : 'mb-picker-chevron',
1708
- viewBox: '0 0 16 16',
1709
- width: 14,
1710
- height: 14,
1711
- fill: 'none',
1712
- stroke: 'currentColor',
1713
- strokeWidth: 1.5,
1714
- 'aria-hidden': true,
1715
- },
1716
- h('path', { d: 'M4 6l4 4 4-4' }))),
1717
- open ? ReactDOM.createPortal(menu, document.body) : null)
1718
- }
1719
-
1720
- function ModelPickerSeat(props) {
1721
- const catalogSnap = useCatalog()
1722
- const display = readDisplay(catalogSnap.data)
1723
- if (!display.takeoverPicker) return null
1724
- return h(OrderedModelPicker, props)
1725
- }
1726
-
1727
- return {
1728
- inject: ['slots', 'locale'],
1729
- apply(ctx) {
1730
- localeService = ctx.get('locale')
1731
- publishModelDirectories(ctx.get('modelDirectories'))
1732
- ctx.inject(['modelDirectories'], (scope) => {
1733
- publishModelDirectories(scope.modelDirectories)
1734
- let seat = null
1735
- const takeoverEnabled = () => readDisplay(catalog.snap.data).takeoverPicker !== false
1736
- const syncSeat = () => {
1737
- if (takeoverEnabled()) {
1738
- if (seat === null) {
1739
- seat = scope.slots.register({
1740
- name: 'conversation.input.model',
1741
- priority: -1,
1742
- }, ModelPickerSeat)
1743
- }
1744
- return
1745
- }
1746
- if (seat !== null) {
1747
- seat()
1748
- seat = null
1749
- }
1750
- }
1751
- scope.slots.inject('conversation.input.model', () => {
1752
- const unsubscribe = subscribeCatalog(syncSeat)
1753
- syncSeat()
1754
- return () => {
1755
- unsubscribe()
1756
- if (seat !== null) {
1757
- seat()
1758
- seat = null
1759
- }
1760
- }
1761
- })
1762
- })
1763
-
1764
- void ensureCatalog()
1765
-
1766
- ctx.slots.inject('settings.section', () => ctx.slots.register({
1767
- name: 'settings.section',
1768
- id: 'model-billing',
1769
- order: 12,
1770
- label: () => t('nav'),
1771
- }, SettingsSection))
1772
-
1773
- ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
1774
- name: 'conversation.composer.dock',
1775
- id: 'model-billing-cost',
1776
- order: 2,
1777
- }, CostDock))
1778
-
1779
- ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({
1780
- name: 'conversation.chat.turnTail',
1781
- id: 'model-billing-turn',
1782
- order: 30,
1783
- }, TurnCost))
1784
- },
1785
- }
1786
- },
1787
- })
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-model-billing',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const ReactDOM = require('react-dom')
6
+ const h = React.createElement
7
+ const {
8
+ Fragment,
9
+ useEffect,
10
+ useId,
11
+ useLayoutEffect,
12
+ useMemo,
13
+ useRef,
14
+ useState,
15
+ useSyncExternalStore,
16
+ } = React
17
+
18
+ // ---------------------------------------------------------------------
19
+ // Locale
20
+ // ---------------------------------------------------------------------
21
+
22
+ const STRINGS = {
23
+ zh: {
24
+ nav: '模型与费用',
25
+ title: '模型与费用',
26
+ intro: '调整已配置模型的顺序,并填写每百万 tokens 的价格。金额根据会话日志估算所有模型;DeepSeek 使用内置峰谷价。',
27
+ loading: '正在加载模型目录…',
28
+ loadFailed: '模型目录加载失败',
29
+ retry: '重试',
30
+ modelsCount: '{count} 个模型',
31
+ save: '保存',
32
+ saving: '保存中…',
33
+ saved: '已保存',
34
+ unsaved: '有未保存的修改',
35
+ undo: '撤销修改',
36
+ orderHint: '用 ↑ / ↓ 调整顺序;顺序直接决定对话框右下角模型选择器中的排列,也用于费用估算。',
37
+ noModels: '当前没有可用的已配置模型。',
38
+ up: '上移',
39
+ down: '下移',
40
+ cacheHitPrice: '输入 · 缓存命中',
41
+ cacheMissPrice: '输入 · 缓存未命中',
42
+ outputPrice: '输出',
43
+ perMillion: '元 / 百万 tokens',
44
+ deepseekTag: 'DeepSeek',
45
+ deepseekNote: '默认使用官方峰谷价;填写完整的自定义价格后,将优先按自定义价格估算。',
46
+ officialPrice: '官方定价',
47
+ priceSourceOfficial: '官方价',
48
+ priceSourceCustom: '自定义',
49
+ customizePrice: '自定义价格',
50
+ useOfficialPrice: '恢复官方价',
51
+ customPriceNote: '自定义价格优先于官方峰谷价;三项留空并保存即可恢复官方价。',
52
+ peak: '高峰',
53
+ offPeak: '空闲',
54
+ deepseekSchedule: '高峰为北京时间周一至周五 9:00–12:00、14:00–18:00(法定节假日除外);其余时段为空闲。',
55
+ pricePlaceholder: '未设置',
56
+ priceUnset: '未定价',
57
+ priceHitShort: '命中',
58
+ priceMissShort: '未命中',
59
+ priceOutShort: '输出',
60
+ priceUnit: '元/M',
61
+ invalidPrice: '价格必须是非负数字,或留空表示未设置。',
62
+ saveFailed: '保存失败:{message}',
63
+ formula: '估算公式:缓存命中输入 × 命中价 +(未缓存输入 + 缓存写入)× 未命中价 + 输出 × 输出价。',
64
+ formulaNote: '价格按每百万 tokens 计。缓存写入按缓存未命中价计算;未配置价格的模型不产生金额。',
65
+ singlePrice: '价格',
66
+ settingsOpen: '在设置中编辑',
67
+ costEstimate: '费用估算',
68
+ costDetails: '输入框下方费用估算',
69
+ close: '关闭',
70
+ thisTurn: '本轮',
71
+ sessionTotal: '本会话',
72
+ cacheHit: '缓存命中率',
73
+ tokens: '输入 / 输出',
74
+ turn: '轮次',
75
+ content: '内容',
76
+ time: '时间',
77
+ model: '使用模型',
78
+ cost: '费用',
79
+ byModel: '按模型',
80
+ excludedShort: '不计入',
81
+ partial: '部分未定价',
82
+ partialShort: '部分未定价',
83
+ partialNote: '有非 DeepSeek 调用尚未配置完整价格,合计只包含已定价部分。',
84
+ showUnpricedNotice: '显示未定价提示',
85
+ unpricedRoutes: '未定价路由',
86
+ addPrice: '补充价格',
87
+ priceSaved: '价格已保存',
88
+ archiveSection: '历史价格',
89
+ archiveHint: '已移除模型的调用仍按这里保存的价格计价,不需要把它们加回模型列表。',
90
+ archiveEmpty: '暂无历史价格',
91
+ addArchive: '添加历史价格',
92
+ archiveProvider: '提供商',
93
+ archiveModel: '模型',
94
+ archiveConflict: '该路由仍在当前模型列表中,请直接编辑上方的模型价格。',
95
+ invalidRoute: '提供商和模型都不能为空。',
96
+ remove: '删除',
97
+ estimateNote: '金额由会话日志中的 token 用量和缓存命中估算;DeepSeek 按事件时间使用内置峰谷价,实际账单以提供方为准。',
98
+ webToolNote: '含 DeepSeek Search/Fetch 按次费 ≈ {amount}(搜索 {searchBilled}/{searchCalls} 次,抓取 {fetchBilled}/{fetchCalls} 次)。',
99
+ listSep: '、',
100
+ turnCost: '费用',
101
+ turnTokens: '本轮 Token',
102
+ displaySection: '轮尾显示',
103
+ displayTurnTail: '启用轮尾显示',
104
+ displayDock: '显示输入框下方费用估算',
105
+ dockSection: '输入框下方费用估算',
106
+ dockHint: '控制输入框下方的费用条与费用估算弹层。',
107
+ displayHint: '控制每轮结束后在对话尾部显示的内容;修改后点“保存”生效。',
108
+ displayModels: '使用模型',
109
+ displayProvider: '模型提供商',
110
+ displayCost: '本轮费用',
111
+ displayTokens: 'Token 用量',
112
+ displayCacheHit: '缓存命中率',
113
+ displayLabels: '显示文字标签',
114
+ displayFontSize: '字号',
115
+ displayDensity: '间距',
116
+ displayWeight: '字重',
117
+ fontSizeSmall: '小',
118
+ fontSizeNormal: '标准',
119
+ fontSizeLarge: '大',
120
+ densityCompact: '紧凑',
121
+ densityComfortable: '舒适',
122
+ weightNormal: '常规',
123
+ weightBold: '加粗',
124
+ pickerSection: '模型选择器',
125
+ takeoverPicker: '接管模型选择器',
126
+ takeoverHint: '开启后使用本插件按自定义顺序排列的模型选择器;关闭后恢复 DSH 内置选择器。',
127
+ chooseModel: '选择模型',
128
+ loadingModels: '加载模型…',
129
+ searchModel: '搜索模型',
130
+ noMatch: '没有匹配的模型',
131
+ pickerEmpty: '暂无可用模型',
132
+ reasoningEffort: '推理强度',
133
+ providerDefault: '提供方默认',
134
+ switching: '切换中…',
135
+ pickerRetry: '重新加载',
136
+ pickerAria: '选择模型与推理强度',
137
+ pickerUnavailable: '模型目录尚未就绪,请刷新页面',
138
+ },
139
+ en: {
140
+ nav: 'Models & Cost',
141
+ title: 'Models & Cost',
142
+ intro: 'Reorder configured models and enter prices per million tokens. Amounts estimate every model from the session log; DeepSeek uses its built-in peak/off-peak prices.',
143
+ loading: 'Loading the model catalog…',
144
+ loadFailed: 'Could not load the model catalog',
145
+ retry: 'Retry',
146
+ modelsCount: '{count} models',
147
+ save: 'Save',
148
+ saving: 'Saving…',
149
+ saved: 'Saved',
150
+ unsaved: 'Unsaved changes',
151
+ undo: 'Discard changes',
152
+ orderHint: 'Use ↑ / ↓ to reorder. This order is used directly by the model picker at the bottom-right of the composer, and by the cost details.',
153
+ noModels: 'No configured models are available.',
154
+ up: 'Move up',
155
+ down: 'Move down',
156
+ cacheHitPrice: 'Input · cache hit',
157
+ cacheMissPrice: 'Input · cache miss',
158
+ outputPrice: 'Output',
159
+ perMillion: 'CNY / million tokens',
160
+ deepseekTag: 'DeepSeek',
161
+ deepseekNote: 'Official peak/off-peak prices are used by default; a complete custom price set takes precedence.',
162
+ officialPrice: 'Official prices',
163
+ priceSourceOfficial: 'Official',
164
+ priceSourceCustom: 'Custom',
165
+ customizePrice: 'Set custom prices',
166
+ useOfficialPrice: 'Restore official prices',
167
+ customPriceNote: 'Custom prices override the official peak/off-peak table. Leave all three blank and save to restore official prices.',
168
+ peak: 'Peak',
169
+ offPeak: 'Off-peak',
170
+ deepseekSchedule: 'Peak: Beijing time Mon–Fri 09:00–12:00 and 14:00–18:00, excluding Chinese statutory holidays; all other times are off-peak.',
171
+ pricePlaceholder: 'Not set',
172
+ priceUnset: 'Not priced',
173
+ priceHitShort: 'hit',
174
+ priceMissShort: 'miss',
175
+ priceOutShort: 'out',
176
+ priceUnit: 'CNY/M',
177
+ invalidPrice: 'Prices must be non-negative numbers, or blank when unset.',
178
+ saveFailed: 'Save failed: {message}',
179
+ formula: 'Estimate: cached input × hit price + (uncached input + cache write) × miss price + output × output price.',
180
+ formulaNote: 'Prices are per million tokens. Cache writes use the cache-miss price; models without a full price set produce no amount.',
181
+ singlePrice: 'Prices',
182
+ settingsOpen: 'Edit in Settings',
183
+ costEstimate: 'Cost estimate',
184
+ costDetails: 'Composer cost estimate',
185
+ close: 'Close',
186
+ thisTurn: 'Turn',
187
+ sessionTotal: 'Session',
188
+ cacheHit: 'Cache hit rate',
189
+ tokens: 'Input / output',
190
+ turn: 'Turn',
191
+ content: 'Content',
192
+ time: 'Time',
193
+ model: 'Model',
194
+ cost: 'Cost',
195
+ byModel: 'By model',
196
+ excludedShort: 'Excluded',
197
+ partial: 'partly unpriced',
198
+ partialShort: 'partly unpriced',
199
+ partialNote: 'Some non-DeepSeek calls do not have a complete price set; the total includes only priced calls.',
200
+ showUnpricedNotice: 'Show unpriced notices',
201
+ unpricedRoutes: 'Unpriced routes',
202
+ addPrice: 'Add price',
203
+ priceSaved: 'Price saved',
204
+ archiveSection: 'Historical prices',
205
+ archiveHint: 'Calls to removed models stay priced from this book; you do not need to add them back to the model list.',
206
+ archiveEmpty: 'No historical prices yet',
207
+ addArchive: 'Add historical price',
208
+ archiveProvider: 'Provider',
209
+ archiveModel: 'Model',
210
+ archiveConflict: 'This route is still in the configured list; edit its price above instead.',
211
+ invalidRoute: 'Provider and model are both required.',
212
+ remove: 'Remove',
213
+ estimateNote: 'Amounts are estimated from token usage and cache hits in the session log; DeepSeek uses built-in peak/off-peak prices at the event time, and the provider bill is authoritative.',
214
+ webToolNote: 'Includes DeepSeek Search/Fetch per-request fees ≈ {amount} (search {searchBilled}/{searchCalls}, fetch {fetchBilled}/{fetchCalls}).',
215
+ listSep: ', ',
216
+ turnCost: 'Cost',
217
+ turnTokens: 'Turn tokens',
218
+ displaySection: 'Turn-tail display',
219
+ displayTurnTail: 'Show the turn tail',
220
+ displayDock: 'Show the composer cost estimate',
221
+ dockSection: 'Composer cost estimate',
222
+ dockHint: 'Controls the cost bar below the composer and its detail panel.',
223
+ displayHint: 'Choose what appears below each completed turn; click Save to apply.',
224
+ displayModels: 'Models used',
225
+ displayProvider: 'Model provider',
226
+ displayCost: 'Turn cost',
227
+ displayTokens: 'Token usage',
228
+ displayCacheHit: 'Cache hit rate',
229
+ displayLabels: 'Show text labels',
230
+ displayFontSize: 'Font size',
231
+ displayDensity: 'Spacing',
232
+ displayWeight: 'Font weight',
233
+ fontSizeSmall: 'Small',
234
+ fontSizeNormal: 'Normal',
235
+ fontSizeLarge: 'Large',
236
+ densityCompact: 'Compact',
237
+ densityComfortable: 'Comfortable',
238
+ weightNormal: 'Regular',
239
+ weightBold: 'Bold',
240
+ pickerSection: 'Model picker',
241
+ takeoverPicker: 'Take over the model picker',
242
+ takeoverHint: 'On: use this plugin’s picker with your custom model order. Off: restore the built-in DSH picker.',
243
+ chooseModel: 'Select model',
244
+ loadingModels: 'Loading models…',
245
+ searchModel: 'Search models',
246
+ noMatch: 'No matching model',
247
+ pickerEmpty: 'No model available',
248
+ reasoningEffort: 'Reasoning effort',
249
+ providerDefault: 'Provider default',
250
+ switching: 'Switching…',
251
+ pickerRetry: 'Reload',
252
+ pickerAria: 'Select model and reasoning effort',
253
+ pickerUnavailable: 'The model directory is not ready; reload the page',
254
+ },
255
+ }
256
+
257
+ const t = (key, values) => {
258
+ const active = localeService?.getSnapshot?.().active ?? 'zh'
259
+ const dict = active.toLowerCase().startsWith('en') ? STRINGS.en : STRINGS.zh
260
+ const template = dict[key] ?? STRINGS.zh[key] ?? key
261
+ return values === undefined
262
+ ? template
263
+ : template.replace(/\{(\w+)\}/g, (match, name) => values[name] === undefined ? match : String(values[name]))
264
+ }
265
+
266
+ let localeService
267
+ let modelDirectories
268
+ let modelDirectoryRevision = 0
269
+ const modelDirectoryListeners = new Set()
270
+
271
+ function publishModelDirectories(next) {
272
+ if (next === undefined || next === modelDirectories) return
273
+ modelDirectories = next
274
+ modelDirectoryRevision += 1
275
+ for (const listener of [...modelDirectoryListeners]) listener()
276
+ }
277
+
278
+ function subscribeModelDirectories(listener) {
279
+ modelDirectoryListeners.add(listener)
280
+ return () => modelDirectoryListeners.delete(listener)
281
+ }
282
+
283
+ function useModelDirectoriesRevision() {
284
+ return useSyncExternalStore(
285
+ subscribeModelDirectories,
286
+ () => modelDirectoryRevision,
287
+ () => 0,
288
+ )
289
+ }
290
+
291
+ function subscribeLocale(listener) {
292
+ return localeService?.subscribe?.(listener) ?? (() => {})
293
+ }
294
+
295
+ function localeRevision() {
296
+ return localeService?.getSnapshot?.().revision ?? 0
297
+ }
298
+
299
+ function useT() {
300
+ useSyncExternalStore(subscribeLocale, localeRevision, () => 0)
301
+ return t
302
+ }
303
+
304
+ const DISPLAY_DEFAULTS = Object.freeze({
305
+ showTurnTail: true,
306
+ showDock: true,
307
+ showModels: true,
308
+ showProvider: false,
309
+ showCost: true,
310
+ showTokens: false,
311
+ showCacheHit: false,
312
+ showLabels: true,
313
+ showUnpricedNotice: true,
314
+ takeoverPicker: true,
315
+ fontSize: 'normal',
316
+ density: 'comfortable',
317
+ fontWeight: 'normal',
318
+ })
319
+
320
+ const DISPLAY_STORAGE_KEY = 'dsh-model-billing.display'
321
+
322
+ function clearStoredDisplay() {
323
+ try {
324
+ localStorage.removeItem(DISPLAY_STORAGE_KEY)
325
+ } catch {
326
+ // Ignore unavailable storage.
327
+ }
328
+ }
329
+
330
+ // Older builds mirrored display settings into localStorage, which made the
331
+ // browser a second source of truth that could never sync across devices.
332
+ // Clear the legacy key once; the Host state is now the only copy.
333
+ clearStoredDisplay()
334
+
335
+ function readDisplay(data) {
336
+ const source = data?.display
337
+ return source !== null && typeof source === 'object' && !Array.isArray(source)
338
+ ? { ...DISPLAY_DEFAULTS, ...source }
339
+ : { ...DISPLAY_DEFAULTS }
340
+ }
341
+
342
+ // ---------------------------------------------------------------------
343
+ // Shared catalog state
344
+ // ---------------------------------------------------------------------
345
+
346
+ const catalog = {
347
+ snap: { status: 'idle', data: null, error: null },
348
+ listeners: new Set(),
349
+ inflight: null,
350
+ generation: 0,
351
+ }
352
+
353
+ const REQUEST_TIMEOUT_MS = 8000
354
+
355
+ async function requestJson(url, options) {
356
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
357
+ const timeout = controller === null
358
+ ? null
359
+ : setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
360
+ let response
361
+ try {
362
+ response = await fetch(url, {
363
+ credentials: 'same-origin',
364
+ cache: 'no-store',
365
+ ...options,
366
+ signal: options?.signal ?? controller?.signal ?? null,
367
+ headers: {
368
+ accept: 'application/json',
369
+ ...(options?.headers ?? {}),
370
+ },
371
+ })
372
+ } catch (error) {
373
+ if (timeout !== null) clearTimeout(timeout)
374
+ throw controller !== null && error?.name === 'AbortError'
375
+ ? new Error(`timeout after ${REQUEST_TIMEOUT_MS}ms`)
376
+ : error
377
+ }
378
+ if (timeout !== null) clearTimeout(timeout)
379
+ let body
380
+ try {
381
+ body = await response.json()
382
+ } catch {
383
+ throw new Error(`HTTP ${response.status}`)
384
+ }
385
+ if (!response.ok || body?.ok === false) {
386
+ throw new Error(body?.message ?? `HTTP ${response.status}`)
387
+ }
388
+ return body
389
+ }
390
+
391
+ function emitCatalog() {
392
+ for (const listener of [...catalog.listeners]) listener()
393
+ }
394
+
395
+ function setCatalog(draft) {
396
+ catalog.snap = { ...catalog.snap, ...draft }
397
+ emitCatalog()
398
+ }
399
+
400
+ async function ensureCatalog(force = false) {
401
+ if (!force && catalog.snap.status === 'ready') return catalog.snap.data
402
+ if (catalog.inflight !== null && !force) return catalog.inflight
403
+ catalog.generation += 1
404
+ const generation = catalog.generation
405
+ setCatalog({ status: 'loading', error: null })
406
+ const operation = requestJson('/model-billing/catalog')
407
+ .then((data) => {
408
+ if (generation !== catalog.generation) return data
409
+ setCatalog({ status: 'ready', data, error: null })
410
+ return data
411
+ })
412
+ .catch((error) => {
413
+ if (generation === catalog.generation) {
414
+ setCatalog({ status: 'error', error: error instanceof Error ? error.message : String(error) })
415
+ }
416
+ return null
417
+ })
418
+ .finally(() => {
419
+ if (catalog.inflight === operation) catalog.inflight = null
420
+ })
421
+ catalog.inflight = operation
422
+ return operation
423
+ }
424
+
425
+ function subscribeCatalog(listener) {
426
+ catalog.listeners.add(listener)
427
+ if (catalog.snap.status === 'idle') void ensureCatalog()
428
+ return () => catalog.listeners.delete(listener)
429
+ }
430
+
431
+ function catalogSnapshot() {
432
+ return catalog.snap
433
+ }
434
+
435
+ function useCatalog() {
436
+ return useSyncExternalStore(subscribeCatalog, catalogSnapshot, catalogSnapshot)
437
+ }
438
+
439
+ // ---------------------------------------------------------------------
440
+ // Shared session usage state
441
+ // ---------------------------------------------------------------------
442
+
443
+ const usageSlots = new Map()
444
+ const USAGE_DEBOUNCE_MS = 300
445
+
446
+ function usageSlot(sessionId) {
447
+ let slot = usageSlots.get(sessionId)
448
+ if (slot === undefined) {
449
+ slot = {
450
+ snap: { status: 'idle', data: null, error: null },
451
+ listeners: new Set(),
452
+ inflight: null,
453
+ generation: 0,
454
+ revision: null,
455
+ pending: null,
456
+ refs: 0,
457
+ rowsByTurn: new Map(),
458
+ }
459
+ usageSlots.set(sessionId, slot)
460
+ }
461
+ slot.refs += 1
462
+ return slot
463
+ }
464
+
465
+ function releaseSlot(sessionId, slot) {
466
+ slot.refs = Math.max(0, slot.refs - 1)
467
+ if (slot.listeners.size > 0 || slot.refs > 0) return
468
+ if (slot.pending !== null) {
469
+ clearTimeout(slot.pending)
470
+ slot.pending = null
471
+ }
472
+ usageSlots.delete(sessionId)
473
+ }
474
+
475
+ function emitUsage(slot) {
476
+ for (const listener of [...slot.listeners]) listener()
477
+ }
478
+
479
+ function ensureUsage(sessionId, revision, force = false) {
480
+ const slot = usageSlot(sessionId)
481
+ if (!force && slot.revision === revision && slot.snap.status !== 'error') return
482
+ if (slot.inflight !== null && !force) return
483
+ slot.revision = revision
484
+ if (slot.pending !== null) clearTimeout(slot.pending)
485
+ // Collapse the token-counter updates a streaming reply produces into one
486
+ // trailing request instead of one request per token.
487
+ slot.pending = setTimeout(() => {
488
+ slot.pending = null
489
+ void fetchUsage(sessionId, revision)
490
+ }, USAGE_DEBOUNCE_MS)
491
+ }
492
+
493
+ function fetchUsage(sessionId, revision) {
494
+ const slot = usageSlots.get(sessionId)
495
+ if (slot === undefined) return
496
+ slot.generation += 1
497
+ const generation = slot.generation
498
+ slot.snap = { ...slot.snap, status: 'loading', error: null }
499
+ emitUsage(slot)
500
+ const operation = requestJson(`/model-billing/usage?sessionId=${encodeURIComponent(sessionId)}`)
501
+ .then((data) => {
502
+ if (generation !== slot.generation) return
503
+ // Index once per fetch rather than scanning the row list on every
504
+ // turn render.
505
+ slot.snap = { status: 'ready', data, rowsByTurn: indexRowsByTurn(data), error: null }
506
+ slot.rowsByTurn = slot.snap.rowsByTurn
507
+ emitUsage(slot)
508
+ })
509
+ .catch((error) => {
510
+ if (generation !== slot.generation) return
511
+ slot.snap = {
512
+ status: 'error',
513
+ data: slot.snap.data,
514
+ rowsByTurn: slot.snap.rowsByTurn,
515
+ error: error instanceof Error ? error.message : String(error),
516
+ }
517
+ emitUsage(slot)
518
+ })
519
+ .finally(() => {
520
+ if (slot.inflight === operation) slot.inflight = null
521
+ })
522
+ slot.inflight = operation
523
+ return operation
524
+ }
525
+
526
+ function indexRowsByTurn(data) {
527
+ const index = new Map()
528
+ if (Array.isArray(data?.usage?.turns)) {
529
+ for (const row of data.usage.turns) index.set(row.turn, row)
530
+ }
531
+ return index
532
+ }
533
+
534
+ function useSessionUsage(sessionId, revision) {
535
+ const slot = usageSlot(sessionId)
536
+ useEffect(() => () => releaseSlot(sessionId, slot), [sessionId, slot])
537
+ const snap = useSyncExternalStore(
538
+ (listener) => {
539
+ slot.listeners.add(listener)
540
+ return () => slot.listeners.delete(listener)
541
+ },
542
+ () => slot.snap,
543
+ () => slot.snap,
544
+ )
545
+ useEffect(() => {
546
+ if (sessionId !== undefined && revision !== null) ensureUsage(sessionId, revision)
547
+ }, [sessionId, revision])
548
+ return snap
549
+ }
550
+
551
+ function tokenUsageRevision(tokenUsage) {
552
+ if (tokenUsage === undefined || tokenUsage === null) return 'none'
553
+ return [
554
+ tokenUsage.uncachedInputTokens ?? '',
555
+ tokenUsage.outputTokens ?? '',
556
+ tokenUsage.cacheReadTokens ?? '',
557
+ tokenUsage.cacheWriteTokens ?? '',
558
+ ].join(':')
559
+ }
560
+
561
+ // ---------------------------------------------------------------------
562
+ // Formatting
563
+ // ---------------------------------------------------------------------
564
+
565
+ function formatMoney(value) {
566
+ if (value === null || value === undefined || !Number.isFinite(value)) return '—'
567
+ if (value === 0) return '¥0'
568
+ const fixed = value.toFixed(2)
569
+ return fixed === '0.00' ? '<¥0.01' : `¥${fixed}`
570
+ }
571
+
572
+ function formatTokens(value) {
573
+ if (!Number.isFinite(value)) return '—'
574
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(2)}M`
575
+ if (value >= 1_000) return `${(value / 1_000).toFixed(1)}k`
576
+ return String(Math.round(value))
577
+ }
578
+
579
+ function formatPercent(value) {
580
+ return value === null || value === undefined ? '—' : `${(value * 100).toFixed(1)}%`
581
+ }
582
+
583
+ function formatPrice(value) {
584
+ if (value === null || value === undefined) return '—'
585
+ return String(Number(value.toFixed(6)))
586
+ }
587
+
588
+ function PriceLines({ pricing, translate, showSource = true }) {
589
+ const source = showSource === false ? null : pricing?.source === 'official'
590
+ ? translate('priceSourceOfficial')
591
+ : pricing?.source === 'user' ? translate('priceSourceCustom') : null
592
+ const sourceLine = source === null ? null : h('div', { className: 'mb-picker-price-source' }, source)
593
+ if (pricing?.builtin === true) {
594
+ const line = (label, prices) =>
595
+ `${label} ${translate('priceHitShort')} ${formatPrice(prices?.cacheHit)} · ${translate('priceMissShort')} ${formatPrice(prices?.cacheMiss)} · ${translate('priceOutShort')} ${formatPrice(prices?.output)} ${translate('priceUnit')}`
596
+ return h('div', { className: 'mb-picker-prices' },
597
+ sourceLine,
598
+ h('div', { className: 'mb-picker-price-line' }, line(translate('peak'), pricing.peak)),
599
+ h('div', { className: 'mb-picker-price-line' }, line(translate('offPeak'), pricing.offPeak)))
600
+ }
601
+ const hasAny = pricing !== null && pricing !== undefined
602
+ && [pricing.cacheHit, pricing.cacheMiss, pricing.output].some((value) => typeof value === 'number')
603
+ if (!hasAny) {
604
+ return h('div', { className: 'mb-picker-prices' }, translate('priceUnset'))
605
+ }
606
+ return h('div', { className: 'mb-picker-prices' },
607
+ sourceLine,
608
+ h('div', { className: 'mb-picker-price-line' },
609
+ `${translate('priceHitShort')} ${formatPrice(pricing.cacheHit)} · ${translate('priceMissShort')} ${formatPrice(pricing.cacheMiss)} · ${translate('priceOutShort')} ${formatPrice(pricing.output)} ${translate('priceUnit')}`))
610
+ }
611
+
612
+ function timeText(timestamp) {
613
+ if (!Number.isFinite(timestamp) || timestamp <= 0) return ''
614
+ try {
615
+ return new Date(timestamp).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
616
+ } catch {
617
+ return ''
618
+ }
619
+ }
620
+
621
+ // ---------------------------------------------------------------------
622
+ // Styles
623
+ // ---------------------------------------------------------------------
624
+
625
+ const CSS = `
626
+ .mb-page { color: var(--dsw-alias-label-primary); font-size: 13px; line-height: 1.5; padding: 4px 0 28px; }
627
+ .mb-page * { box-sizing: border-box; }
628
+ .mb-title { margin: 0 0 4px; font-size: 18px; font-weight: 600; }
629
+ .mb-intro { margin: 0 0 14px; color: var(--dsw-alias-label-secondary); max-width: 760px; }
630
+ .mb-toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 14px 0; }
631
+ .mb-muted { color: var(--dsw-alias-label-secondary); }
632
+ .mb-spacer { flex: 1; }
633
+ .mb-btn { appearance: none; border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); border-radius: 7px; height: 30px; padding: 0 12px; font: inherit; cursor: pointer; }
634
+ .mb-btn:hover:not(:disabled) { background: var(--dsw-alias-bg-layer-2); }
635
+ .mb-btn:disabled { opacity: .45; cursor: default; }
636
+ .mb-btn-primary { background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-bg-base); font-weight: 600; }
637
+ .mb-btn-primary:hover:not(:disabled) { background: var(--dsw-alias-brand-primary); opacity: .9; }
638
+ .mb-btn-icon { width: 28px; height: 28px; padding: 0; font-size: 13px; }
639
+ .mb-status { color: var(--dsw-alias-label-secondary); min-height: 18px; }
640
+ .mb-status[data-tone="error"] { color: var(--dsw-alias-state-error-primary); }
641
+ .mb-status[data-tone="success"] { color: var(--dsw-alias-state-success-primary); }
642
+ .mb-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; max-width: 980px; }
643
+ .mb-card { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); border-radius: 10px; padding: 12px 14px; }
644
+ .mb-card-head { display: flex; align-items: flex-start; gap: 12px; }
645
+ .mb-index { width: 26px; height: 26px; border-radius: 7px; background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-secondary); display: grid; place-items: center; font-variant-numeric: tabular-nums; flex: none; }
646
+ .mb-name { font-weight: 600; font-size: 14px; }
647
+ .mb-sub { color: var(--dsw-alias-label-secondary); font-size: 12px; overflow-wrap: anywhere; }
648
+ .mb-head-actions { margin-left: auto; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; justify-content: flex-end; }
649
+ .mb-tag { display: inline-block; margin-left: 6px; padding: 1px 6px; border-radius: 999px; background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-secondary); font-size: 11px; font-weight: 500; vertical-align: 1px; }
650
+ .mb-tag-excluded { color: var(--dsw-alias-state-warn-primary); }
651
+ .mb-prices { display: grid; gap: 10px; margin-top: 12px; }
652
+ .mb-price-group { border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px; padding: 10px 12px 12px; }
653
+ .mb-price-group-title { display: flex; gap: 8px; align-items: baseline; margin-bottom: 8px; font-weight: 600; }
654
+ .mb-price-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
655
+ .mb-card-actions { margin-top: 10px; display: flex; justify-content: flex-end; }
656
+ .mb-field { display: grid; gap: 4px; min-width: 0; }
657
+ .mb-field-label { color: var(--dsw-alias-label-secondary); font-size: 11px; }
658
+ .mb-input { width: 100%; height: 30px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); padding: 0 8px; font: inherit; font-variant-numeric: tabular-nums; }
659
+ .mb-input:focus { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -1px; }
660
+ .mb-note { margin: 8px 0 0; color: var(--dsw-alias-label-secondary); font-size: 12px; }
661
+ .mb-warn { margin: 6px 0 0; color: var(--dsw-alias-state-warn-primary); font-size: 12px; }
662
+ .mb-empty { border: 1px dashed var(--dsw-alias-border-l2); border-radius: 10px; padding: 28px; text-align: center; color: var(--dsw-alias-label-secondary); }
663
+ .mb-footer-note { max-width: 980px; margin-top: 14px; color: var(--dsw-alias-label-secondary); font-size: 12px; }
664
+ .mb-dock { align-self: center; display: flex; flex-direction: column; align-items: flex-start; color: var(--dsw-alias-label-tertiary); font-size: calc(var(--dsh-content-font-size-secondary, 13px) - 1px); line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px)); }
665
+ .mb-dock-trigger { appearance: none; border: 0; background: transparent; color: inherit; font: inherit; line-height: inherit; padding: 1px 8px; border-radius: var(--dsw-radius-sm); display: inline-flex; align-items: center; gap: 6px; cursor: pointer; text-align: left; max-width: 100%; flex-wrap: nowrap; }
666
+ .mb-dock-trigger:hover, .mb-dock-trigger[aria-expanded="true"] { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-secondary); }
667
+ .mb-dock-amount { color: var(--dsw-alias-label-secondary); font-weight: 500; font-variant-numeric: tabular-nums; }
668
+ .mb-dock-sep { opacity: .55; }
669
+ .mb-dock-icon { flex: none; width: 14px; height: 14px; }
670
+ .mb-dock-caret { font-size: 10px; opacity: .7; }
671
+ .mb-panel { box-sizing: border-box; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-menu-surface-fill, var(--dsw-alias-bg-layer-1)); border-radius: var(--dsw-radius-lg, 10px); padding: 10px 12px; color: var(--dsw-alias-label-primary); }
672
+ .mb-panel-floating { position: fixed; z-index: 1200; max-width: calc(100vw - 24px); max-height: min(430px, calc(100vh - 96px)); overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: var(--dsw-alias-scrollbar-bg-l2, var(--dsw-alias-border-l2)) transparent; box-shadow: var(--dsw-elevation-prominent); backdrop-filter: var(--dsw-menu-backdrop-filter, none); }
673
+ .mb-panel-head { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; }
674
+ .mb-panel-title { font-weight: 600; }
675
+ .mb-panel-close { margin-left: auto; width: 24px; height: 24px; border: 0; border-radius: var(--dsw-radius-sm); background: 0 0; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 18px; line-height: 20px; cursor: pointer; }
676
+ .mb-panel-close:hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
677
+ .mb-summary { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-bottom: 10px; }
678
+ .mb-summary-item { background: var(--dsw-alias-bg-layer-2); border-radius: 7px; padding: 7px 9px; min-width: 0; }
679
+ .mb-summary-key { color: var(--dsw-alias-label-secondary); font-size: 11px; }
680
+ .mb-summary-value { font-variant-numeric: tabular-nums; font-weight: 600; overflow-wrap: anywhere; }
681
+ .mb-table { width: 100%; border-collapse: collapse; font-size: 12px; }
682
+ .mb-table th, .mb-table td { text-align: left; padding: 4px 5px; border-bottom: 1px solid var(--dsw-alias-border-l1); vertical-align: top; }
683
+ .mb-table th { color: var(--dsw-alias-label-secondary); font-weight: 500; font-size: 11px; }
684
+ .mb-table td.num, .mb-table th.num { text-align: right; font-variant-numeric: tabular-nums; }
685
+ .mb-table tr:last-child td { border-bottom: 0; }
686
+ .mb-turn-table { table-layout: fixed; }
687
+ .mb-turn-table th, .mb-turn-table td, .mb-turn-table th.num, .mb-turn-table td.num { text-align: left; }
688
+ .mb-turn-table th:nth-child(1), .mb-turn-table td:nth-child(1) { width: 5%; }
689
+ .mb-turn-table th:nth-child(2), .mb-turn-table td:nth-child(2) { width: 25.5%; }
690
+ .mb-turn-table th:nth-child(3), .mb-turn-table td:nth-child(3) { width: 12.5%; }
691
+ .mb-turn-table th:nth-child(4), .mb-turn-table td:nth-child(4) { width: 21%; }
692
+ .mb-turn-table th:nth-child(5), .mb-turn-table td:nth-child(5) { width: 10%; }
693
+ .mb-turn-table th:nth-child(6), .mb-turn-table td:nth-child(6) { width: 16%; }
694
+ .mb-turn-table th:nth-child(7), .mb-turn-table td:nth-child(7) { width: 10%; }
695
+ .mb-turn-preview, .mb-turn-model { color: var(--dsw-alias-label-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
696
+ .mb-turn-model { color: var(--dsw-alias-label-primary); }
697
+ .mb-panel-note { margin: 9px 0 0; color: var(--dsw-alias-label-secondary); font-size: 11px; }
698
+ .mb-turn { color: var(--dsw-alias-label-secondary); font-size: 12px; font-variant-numeric: tabular-nums; display: inline-flex; flex-wrap: wrap; align-items: baseline; column-gap: 10px; row-gap: 2px; max-width: 100%; }
699
+ .mb-turn[data-size="small"] { font-size: 11px; }
700
+ .mb-turn[data-size="large"] { font-size: 13px; }
701
+ .mb-turn[data-density="compact"] { column-gap: 6px; }
702
+ .mb-turn-item { white-space: nowrap; }
703
+ .mb-turn strong { color: inherit; font-weight: 600; }
704
+ .mb-turn[data-weight="normal"] { font-weight: 400; }
705
+ .mb-turn[data-weight="normal"] strong { font-weight: 400; }
706
+ .mb-turn[data-weight="bold"] { font-weight: 600; }
707
+ .mb-turn[data-weight="bold"] strong { font-weight: 600; }
708
+ .mb-turn-partial { color: var(--dsw-alias-state-warn-primary); }
709
+ .mb-display { border: 1px solid var(--dsw-alias-border-l1); border-radius: 10px; padding: 12px 14px; margin: 10px 0 14px; background: var(--dsw-alias-bg-layer-2); }
710
+ .mb-display-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; }
711
+ .mb-display-title { font-weight: 600; }
712
+ .mb-display-hint { color: var(--dsw-alias-label-secondary); font-size: 12px; }
713
+ .mb-check-grid { display: flex; flex-wrap: wrap; gap: 8px 18px; }
714
+ .mb-check { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; }
715
+ .mb-check.is-disabled { opacity: .55; cursor: default; }
716
+ .mb-check input { width: 15px; height: 15px; accent-color: var(--dsw-alias-brand-primary); }
717
+ .mb-display-controls { display: flex; flex-wrap: wrap; gap: 10px 18px; margin-top: 12px; }
718
+ .mb-archive-list { display: flex; flex-direction: column; gap: 8px; }
719
+ .mb-archive-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 8px; align-items: center; }
720
+ .mb-archive-row .mb-archive-provider { grid-column: 1; grid-row: 1; min-width: 0; }
721
+ .mb-archive-row .mb-archive-model { grid-column: 2; grid-row: 1; min-width: 0; }
722
+ .mb-archive-row > .mb-btn { grid-column: 3; grid-row: 1; }
723
+ .mb-archive-row .mb-archive-price { grid-row: 2; min-width: 0; }
724
+ .mb-route-editor { display: flex; flex-wrap: wrap; }
725
+ .mb-route-editor .mb-input { flex: 1 1 120px; min-width: 110px; }
726
+ .mb-route-editor .mb-btn { flex: 0 0 auto; }
727
+ .mb-archive-actions { display: flex; gap: 8px; margin-top: 10px; }
728
+ .mb-master { display: flex; align-items: center; gap: 10px; padding: 10px 0 4px; font-size: 15px; font-weight: 600; cursor: pointer; }
729
+ .mb-master input { width: 16px; height: 16px; flex: 0 0 auto; }
730
+ .mb-master-label { line-height: 1.4; }
731
+ .mb-master-hint { color: var(--dsw-alias-label-secondary); font-size: 12px; font-weight: 400; }
732
+ .mb-subchecks { margin: 2px 0 0 26px; }
733
+ .mb-tag.is-muted { color: var(--dsw-alias-label-secondary); }
734
+ @media (max-width: 720px) {
735
+ .mb-subchecks { margin-left: 18px; }
736
+ }
737
+ .mb-select { height: 30px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); padding: 0 8px; font: inherit; }
738
+ .mb-select:focus { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -1px; }
739
+ .mb-picker { position: relative; display: flex; min-width: 0; }
740
+ .mb-picker-trigger { border-radius: var(--dsw-radius-sm); min-width: 0; max-width: min(360px, 45cqw); height: 28px; color: var(--dsw-alias-label-secondary); cursor: pointer; background: 0 0; border: none; outline: none; align-items: center; gap: 4px; padding: 0 4px 0 8px; font-size: 13px; font-weight: 400; line-height: 20px; display: flex; }
741
+ .mb-picker-trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
742
+ .mb-picker-trigger:focus-visible { box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }
743
+ .mb-picker-trigger:disabled { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-secondary)); cursor: default; }
744
+ .mb-picker-icon { display: var(--dsh-composer-model-icon-display, none); flex: none; }
745
+ .mb-picker-name { color: inherit; text-overflow: ellipsis; white-space: nowrap; min-width: 0; overflow: hidden; display: var(--dsh-composer-model-text-display, block); }
746
+ .mb-picker-trigger-effort { text-overflow: ellipsis; white-space: nowrap; min-width: 0; color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); flex-shrink: 1000; overflow: hidden; display: var(--dsh-composer-model-text-display, block); }
747
+ .mb-picker-chevron { color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); flex: none; transition: transform .12s; }
748
+ .mb-picker-chevron-open { transform: rotate(180deg); }
749
+ .mb-picker-menu { box-sizing: border-box; z-index: 1100; width: min(360px, calc(100vw - 32px)); max-width: min(360px, calc(100vw - 32px)); max-height: min(480px, calc(100vh - 96px)); box-shadow: var(--dsw-elevation-prominent); background: var(--dsw-menu-surface-fill, var(--dsw-alias-bg-layer-1)); backdrop-filter: var(--dsw-menu-backdrop-filter, none); color: var(--dsw-alias-label-primary); border: 0; border-radius: var(--dsw-radius-lg, 10px); flex-direction: column; padding: 10px; display: flex; position: fixed; overflow: hidden; }
750
+ .mb-picker-search { box-sizing: border-box; border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-layer-2); border: 1px solid var(--dsw-alias-border-l1); height: 32px; margin: 0 0 6px; padding: 0 9px; font: inherit; font-size: 13px; color: var(--dsw-alias-label-primary); width: 100%; flex: none; }
751
+ .mb-picker-search::placeholder { color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); }
752
+ .mb-picker-search:focus { border-color: var(--dsw-alias-state-business-primary); outline: none; }
753
+ .mb-picker-list { min-height: 0; overflow-y: auto; padding: 0 2px; display: flex; flex-direction: column; }
754
+ .mb-picker-group { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); background: var(--dsw-alias-menu-group-header-fill, var(--dsw-menu-surface-fill, var(--dsw-alias-bg-layer-1))); position: sticky; top: 0; z-index: 1; margin-top: 2px; padding: 10px 10px 6px; font-size: 11px; font-weight: 500; line-height: 16px; }
755
+ .mb-picker-row { box-sizing: border-box; border-radius: var(--dsw-radius-md); width: auto; min-width: 100%; color: inherit; text-align: left; cursor: pointer; background: 0 0; border: none; outline: none; align-items: center; gap: 8px; padding: 10px; font: inherit; display: flex; }
756
+ .mb-picker-row + .mb-picker-row { margin-top: 2px; }
757
+ .mb-picker-row:hover:not(:disabled), .mb-picker-row:focus-visible { background: var(--dsw-alias-interactive-bg-hover); }
758
+ .mb-picker-row:disabled { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-secondary)); cursor: default; }
759
+ .mb-picker-option-copy { flex-direction: column; flex: 1; min-width: 0; gap: 4px; display: flex; }
760
+ .mb-picker-model { color: inherit; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 400; line-height: 20px; overflow: hidden; }
761
+ .mb-picker-prices { color: var(--dsw-alias-label-caption, var(--dsw-alias-label-secondary)); font-size: 11px; line-height: 17px; font-variant-numeric: tabular-nums; }
762
+ .mb-picker-price-line { white-space: normal; overflow-wrap: anywhere; }
763
+ .mb-picker-price-source { margin-bottom: 2px; color: var(--dsw-alias-label-secondary); font-weight: 600; }
764
+ .mb-picker-check { color: var(--dsw-alias-label-primary); flex: 0 0 14px; place-items: center; display: grid; font-size: 12px; }
765
+ .mb-picker-check svg { width: 14px; height: 14px; }
766
+ .mb-picker-empty { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); padding: 8px; font-size: 12px; line-height: 18px; }
767
+ .mb-picker-divider { border-top: 1px solid var(--dsw-alias-border-l1); margin: 3px 0; }
768
+ .mb-picker-efforts { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; padding: 2px 4px 4px; }
769
+ .mb-picker-efforts-label { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); font-size: 11px; margin-right: 2px; }
770
+ .mb-picker-chip { appearance: none; border: 0; background: 0 0; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 11px; height: 24px; padding: 0 7px; border-radius: var(--dsw-radius-sm); cursor: pointer; }
771
+ .mb-picker-chip:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
772
+ .mb-picker-chip[aria-pressed="true"] { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
773
+ .mb-picker-error { border-radius: var(--dsw-radius-md); background: var(--dsw-alias-interactive-bg-hover-danger); color: var(--dsw-alias-state-error-primary); margin-bottom: 3px; padding: 6px 7px; font-size: 11px; line-height: 16px; }
774
+ .mb-picker-retry { align-self: flex-start; margin: 0 4px 2px; }
775
+ .mb-picker-status { color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); padding: 4px 7px; font-size: 11px; line-height: 16px; }
776
+ .mb-fatal { border: 1px solid var(--dsw-alias-state-error-primary); color: var(--dsw-alias-state-error-primary); border-radius: 8px; padding: 12px; }
777
+ @media (max-width: 720px) {
778
+ .mb-price-grid { grid-template-columns: 1fr; }
779
+ .mb-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
780
+ .mb-head-actions { width: 100%; margin-left: 38px; justify-content: flex-start; }
781
+ }
782
+ `
783
+
784
+ const STYLE_MARKER = 'data-dsh-model-billing'
785
+
786
+ // The stylesheet belongs to the plugin, not to any one surface, so inject it
787
+ // once into <head> instead of rendering a copy per settings page, dock,
788
+ // panel and picker.
789
+ function ensureStylesheet() {
790
+ if (typeof document === 'undefined') return
791
+ if (document.head.querySelector(`style[${STYLE_MARKER}]`) !== null) return
792
+ const style = document.createElement('style')
793
+ style.setAttribute(STYLE_MARKER, '')
794
+ style.textContent = CSS
795
+ document.head.appendChild(style)
796
+ }
797
+
798
+ function Style() {
799
+ ensureStylesheet()
800
+ return null
801
+ }
802
+
803
+ // ---------------------------------------------------------------------
804
+ // Settings section
805
+ // ---------------------------------------------------------------------
806
+
807
+ const PRICE_FIELDS = ['cacheHit', 'cacheMiss', 'output']
808
+ const PRICE_LABEL_KEYS = {
809
+ cacheHit: 'cacheHitPrice',
810
+ cacheMiss: 'cacheMissPrice',
811
+ output: 'outputPrice',
812
+ }
813
+
814
+ function toDraftPricing(pricing) {
815
+ if (pricing?.builtin === true) return { ...pricing, peak: { ...pricing.peak }, offPeak: { ...pricing.offPeak } }
816
+ const source = pricing ?? {}
817
+ return Object.fromEntries(PRICE_FIELDS.map((field) => [
818
+ field,
819
+ source[field] === null || source[field] === undefined ? '' : String(source[field]),
820
+ ]))
821
+ }
822
+
823
+ function toDraft(models) {
824
+ return models.map((model) => ({
825
+ provider: model.provider,
826
+ providerName: model.providerName,
827
+ model: model.model,
828
+ name: model.name,
829
+ isDeepSeek: model.isDeepSeek,
830
+ pricing: toDraftPricing(model.pricing),
831
+ }))
832
+ }
833
+
834
+ function toDraftArchive(entries) {
835
+ return (entries ?? []).map((entry) => ({
836
+ provider: entry.provider,
837
+ model: entry.model,
838
+ pricing: toDraftPricing(entry.pricing),
839
+ }))
840
+ }
841
+
842
+ function parsePriceInput(value) {
843
+ if (typeof value === 'string' && value.trim() === '') return null
844
+ const number = Number(value)
845
+ if (!Number.isFinite(number) || number < 0 || number > 1e12) return undefined
846
+ return Math.round(number * 1e8) / 1e8
847
+ }
848
+
849
+ function SettingsSection() {
850
+ const translate = useT()
851
+ const snap = useCatalog()
852
+ const [draft, setDraft] = useState(null)
853
+ const [archive, setArchive] = useState(null)
854
+ const [display, setDisplay] = useState(null)
855
+ const [dirty, setDirty] = useState(false)
856
+ const [saving, setSaving] = useState(false)
857
+ const [status, setStatus] = useState(null)
858
+
859
+ useEffect(() => {
860
+ if (snap.data === null) return
861
+ setDraft(toDraft(snap.data.models))
862
+ setArchive(toDraftArchive(snap.data.pricingArchive))
863
+ setDisplay(readDisplay(snap.data))
864
+ setDirty(false)
865
+ }, [snap.data])
866
+
867
+ const models = draft ?? []
868
+ const archiveRows = archive ?? []
869
+ const update = (index, change) => {
870
+ setDraft((current) => current === null ? current : current.map((entry, at) => at === index ? change(entry) : entry))
871
+ setDirty(true)
872
+ setStatus(null)
873
+ }
874
+
875
+ const updatePrice = (index, field, value) => {
876
+ update(index, (entry) => ({
877
+ ...entry,
878
+ pricing: { ...entry.pricing, [field]: value },
879
+ }))
880
+ }
881
+
882
+ // "Custom prices" starts from blank fields; the user opts in explicitly.
883
+ const resetPricing = (index) => {
884
+ update(index, (entry) => ({
885
+ ...entry,
886
+ pricing: { cacheHit: '', cacheMiss: '', output: '' },
887
+ }))
888
+ }
889
+
890
+ // "Restore official prices" puts the built-in peak/off-peak card back
891
+ // immediately, so the user sees the official table before saving.
892
+ const restoreOfficialPricing = (index) => {
893
+ const entry = models[index]
894
+ if (entry === undefined) return
895
+ const catalogRow = (snap.data?.models ?? []).find((row) =>
896
+ row.provider === entry.provider && row.model === entry.model)
897
+ const official = catalogRow?.pricing?.official
898
+ ?? (catalogRow?.pricing?.builtin === true ? catalogRow.pricing : null)
899
+ const restored = official?.builtin === true
900
+ ? toDraftPricing(official)
901
+ : { cacheHit: '', cacheMiss: '', output: '' }
902
+ update(index, (current) => ({ ...current, pricing: restored }))
903
+ }
904
+
905
+ const move = (index, delta) => {
906
+ const target = index + delta
907
+ if (target < 0 || target >= models.length) return
908
+ setDraft((current) => {
909
+ if (current === null) return current
910
+ const next = [...current]
911
+ const [item] = next.splice(index, 1)
912
+ next.splice(target, 0, item)
913
+ return next
914
+ })
915
+ setDirty(true)
916
+ setStatus(null)
917
+ }
918
+
919
+ const updateArchive = (index, change) => {
920
+ setArchive((current) => current === null ? current : current.map((entry, at) => at === index ? change(entry) : entry))
921
+ setDirty(true)
922
+ setStatus(null)
923
+ }
924
+
925
+ const updateArchivePrice = (index, field, value) => {
926
+ updateArchive(index, (entry) => ({ ...entry, pricing: { ...entry.pricing, [field]: value } }))
927
+ }
928
+
929
+ const addArchive = () => {
930
+ setArchive((current) => [...(current ?? []), { provider: '', model: '', pricing: { cacheHit: '', cacheMiss: '', output: '' } }])
931
+ setDirty(true)
932
+ setStatus(null)
933
+ }
934
+
935
+ const removeArchive = (index) => {
936
+ setArchive((current) => current === null ? current : current.filter((entry, at) => at !== index))
937
+ setDirty(true)
938
+ setStatus(null)
939
+ }
940
+
941
+ const reset = () => {
942
+ emitCatalog()
943
+ if (snap.data !== null) {
944
+ setDraft(toDraft(snap.data.models))
945
+ setArchive(toDraftArchive(snap.data.pricingArchive))
946
+ setDisplay(readDisplay(snap.data))
947
+ }
948
+ setDirty(false)
949
+ setStatus(null)
950
+ }
951
+
952
+ const displayValue = display ?? readDisplay(snap.data)
953
+
954
+ const updateDisplay = (change) => {
955
+ setDisplay((current) => ({ ...(current ?? readDisplay(snap.data)), ...change }))
956
+ setDirty(true)
957
+ setStatus(null)
958
+ }
959
+
960
+ const masterToggle = (field, label, hint) => h('label', { className: 'mb-master' },
961
+ h('input', {
962
+ type: 'checkbox',
963
+ checked: displayValue[field] === true,
964
+ onChange: (event) => updateDisplay({ [field]: event.target.checked }),
965
+ }),
966
+ h('span', { className: 'mb-master-label' }, translate(label)),
967
+ hint === undefined ? null : h('span', { className: 'mb-master-hint' }, hint))
968
+
969
+ const renderDisplaySettings = () => h(Fragment, null,
970
+ h('div', { className: 'mb-display' },
971
+ h('div', { className: 'mb-display-head' },
972
+ h('div', { className: 'mb-display-title' }, translate('displaySection')),
973
+ h('div', { className: 'mb-display-hint' }, translate('displayHint'))),
974
+ masterToggle('showTurnTail', 'displayTurnTail'),
975
+ h('div', { className: 'mb-check-grid mb-subchecks' },
976
+ [
977
+ ['showProvider', 'displayProvider'],
978
+ ['showModels', 'displayModels'],
979
+ ['showCost', 'displayCost'],
980
+ ['showTokens', 'displayTokens'],
981
+ ['showCacheHit', 'displayCacheHit'],
982
+ ['showLabels', 'displayLabels'],
983
+ ].map(([field, label]) => {
984
+ const disabled = displayValue.showTurnTail !== true ||
985
+ (field === 'showProvider' && displayValue.showModels !== true)
986
+ return h('label', {
987
+ className: `mb-check${disabled ? ' is-disabled' : ''}`,
988
+ key: field,
989
+ },
990
+ h('input', {
991
+ type: 'checkbox',
992
+ checked: displayValue[field] === true,
993
+ disabled,
994
+ onChange: (event) => updateDisplay({ [field]: event.target.checked }),
995
+ }),
996
+ h('span', null, translate(label)))
997
+ })),
998
+ h('div', { className: 'mb-display-controls' },
999
+ h('label', { className: 'mb-field' },
1000
+ h('span', { className: 'mb-field-label' }, translate('displayFontSize')),
1001
+ h('select', {
1002
+ className: 'mb-select',
1003
+ value: displayValue.fontSize,
1004
+ onChange: (event) => updateDisplay({ fontSize: event.target.value }),
1005
+ },
1006
+ h('option', { value: 'small' }, translate('fontSizeSmall')),
1007
+ h('option', { value: 'normal' }, translate('fontSizeNormal')),
1008
+ h('option', { value: 'large' }, translate('fontSizeLarge')))),
1009
+ h('label', { className: 'mb-field' },
1010
+ h('span', { className: 'mb-field-label' }, translate('displayDensity')),
1011
+ h('select', {
1012
+ className: 'mb-select',
1013
+ value: displayValue.density,
1014
+ onChange: (event) => updateDisplay({ density: event.target.value }),
1015
+ },
1016
+ h('option', { value: 'compact' }, translate('densityCompact')),
1017
+ h('option', { value: 'comfortable' }, translate('densityComfortable')))),
1018
+ h('label', { className: 'mb-field' },
1019
+ h('span', { className: 'mb-field-label' }, translate('displayWeight')),
1020
+ h('select', {
1021
+ className: 'mb-select',
1022
+ value: displayValue.fontWeight,
1023
+ onChange: (event) => updateDisplay({ fontWeight: event.target.value }),
1024
+ },
1025
+ h('option', { value: 'normal' }, translate('weightNormal')),
1026
+ h('option', { value: 'bold' }, translate('weightBold')))))),
1027
+ h('div', { className: 'mb-display' },
1028
+ h('div', { className: 'mb-display-head' },
1029
+ h('div', { className: 'mb-display-title' }, translate('dockSection')),
1030
+ h('div', { className: 'mb-display-hint' }, translate('dockHint'))),
1031
+ masterToggle('showDock', 'displayDock'),
1032
+ h('div', { className: 'mb-check-grid mb-subchecks' },
1033
+ h('label', { className: `mb-check${displayValue.showDock === true ? '' : ' is-disabled'}` },
1034
+ h('input', {
1035
+ type: 'checkbox',
1036
+ checked: displayValue.showUnpricedNotice === true,
1037
+ disabled: displayValue.showDock !== true,
1038
+ onChange: (event) => updateDisplay({ showUnpricedNotice: event.target.checked }),
1039
+ }),
1040
+ h('span', null, translate('showUnpricedNotice'))))),
1041
+ h('div', { className: 'mb-display' },
1042
+ h('div', { className: 'mb-display-head' },
1043
+ h('div', { className: 'mb-display-title' }, translate('pickerSection')),
1044
+ h('div', { className: 'mb-display-hint' }, translate('takeoverHint'))),
1045
+ h('label', { className: 'mb-check' },
1046
+ h('input', {
1047
+ type: 'checkbox',
1048
+ checked: displayValue.takeoverPicker === true,
1049
+ onChange: (event) => updateDisplay({ takeoverPicker: event.target.checked }),
1050
+ }),
1051
+ h('span', null, translate('takeoverPicker')))))
1052
+
1053
+ const renderArchive = () => h('div', { className: 'mb-display' },
1054
+ h('div', { className: 'mb-display-head' },
1055
+ h('div', { className: 'mb-display-title' }, translate('archiveSection')),
1056
+ h('div', { className: 'mb-display-hint' }, translate('archiveHint'))),
1057
+ archiveRows.length === 0
1058
+ ? h('div', { className: 'mb-muted' }, translate('archiveEmpty'))
1059
+ : h('div', { className: 'mb-archive-list' },
1060
+ archiveRows.map((entry, index) => h('div', { className: 'mb-archive-row', key: index },
1061
+ h('input', {
1062
+ className: 'mb-input mb-archive-provider',
1063
+ placeholder: translate('archiveProvider'),
1064
+ value: entry.provider,
1065
+ onChange: (event) => updateArchive(index, (current) => ({ ...current, provider: event.target.value })),
1066
+ }),
1067
+ h('input', {
1068
+ className: 'mb-input mb-archive-model',
1069
+ placeholder: translate('archiveModel'),
1070
+ value: entry.model,
1071
+ onChange: (event) => updateArchive(index, (current) => ({ ...current, model: event.target.value })),
1072
+ }),
1073
+ ...PRICE_FIELDS.map((field) => h('input', {
1074
+ key: field,
1075
+ className: 'mb-input mb-archive-price',
1076
+ inputMode: 'decimal',
1077
+ placeholder: translate(PRICE_LABEL_KEYS[field]),
1078
+ 'aria-label': translate(PRICE_LABEL_KEYS[field]),
1079
+ value: entry.pricing[field] ?? '',
1080
+ onChange: (event) => updateArchivePrice(index, field, event.target.value),
1081
+ })),
1082
+ h('button', {
1083
+ type: 'button',
1084
+ className: 'mb-btn',
1085
+ title: translate('remove'),
1086
+ 'aria-label': translate('remove'),
1087
+ onClick: () => removeArchive(index),
1088
+ }, translate('remove'))))),
1089
+ h('div', { className: 'mb-archive-actions' },
1090
+ h('button', { type: 'button', className: 'mb-btn', onClick: addArchive }, translate('addArchive'))))
1091
+
1092
+ const save = async () => {
1093
+ if (draft === null) return
1094
+ const payload = []
1095
+ for (const entry of draft) {
1096
+ if (entry.pricing.builtin === true) {
1097
+ payload.push({ provider: entry.provider, model: entry.model, pricing: {} })
1098
+ continue
1099
+ }
1100
+ const pricing = {}
1101
+ const blank = PRICE_FIELDS.every((field) => String(entry.pricing[field] ?? '').trim() === '')
1102
+ if (blank) {
1103
+ // Three blank fields mean "drop the override", so the official table applies again.
1104
+ payload.push({ provider: entry.provider, model: entry.model, pricing: {} })
1105
+ continue
1106
+ }
1107
+ for (const field of PRICE_FIELDS) {
1108
+ const parsed = parsePriceInput(entry.pricing[field])
1109
+ if (parsed === undefined) {
1110
+ setStatus({ tone: 'error', text: translate('invalidPrice') })
1111
+ return
1112
+ }
1113
+ pricing[field] = parsed
1114
+ }
1115
+ payload.push({ provider: entry.provider, model: entry.model, pricing })
1116
+ }
1117
+ const archivePayload = []
1118
+ const currentKeys = new Set(draft.map((entry) => `${entry.provider}\u0000${entry.model}`))
1119
+ for (const entry of archiveRows) {
1120
+ const provider = entry.provider.trim()
1121
+ const model = entry.model.trim()
1122
+ if (provider === '' && model === '') continue
1123
+ if (provider === '' || model === '') {
1124
+ setStatus({ tone: 'error', text: translate('invalidRoute') })
1125
+ return
1126
+ }
1127
+ if (currentKeys.has(`${provider}\u0000${model}`)) {
1128
+ setStatus({ tone: 'error', text: translate('archiveConflict') })
1129
+ return
1130
+ }
1131
+ const pricing = {}
1132
+ const blank = PRICE_FIELDS.every((field) => String(entry.pricing[field] ?? '').trim() === '')
1133
+ if (blank) {
1134
+ archivePayload.push({ provider, model, pricing: {} })
1135
+ continue
1136
+ }
1137
+ for (const field of PRICE_FIELDS) {
1138
+ const parsed = parsePriceInput(entry.pricing[field])
1139
+ if (parsed === undefined) {
1140
+ setStatus({ tone: 'error', text: translate('invalidPrice') })
1141
+ return
1142
+ }
1143
+ pricing[field] = parsed
1144
+ }
1145
+ archivePayload.push({ provider, model, pricing })
1146
+ }
1147
+ setSaving(true)
1148
+ setStatus(null)
1149
+ try {
1150
+ await requestJson('/model-billing/save', {
1151
+ method: 'POST',
1152
+ headers: { 'content-type': 'application/json' },
1153
+ body: JSON.stringify({ models: payload, pricingArchive: archivePayload, display: displayValue }),
1154
+ })
1155
+ setDirty(false)
1156
+ setStatus({ tone: 'success', text: translate('saved') })
1157
+ await ensureCatalog(true)
1158
+ } catch (error) {
1159
+ setStatus({ tone: 'error', text: translate('saveFailed', { message: error instanceof Error ? error.message : String(error) }) })
1160
+ } finally {
1161
+ setSaving(false)
1162
+ }
1163
+ }
1164
+
1165
+ if (snap.data === null) {
1166
+ return h(Fragment, null,
1167
+ h(Style),
1168
+ h('section', { className: 'mb-page' },
1169
+ h('h2', { className: 'mb-title' }, translate('title')),
1170
+ snap.status === 'error'
1171
+ ? h('div', { className: 'mb-fatal' },
1172
+ h('div', null, translate('loadFailed')),
1173
+ h('p', { className: 'mb-note' }, snap.error),
1174
+ h('button', { type: 'button', className: 'mb-btn', onClick: () => void ensureCatalog(true) }, translate('retry')))
1175
+ : h('p', { className: 'mb-muted' }, translate('loading'))))
1176
+ }
1177
+
1178
+ if (draft === null) {
1179
+ return h(Fragment, null,
1180
+ h(Style),
1181
+ h('section', { className: 'mb-page' },
1182
+ h('h2', { className: 'mb-title' }, translate('title')),
1183
+ h('p', { className: 'mb-muted' }, translate('loading'))))
1184
+ }
1185
+
1186
+ const renderToolbar = () => h('div', { className: 'mb-toolbar' },
1187
+ h('span', { className: 'mb-muted' }, translate('modelsCount', { count: models.length })),
1188
+ h('span', { className: 'mb-spacer' }),
1189
+ dirty ? h('span', { className: 'mb-muted' }, translate('unsaved')) : null,
1190
+ h('button', { type: 'button', className: 'mb-btn', disabled: !dirty || saving, onClick: reset }, translate('undo')),
1191
+ h('button', { type: 'button', className: 'mb-btn mb-btn-primary', disabled: !dirty || saving, onClick: () => void save() }, saving ? translate('saving') : translate('save')))
1192
+
1193
+ if (models.length === 0) {
1194
+ // The display controls stay editable with no models configured, so the
1195
+ // toolbar (and its save button) must still render here.
1196
+ return h(Fragment, null,
1197
+ h(Style),
1198
+ h('section', { className: 'mb-page' },
1199
+ h('h2', { className: 'mb-title' }, translate('title')),
1200
+ h('p', { className: 'mb-intro' }, translate('intro')),
1201
+ renderToolbar(),
1202
+ status === null ? null : h('div', { className: 'mb-status', 'data-tone': status.tone, role: 'status' }, status.text),
1203
+ renderDisplaySettings(),
1204
+ renderArchive(),
1205
+ h('div', { className: 'mb-empty' }, translate('noModels'))))
1206
+ }
1207
+
1208
+ return h(Fragment, null,
1209
+ h(Style),
1210
+ h('section', { className: 'mb-page' },
1211
+ h('h2', { className: 'mb-title' }, translate('title')),
1212
+ h('p', { className: 'mb-intro' }, translate('intro')),
1213
+ renderToolbar(),
1214
+ status === null ? null : h('div', { className: 'mb-status', 'data-tone': status.tone, role: 'status' }, status.text),
1215
+ renderDisplaySettings(),
1216
+ h('p', { className: 'mb-note' }, translate('orderHint')),
1217
+ h('ul', { className: 'mb-list' },
1218
+ models.map((entry, index) => h(SettingsModelCard, {
1219
+ key: `${entry.provider}\u0000${entry.model}`,
1220
+ entry,
1221
+ index,
1222
+ count: models.length,
1223
+ translate,
1224
+ onMove: move,
1225
+ onUpdatePrice: updatePrice,
1226
+ onResetPricing: resetPricing,
1227
+ onRestoreOfficial: restoreOfficialPricing,
1228
+ }))),
1229
+ renderArchive(),
1230
+ h('p', { className: 'mb-footer-note' }, translate('formula')),
1231
+ h('p', { className: 'mb-footer-note' }, translate('formulaNote'))))
1232
+ }
1233
+
1234
+ function SettingsModelCard({ entry, index, count, translate, onMove, onUpdatePrice, onResetPricing, onRestoreOfficial }) {
1235
+ const id = useId()
1236
+ const pricing = entry.pricing
1237
+ const builtin = pricing.builtin === true
1238
+ const custom = entry.isDeepSeek && !builtin
1239
+ const fields = builtin ? null : PRICE_FIELDS.map((field) => {
1240
+ const inputId = `${id}-${field}`
1241
+ return h('label', { className: 'mb-field', htmlFor: inputId, key: field },
1242
+ h('span', { className: 'mb-field-label' }, translate(PRICE_LABEL_KEYS[field])),
1243
+ h('input', {
1244
+ id: inputId,
1245
+ className: 'mb-input',
1246
+ type: 'text',
1247
+ inputMode: 'decimal',
1248
+ autoComplete: 'off',
1249
+ placeholder: translate('pricePlaceholder'),
1250
+ value: pricing[field],
1251
+ onChange: (event) => onUpdatePrice(index, field, event.target.value),
1252
+ }))
1253
+ })
1254
+
1255
+ return h('li', { className: 'mb-card' },
1256
+ h('div', { className: 'mb-card-head' },
1257
+ h('div', { className: 'mb-index' }, index + 1),
1258
+ h('div', { style: { minWidth: 0 } },
1259
+ h('div', { className: 'mb-name' },
1260
+ entry.name,
1261
+ entry.isDeepSeek ? h('span', { className: 'mb-tag' }, translate('deepseekTag')) : null),
1262
+ h('div', { className: 'mb-sub' }, `${entry.providerName} · ${entry.provider} / ${entry.model}`)),
1263
+ h('div', { className: 'mb-head-actions' },
1264
+ h('button', {
1265
+ type: 'button',
1266
+ className: 'mb-btn mb-btn-icon',
1267
+ disabled: index === 0,
1268
+ title: translate('up'),
1269
+ 'aria-label': translate('up'),
1270
+ onClick: () => onMove(index, -1),
1271
+ }, '↑'),
1272
+ h('button', {
1273
+ type: 'button',
1274
+ className: 'mb-btn mb-btn-icon',
1275
+ disabled: index === count - 1,
1276
+ title: translate('down'),
1277
+ 'aria-label': translate('down'),
1278
+ onClick: () => onMove(index, 1),
1279
+ }, '↓'))),
1280
+ entry.isDeepSeek ? h('p', { className: 'mb-note' }, translate('deepseekNote')) : null,
1281
+ h('div', { className: 'mb-prices' },
1282
+ h('div', { className: 'mb-price-group' },
1283
+ h('div', { className: 'mb-price-group-title' },
1284
+ h('span', null, builtin ? translate('officialPrice') : translate('singlePrice')),
1285
+ custom ? h('span', { className: 'mb-tag' }, translate('priceSourceCustom')) : null,
1286
+ h('span', { className: 'mb-muted', style: { fontWeight: 400, fontSize: '11px' } }, translate('perMillion'))),
1287
+ builtin
1288
+ ? h(Fragment, null,
1289
+ h(PriceLines, { pricing, translate, showSource: false }),
1290
+ h('p', { className: 'mb-note' }, translate('deepseekSchedule')))
1291
+ : h(Fragment, null,
1292
+ h('div', { className: 'mb-price-grid' }, fields),
1293
+ custom ? h('p', { className: 'mb-note' }, translate('customPriceNote')) : null),
1294
+ entry.isDeepSeek
1295
+ ? h('div', { className: 'mb-card-actions' },
1296
+ h('button', {
1297
+ type: 'button',
1298
+ className: 'mb-btn',
1299
+ onClick: () => builtin ? onResetPricing(index) : onRestoreOfficial(index),
1300
+ }, builtin ? translate('customizePrice') : translate('useOfficialPrice')))
1301
+ : null)))
1302
+ }
1303
+
1304
+ // ---------------------------------------------------------------------
1305
+ // Composer dock cost summary
1306
+ // ---------------------------------------------------------------------
1307
+
1308
+ function CostDock({ sessionId, useProjection }) {
1309
+ const translate = useT()
1310
+ const tokenUsage = useProjection('tokenUsage')
1311
+ const revision = tokenUsageRevision(tokenUsage)
1312
+ const usage = useSessionUsage(sessionId, revision)
1313
+ const catalogSnap = useCatalog()
1314
+ const [open, setOpen] = useState(false)
1315
+ const [panelPos, setPanelPos] = useState(null)
1316
+ const [editingRoute, setEditingRoute] = useState(null)
1317
+ const [editPrices, setEditPrices] = useState({ cacheHit: '', cacheMiss: '', output: '' })
1318
+ const [savingPrice, setSavingPrice] = useState(false)
1319
+ const [priceStatus, setPriceStatus] = useState(null)
1320
+ const triggerRef = useRef(null)
1321
+ const panelRef = useRef(null)
1322
+
1323
+ useLayoutEffect(() => {
1324
+ if (!open) {
1325
+ setPanelPos(null)
1326
+ return undefined
1327
+ }
1328
+ const place = () => {
1329
+ const rect = triggerRef.current?.getBoundingClientRect()
1330
+ if (rect === undefined) return
1331
+ const width = Math.min(660, window.innerWidth - 24)
1332
+ const naturalLeft = Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))
1333
+ // The dock sits near the right edge; shift the whole detail panel left so
1334
+ // the bottom-right whale widget cannot cover it.
1335
+ const left = Math.max(12, naturalLeft - 120)
1336
+ const spaceAbove = rect.top - 12
1337
+ const spaceBelow = window.innerHeight - rect.bottom - 12
1338
+ const above = spaceAbove > spaceBelow
1339
+ const maxHeight = Math.min(430, Math.max(180, above ? spaceAbove : spaceBelow))
1340
+ setPanelPos(above
1341
+ ? { left, width, bottom: window.innerHeight - rect.top + 8, maxHeight }
1342
+ : { left, width, top: rect.bottom + 8, maxHeight })
1343
+ }
1344
+ place()
1345
+ window.addEventListener('resize', place)
1346
+ window.addEventListener('scroll', place, true)
1347
+ return () => {
1348
+ window.removeEventListener('resize', place)
1349
+ window.removeEventListener('scroll', place, true)
1350
+ }
1351
+ }, [open])
1352
+
1353
+ useEffect(() => {
1354
+ if (!open) return undefined
1355
+ const closeOutside = (event) => {
1356
+ if (triggerRef.current?.contains(event.target) === true) return
1357
+ if (panelRef.current?.contains(event.target) === true) return
1358
+ setOpen(false)
1359
+ }
1360
+ const closeOnEscape = (event) => {
1361
+ if (event.key !== 'Escape') return
1362
+ event.preventDefault()
1363
+ setOpen(false)
1364
+ triggerRef.current?.focus()
1365
+ }
1366
+ document.addEventListener('mousedown', closeOutside)
1367
+ document.addEventListener('keydown', closeOnEscape)
1368
+ // A dialog must take focus when it opens so keyboard users land inside it.
1369
+ panelRef.current?.focus()
1370
+ return () => {
1371
+ document.removeEventListener('mousedown', closeOutside)
1372
+ document.removeEventListener('keydown', closeOnEscape)
1373
+ }
1374
+ }, [open])
1375
+
1376
+ // Hooks must run on every render, so derive the catalog indexes before any
1377
+ // early return; React rejects a different hook count between renders.
1378
+ const orderIndex = useMemo(() =>
1379
+ new Map((catalogSnap.data?.models ?? []).map((model) => [`${model.provider}\u0000${model.model}`, model.order])),
1380
+ [catalogSnap.data])
1381
+ const catalogByKey = useMemo(() =>
1382
+ new Map((catalogSnap.data?.models ?? []).map((model) => [`${model.provider}\u0000${model.model}`, model])),
1383
+ [catalogSnap.data])
1384
+
1385
+ const display = readDisplay(catalogSnap.data)
1386
+ if (display.showDock === false) return null
1387
+
1388
+ const data = usage.data
1389
+ if (data === null || data === undefined || data.totals?.hasBillable !== true) {
1390
+ return null
1391
+ }
1392
+ const totals = data.totals
1393
+ const unpricedRoutes = data.unpricedRoutes ?? []
1394
+ const beginRouteEdit = (route) => {
1395
+ setEditingRoute(`${route.provider}\u0000${route.model}`)
1396
+ setEditPrices({ cacheHit: '', cacheMiss: '', output: '' })
1397
+ setPriceStatus(null)
1398
+ }
1399
+ const saveRoutePrice = async (route) => {
1400
+ const pricing = {}
1401
+ for (const field of PRICE_FIELDS) {
1402
+ const parsed = parsePriceInput(editPrices[field])
1403
+ if (parsed === undefined || parsed === null) {
1404
+ setPriceStatus({ tone: 'error', text: translate('invalidPrice') })
1405
+ return
1406
+ }
1407
+ pricing[field] = parsed
1408
+ }
1409
+ setSavingPrice(true)
1410
+ setPriceStatus(null)
1411
+ try {
1412
+ await requestJson('/model-billing/save', {
1413
+ method: 'POST',
1414
+ headers: { 'content-type': 'application/json' },
1415
+ body: JSON.stringify({ pricingArchive: [{ provider: route.provider, model: route.model, pricing }] }),
1416
+ })
1417
+ await ensureCatalog(true)
1418
+ setEditingRoute(null)
1419
+ setPriceStatus({ tone: 'success', text: translate('priceSaved') })
1420
+ await ensureUsage(sessionId, revision, true)
1421
+ } catch (error) {
1422
+ setPriceStatus({ tone: 'error', text: translate('saveFailed', { message: error instanceof Error ? error.message : String(error) }) })
1423
+ } finally {
1424
+ setSavingPrice(false)
1425
+ }
1426
+ }
1427
+ const last = [...(data.turns ?? [])].reverse().find((entry) => entry.hasBillable) ?? null
1428
+ const totalText = totals.costKnown
1429
+ ? `≈ ${formatMoney(totals.cost)}`
1430
+ : totals.pricedAttempts > 0 ? `≈ ${formatMoney(totals.cost)}` : translate('pricePlaceholder')
1431
+ const lastText = last === null || last === undefined || !last.hasBillable
1432
+ ? null
1433
+ : last.costKnown ? `≈ ${formatMoney(last.cost)}` : last.pricedAttempts > 0 ? `≈ ${formatMoney(last.cost)}` : translate('pricePlaceholder')
1434
+ // Rebuilding the index and scanning the catalog on every render gets
1435
+ // expensive on a long session, so both indexes are memoized above.
1436
+ const byModel = [...(data.byModel ?? [])].sort((left, right) => {
1437
+ const leftKey = left.provider === null ? '' : `${left.provider}\u0000${left.model}`
1438
+ const rightKey = right.provider === null ? '' : `${right.provider}\u0000${right.model}`
1439
+ return (orderIndex.get(leftKey) ?? Number.MAX_SAFE_INTEGER) - (orderIndex.get(rightKey) ?? Number.MAX_SAFE_INTEGER)
1440
+ })
1441
+
1442
+ const modelNameOf = (model) => {
1443
+ const catalogRow = model?.provider === null || model?.provider === undefined
1444
+ ? undefined
1445
+ : catalogByKey.get(`${model.provider}\u0000${model.model}`)
1446
+ return catalogRow?.name ?? model?.name ?? model?.model ?? '—'
1447
+ }
1448
+ const turnModelNames = (turn) => {
1449
+ const names = []
1450
+ for (const model of turn.models ?? []) {
1451
+ const name = modelNameOf(model)
1452
+ if (!names.includes(name)) names.push(name)
1453
+ }
1454
+ return names
1455
+ }
1456
+
1457
+ const header = h('thead', null,
1458
+ h('tr', null,
1459
+ h('th', null, translate('turn')),
1460
+ h('th', null, translate('content')),
1461
+ h('th', null, translate('time')),
1462
+ h('th', null, translate('model')),
1463
+ h('th', { className: 'num' }, translate('cost')),
1464
+ h('th', { className: 'num' }, translate('tokens')),
1465
+ h('th', { className: 'num' }, translate('cacheHit'))))
1466
+
1467
+ const turnRows = [...(data.turns ?? [])].reverse().slice(0, 20).map((turn) => {
1468
+ const costText = turn.costKnown
1469
+ ? `≈ ${formatMoney(turn.cost)}`
1470
+ : turn.pricedAttempts > 0 ? `≈ ${formatMoney(turn.cost)}` : translate('pricePlaceholder')
1471
+ const modelNames = turnModelNames(turn)
1472
+ const modelText = modelNames.length === 0
1473
+ ? '—'
1474
+ : modelNames.length === 1 ? modelNames[0] : `${modelNames[0]} +${modelNames.length - 1}`
1475
+ return h('tr', { key: turn.turn },
1476
+ h('td', null, `#${turn.turn}`),
1477
+ h('td', { className: 'mb-turn-preview', title: turn.preview }, turn.preview || '—'),
1478
+ h('td', null, `${timeText(turn.startTime)}–${timeText(turn.endTime)}`),
1479
+ h('td', { className: 'mb-turn-model', title: modelNames.join(' / ') }, modelText),
1480
+ h('td', { className: 'num' }, costText),
1481
+ h('td', { className: 'num' }, `${formatTokens(turn.promptTokens)} / ${formatTokens(turn.outputTokens)}`),
1482
+ h('td', { className: 'num' }, formatPercent(turn.cacheHit)))
1483
+ })
1484
+
1485
+ const turnTable = h('div', { style: { overflowX: 'auto' } },
1486
+ h('table', { className: 'mb-table mb-turn-table' }, header, h('tbody', null, turnRows)))
1487
+
1488
+ const modelRows = byModel.map((model) => {
1489
+ const catalogRow = model.provider === null
1490
+ ? undefined
1491
+ : catalogByKey.get(`${model.provider}\u0000${model.model}`)
1492
+ const modelName = catalogRow === undefined ? model.name : `${catalogRow.providerName} / ${catalogRow.name}`
1493
+ return h('tr', { key: `${model.provider}\u0000${model.model}\u0000${model.name}` },
1494
+ h('td', null,
1495
+ modelName,
1496
+ model.isDeepSeek ? h('span', { className: 'mb-tag' }, translate('deepseekTag')) : null),
1497
+ h('td', { className: 'num' },
1498
+ model.pricedAttempts > 0 ? `≈ ${formatMoney(model.cost)}` : translate('pricePlaceholder')),
1499
+ h('td', { className: 'num', style: { color: 'var(--dsw-alias-label-secondary)' } },
1500
+ `${formatTokens(model.promptTokens)} / ${formatTokens(model.outputTokens)}`))
1501
+ })
1502
+
1503
+ const modelTable = byModel.length === 0
1504
+ ? null
1505
+ : h('div', { style: { marginTop: '10px' } },
1506
+ h('div', { className: 'mb-panel-title', style: { fontSize: '12px', marginBottom: '4px' } }, translate('byModel')),
1507
+ h('div', { style: { overflowX: 'auto' } },
1508
+ h('table', { className: 'mb-table' }, h('tbody', null, modelRows))))
1509
+
1510
+ const editingRouteRow = editingRoute === null
1511
+ ? null
1512
+ : unpricedRoutes.find((route) => `${route.provider}\u0000${route.model}` === editingRoute) ?? null
1513
+ const routeEditor = editingRouteRow === null
1514
+ ? null
1515
+ : h('div', { className: 'mb-archive-row mb-route-editor', style: { marginTop: '8px' } },
1516
+ h('span', { className: 'mb-muted' }, `${editingRouteRow.provider} / ${editingRouteRow.model}`),
1517
+ ...PRICE_FIELDS.map((field) => h('input', {
1518
+ key: field,
1519
+ className: 'mb-input',
1520
+ inputMode: 'decimal',
1521
+ placeholder: translate(PRICE_LABEL_KEYS[field]),
1522
+ 'aria-label': translate(PRICE_LABEL_KEYS[field]),
1523
+ value: editPrices[field],
1524
+ onChange: (event) => setEditPrices((current) => ({ ...current, [field]: event.target.value })),
1525
+ })),
1526
+ h('button', {
1527
+ type: 'button',
1528
+ className: 'mb-btn mb-btn-primary',
1529
+ disabled: savingPrice,
1530
+ onClick: () => void saveRoutePrice(editingRouteRow),
1531
+ }, savingPrice ? translate('saving') : translate('save')))
1532
+
1533
+ const unpricedTable = unpricedRoutes.length === 0 || display.showUnpricedNotice === false
1534
+ ? null
1535
+ : h('div', { style: { marginTop: '10px' } },
1536
+ h('div', { className: 'mb-panel-title', style: { fontSize: '12px', marginBottom: '4px' } }, translate('unpricedRoutes')),
1537
+ h('div', { style: { overflowX: 'auto' } },
1538
+ h('table', { className: 'mb-table' },
1539
+ h('tbody', null, unpricedRoutes.map((route) => h('tr', { key: `${route.provider}\u0000${route.model}` },
1540
+ h('td', null, `${route.provider} / ${route.model}`),
1541
+ h('td', { className: 'num' }, String(route.attempts)),
1542
+ h('td', { className: 'num', style: { color: 'var(--dsw-alias-label-secondary)' } },
1543
+ `${formatTokens(route.promptTokens)} / ${formatTokens(route.outputTokens)}`),
1544
+ h('td', { className: 'num' },
1545
+ h('button', {
1546
+ type: 'button',
1547
+ className: 'mb-btn',
1548
+ onClick: () => beginRouteEdit(route),
1549
+ }, translate('addPrice')))))))),
1550
+ routeEditor,
1551
+ priceStatus === null ? null : h('div', { className: 'mb-status', 'data-tone': priceStatus.tone, role: 'status' }, priceStatus.text))
1552
+
1553
+ const panelStyle = panelPos === null
1554
+ ? { left: 0, top: 0, width: 660, visibility: 'hidden' }
1555
+ : {
1556
+ left: panelPos.left,
1557
+ width: panelPos.width,
1558
+ maxHeight: panelPos.maxHeight,
1559
+ ...panelPos.top === undefined ? { bottom: panelPos.bottom } : { top: panelPos.top },
1560
+ }
1561
+
1562
+ const panel = h('div', {
1563
+ ref: panelRef,
1564
+ className: 'mb-panel mb-panel-floating',
1565
+ style: panelStyle,
1566
+ role: 'dialog',
1567
+ 'aria-modal': true,
1568
+ 'aria-label': translate('costDetails'),
1569
+ tabIndex: -1,
1570
+ },
1571
+ h('div', { className: 'mb-panel-head' },
1572
+ h('span', { className: 'mb-panel-title' }, translate('costDetails')),
1573
+ h('span', { className: 'mb-muted' }, translate('sessionTotal')),
1574
+ usage.status === 'error'
1575
+ ? h('button', {
1576
+ type: 'button',
1577
+ className: 'mb-btn',
1578
+ onClick: () => void ensureUsage(sessionId, revision, true),
1579
+ }, translate('retry'))
1580
+ : null,
1581
+ h('button', {
1582
+ type: 'button',
1583
+ className: 'mb-panel-close',
1584
+ 'aria-label': translate('close'),
1585
+ title: translate('close'),
1586
+ onClick: () => {
1587
+ setOpen(false)
1588
+ triggerRef.current?.focus()
1589
+ },
1590
+ }, '×')),
1591
+ h('div', { className: 'mb-summary' },
1592
+ summaryItem(translate('sessionTotal'), totalText),
1593
+ summaryItem(translate('thisTurn'), lastText ?? '—'),
1594
+ summaryItem(translate('cacheHit'), formatPercent(totals.cacheHit)),
1595
+ summaryItem(translate('tokens'), `${formatTokens(totals.promptTokens)} / ${formatTokens(totals.outputTokens)}`)),
1596
+ turnTable,
1597
+ modelTable,
1598
+ unpricedTable,
1599
+ h('p', { className: 'mb-panel-note' }, translate('estimateNote')),
1600
+ totals.toolCost > 0
1601
+ ? h('p', { className: 'mb-panel-note' }, translate('webToolNote', {
1602
+ amount: formatMoney(totals.toolCost),
1603
+ searchBilled: totals.webSearchBilled ?? 0,
1604
+ searchCalls: totals.webSearchCalls ?? 0,
1605
+ fetchBilled: totals.webFetchBilled ?? 0,
1606
+ fetchCalls: totals.webFetchCalls ?? 0,
1607
+ }))
1608
+ : null,
1609
+ totals.partial && display.showUnpricedNotice
1610
+ ? h('p', { className: 'mb-warn' }, translate('partialNote'))
1611
+ : null)
1612
+
1613
+ return h('div', { className: 'mb-dock' },
1614
+ h(Style),
1615
+ h('button', {
1616
+ ref: triggerRef,
1617
+ type: 'button',
1618
+ className: 'mb-dock-trigger',
1619
+ 'aria-expanded': open ? 'true' : 'false',
1620
+ 'aria-haspopup': 'dialog',
1621
+ onClick: () => setOpen((value) => !value),
1622
+ title: translate('costEstimate'),
1623
+ },
1624
+ h('svg', {
1625
+ className: 'mb-dock-icon',
1626
+ viewBox: '0 0 16 16',
1627
+ fill: 'none',
1628
+ stroke: 'currentColor',
1629
+ strokeWidth: 1.2,
1630
+ 'aria-hidden': true,
1631
+ },
1632
+ h('circle', { cx: 8, cy: 8, r: 5.5 }),
1633
+ h('path', { d: 'M8 5v6M6.2 6.8h3.6M6.2 9.2h3.6' })),
1634
+ h('span', null, translate('costEstimate')),
1635
+ h('span', { className: 'mb-dock-amount' }, totalText),
1636
+ lastText === null ? null : h(Fragment, null,
1637
+ h('span', { className: 'mb-dock-sep' }, '·'),
1638
+ h('span', null, `${translate('thisTurn')} ${lastText}`)),
1639
+ totals.partial && display.showUnpricedNotice ? h('span', { className: 'mb-warn', style: { margin: 0 } }, translate('partial')) : null),
1640
+ open ? ReactDOM.createPortal(panel, document.body) : null)
1641
+ }
1642
+
1643
+ function summaryItem(label, value) {
1644
+ return h('div', { className: 'mb-summary-item', key: label },
1645
+ h('div', { className: 'mb-summary-key' }, label),
1646
+ h('div', { className: 'mb-summary-value' }, value))
1647
+ }
1648
+
1649
+ // ---------------------------------------------------------------------
1650
+ // Per-turn cost chip
1651
+ // ---------------------------------------------------------------------
1652
+
1653
+ function turnModelText(models, translate, showProvider, catalogModels) {
1654
+ const findModel = (entry) => {
1655
+ if (entry.provider === undefined || entry.model === undefined) return undefined
1656
+ return (catalogModels ?? []).find((candidate) => candidate.provider === entry.provider && candidate.model === entry.model)
1657
+ }
1658
+ const names = (models ?? []).map((entry) => {
1659
+ if (entry === undefined || entry === null) return null
1660
+ const matched = findModel(entry)
1661
+ const modelName = typeof matched?.name === 'string' && matched.name !== ''
1662
+ ? matched.name
1663
+ : typeof entry.name === 'string' && entry.name !== ''
1664
+ ? entry.name
1665
+ : typeof entry.model === 'string' && entry.model !== '' ? entry.model : null
1666
+ if (modelName === null) return null
1667
+ if (!showProvider) return modelName
1668
+ const providerName = typeof matched?.providerName === 'string' && matched.providerName !== ''
1669
+ ? matched.providerName
1670
+ : typeof entry.providerName === 'string' && entry.providerName !== ''
1671
+ ? entry.providerName
1672
+ : typeof entry.provider === 'string' && entry.provider !== '' ? entry.provider : null
1673
+ return providerName === null ? modelName : `${providerName} / ${modelName}`
1674
+ }).filter((name) => name !== null)
1675
+ if (names.length === 0) return null
1676
+ return names.join(translate('listSep'))
1677
+ }
1678
+
1679
+ function TurnCost(props) {
1680
+ const { turn } = props
1681
+ // The turnTail owner hands over the whole folded turn life cycle, not just its number.
1682
+ const turnNumber = turn === null || turn === undefined
1683
+ ? undefined
1684
+ : typeof turn === 'number' ? turn : turn.turn
1685
+ const sessionId = props.sessionId
1686
+ const useProjection = props.useProjection
1687
+ const translate = useT()
1688
+ const catalogSnap = useCatalog()
1689
+ const display = readDisplay(catalogSnap.data)
1690
+ const tokenUsage = typeof useProjection === 'function' ? useProjection('tokenUsage') : undefined
1691
+ const revision = tokenUsageRevision(tokenUsage)
1692
+ const usage = useSessionUsage(sessionId, revision)
1693
+ // The master switch hides the whole chip while the per-field switches keep
1694
+ // their saved values, so turning it back on restores the previous layout.
1695
+ if (display.showTurnTail === false) return null
1696
+ const rows = usage.data?.turns
1697
+ const row = (usage.rowsByTurn instanceof Map ? usage.rowsByTurn.get(turnNumber) : undefined) ??
1698
+ rows?.find((entry) => entry.turn === turnNumber)
1699
+ if (row === undefined) return null
1700
+ const costText = row.costKnown
1701
+ ? `≈ ${formatMoney(row.cost)}`
1702
+ : row.pricedAttempts > 0 ? `≈ ${formatMoney(row.cost)}` : translate('pricePlaceholder')
1703
+ const modelText = turnModelText(row.models, translate, display.showProvider === true, catalogSnap.data?.models)
1704
+ const label = (key) => display.showLabels ? `${translate(key)} ` : ''
1705
+ const parts = []
1706
+ if (display.showModels && modelText !== null) {
1707
+ parts.push(h('span', { className: 'mb-turn-item', key: 'model' },
1708
+ label('model'), h('strong', null, modelText)))
1709
+ }
1710
+ if (display.showCost) {
1711
+ parts.push(h('span', { className: 'mb-turn-item', key: 'cost' },
1712
+ label('turnCost'), h('strong', null, costText)))
1713
+ }
1714
+ const promptTokens = Number.isFinite(row.promptTokens) ? row.promptTokens : 0
1715
+ const outputTokens = Number.isFinite(row.outputTokens) ? row.outputTokens : 0
1716
+ if (display.showTokens && (promptTokens > 0 || outputTokens > 0)) {
1717
+ parts.push(h('span', { className: 'mb-turn-item', key: 'tokens' },
1718
+ label('turnTokens'), h('strong', null, `${formatTokens(promptTokens)} / ${formatTokens(outputTokens)}`)))
1719
+ }
1720
+ if (display.showCacheHit && row.cacheHit !== null && row.cacheHit !== undefined) {
1721
+ parts.push(h('span', { className: 'mb-turn-item', key: 'cache' },
1722
+ label('cacheHit'), h('strong', null, formatPercent(row.cacheHit))))
1723
+ }
1724
+ if (row.partial) {
1725
+ parts.push(h('span', { className: 'mb-turn-item mb-turn-partial', key: 'partial' }, translate('partialShort')))
1726
+ }
1727
+ if (parts.length === 0) return null
1728
+ return h('span', {
1729
+ className: 'mb-turn',
1730
+ 'data-size': display.fontSize,
1731
+ 'data-density': display.density,
1732
+ 'data-weight': display.fontWeight,
1733
+ }, parts)
1734
+ }
1735
+
1736
+ // ---------------------------------------------------------------------
1737
+ // Custom-ordered model picker in the composer seat
1738
+ // ---------------------------------------------------------------------
1739
+
1740
+ const MODEL_KEY_SEPARATOR = '\u0000'
1741
+
1742
+ function OrderedModelPicker({ locked, sessionId, useProjection }) {
1743
+ const translate = useT()
1744
+ const catalogSnap = useCatalog()
1745
+ const selectionProjection = useProjection('modelSelection')
1746
+ const directoryRevision = useModelDirectoriesRevision()
1747
+ const [directoryTick, setDirectoryTick] = useState(0)
1748
+ const directory = useMemo(() => {
1749
+ if (modelDirectories === undefined || sessionId === undefined) return null
1750
+ try {
1751
+ return modelDirectories.directoryFor(sessionId)
1752
+ } catch {
1753
+ return null
1754
+ }
1755
+ }, [sessionId, directoryRevision, directoryTick])
1756
+
1757
+ const [state, setState] = useState(null)
1758
+ const [open, setOpen] = useState(false)
1759
+ const [query, setQuery] = useState('')
1760
+ const [selecting, setSelecting] = useState(false)
1761
+ const [failure, setFailure] = useState(null)
1762
+ const [menuPos, setMenuPos] = useState(null)
1763
+ // Roving cursor for arrow-key navigation inside the model list.
1764
+ const [activeIndex, setActiveIndex] = useState(0)
1765
+ const rootRef = useRef(null)
1766
+ const triggerRef = useRef(null)
1767
+ const menuRef = useRef(null)
1768
+ const searchRef = useRef(null)
1769
+ const id = useId()
1770
+
1771
+ useEffect(() => {
1772
+ if (directory === null) {
1773
+ setState(null)
1774
+ return undefined
1775
+ }
1776
+ const sync = () => setState(directory.store.getSnapshot())
1777
+ sync()
1778
+ const unsubscribe = directory.store.subscribe(sync)
1779
+ directory.load().catch(() => {})
1780
+ return unsubscribe
1781
+ }, [directory])
1782
+
1783
+ useEffect(() => {
1784
+ if (directory !== null || directoryTick >= 20) return undefined
1785
+ const timer = setTimeout(() => setDirectoryTick((value) => value + 1), 300)
1786
+ return () => clearTimeout(timer)
1787
+ }, [directory, directoryTick])
1788
+
1789
+ useEffect(() => {
1790
+ if (!open) return undefined
1791
+ const closeOutside = (event) => {
1792
+ if (rootRef.current?.contains(event.target) === true) return
1793
+ if (menuRef.current?.contains(event.target) === true) return
1794
+ setOpen(false)
1795
+ }
1796
+ document.addEventListener('mousedown', closeOutside)
1797
+ return () => document.removeEventListener('mousedown', closeOutside)
1798
+ }, [open])
1799
+
1800
+ useEffect(() => {
1801
+ if (!open) {
1802
+ setQuery('')
1803
+ return undefined
1804
+ }
1805
+ const closeOnEscape = (event) => {
1806
+ if (event.key !== 'Escape') return
1807
+ event.preventDefault()
1808
+ setOpen(false)
1809
+ queueMicrotask(() => triggerRef.current?.focus())
1810
+ }
1811
+ document.addEventListener('keydown', closeOnEscape)
1812
+ return () => document.removeEventListener('keydown', closeOnEscape)
1813
+ }, [open])
1814
+
1815
+ useEffect(() => {
1816
+ if (locked && open) setOpen(false)
1817
+ }, [locked, open])
1818
+
1819
+ const rank = useMemo(() => {
1820
+ const map = new Map()
1821
+ for (const model of catalogSnap.data?.models ?? []) {
1822
+ map.set(`${model.provider}${MODEL_KEY_SEPARATOR}${model.model}`, model.order)
1823
+ }
1824
+ return map
1825
+ }, [catalogSnap.data])
1826
+
1827
+ const priceByKey = useMemo(() => {
1828
+ const map = new Map()
1829
+ for (const model of catalogSnap.data?.models ?? []) {
1830
+ map.set(`${model.provider}${MODEL_KEY_SEPARATOR}${model.model}`, model.pricing)
1831
+ }
1832
+ return map
1833
+ }, [catalogSnap.data])
1834
+
1835
+ const groups = state?.groups
1836
+ const catalogModels = catalogSnap.data?.models
1837
+ const entries = useMemo(() => {
1838
+ if (Array.isArray(groups) && groups.length > 0) {
1839
+ const list = []
1840
+ for (const [groupIndex, group] of groups.entries()) {
1841
+ for (const [modelIndex, model] of group.models.entries()) {
1842
+ list.push({ group, model, groupIndex, modelIndex })
1843
+ }
1844
+ }
1845
+ list.sort((left, right) => {
1846
+ const leftRank = rank.get(`${left.group.id}${MODEL_KEY_SEPARATOR}${left.model.id}`) ?? Number.MAX_SAFE_INTEGER
1847
+ const rightRank = rank.get(`${right.group.id}${MODEL_KEY_SEPARATOR}${right.model.id}`) ?? Number.MAX_SAFE_INTEGER
1848
+ return leftRank - rightRank || left.groupIndex - right.groupIndex || left.modelIndex - right.modelIndex
1849
+ })
1850
+ return list
1851
+ }
1852
+ return (catalogModels ?? []).map((model, index) => ({
1853
+ group: { id: model.provider, name: model.providerName },
1854
+ model: {
1855
+ id: model.model,
1856
+ name: model.name,
1857
+ ...(model.reasoning === undefined ? {} : { reasoning: model.reasoning }),
1858
+ },
1859
+ groupIndex: model.order ?? index,
1860
+ modelIndex: index,
1861
+ }))
1862
+ }, [groups, catalogModels, rank])
1863
+
1864
+ const projected = selectionProjection?.next ?? selectionProjection?.lastUsed ?? null
1865
+ const current = state?.current ?? projected
1866
+ const currentEntry = current === null
1867
+ ? undefined
1868
+ : entries.find((entry) => entry.group.id === current.provider && entry.model.id === current.model)
1869
+ const currentCatalog = current === null
1870
+ ? undefined
1871
+ : (catalogModels ?? []).find((model) => model.provider === current.provider && model.model === current.model)
1872
+ const currentReasoning = currentEntry?.model.reasoning
1873
+ const effectiveEffort = current?.reasoningEffort ?? currentReasoning?.defaultEffort
1874
+ const effortLabel = current === null
1875
+ ? undefined
1876
+ : currentReasoning === undefined
1877
+ ? state?.retainedEffort
1878
+ : effectiveEffort === undefined
1879
+ ? translate('providerDefault')
1880
+ : currentReasoning.efforts.find((effort) => effort.id === effectiveEffort)?.name ?? effectiveEffort
1881
+ const effortChoices = currentReasoning === undefined
1882
+ ? []
1883
+ : [
1884
+ ...(currentReasoning.defaultEffort === undefined
1885
+ ? [{ key: 'provider-default', effort: undefined, label: translate('providerDefault') }]
1886
+ : []),
1887
+ ...currentReasoning.efforts.map((effort) => ({
1888
+ key: `effort:${effort.id}`,
1889
+ effort: effort.id,
1890
+ label: effort.name,
1891
+ })),
1892
+ ]
1893
+
1894
+ const showSearch = entries.length > 4
1895
+ const term = query.trim().toLowerCase()
1896
+ const filtered = useMemo(() => {
1897
+ if (term === '') return entries
1898
+ return entries.filter((entry) => `${entry.model.name} ${entry.group.name}`.toLowerCase().includes(term))
1899
+ }, [entries, term])
1900
+ // Keep the roving cursor inside the visible list; a shrunk search result
1901
+ // must not leave the index pointing past the end.
1902
+ const active = filtered.length === 0 ? -1 : Math.min(Math.max(activeIndex, 0), filtered.length - 1)
1903
+
1904
+ useLayoutEffect(() => {
1905
+ if (!open) {
1906
+ setMenuPos(null)
1907
+ return undefined
1908
+ }
1909
+ const place = () => {
1910
+ const rect = triggerRef.current?.getBoundingClientRect()
1911
+ if (rect === undefined) return
1912
+ const width = Math.min(360, window.innerWidth - 24)
1913
+ const left = Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))
1914
+ const spaceAbove = rect.top - 12
1915
+ const spaceBelow = window.innerHeight - rect.bottom - 12
1916
+ const openBelow = spaceBelow > spaceAbove
1917
+ const maxHeight = Math.min(480, Math.max(160, openBelow ? spaceBelow : spaceAbove))
1918
+ setMenuPos(openBelow
1919
+ ? { left, top: rect.bottom + 8, width, maxHeight }
1920
+ : { left, bottom: window.innerHeight - rect.top + 8, width, maxHeight })
1921
+ }
1922
+ place()
1923
+ window.addEventListener('scroll', place, true)
1924
+ window.addEventListener('resize', place)
1925
+ return () => {
1926
+ window.removeEventListener('scroll', place, true)
1927
+ window.removeEventListener('resize', place)
1928
+ }
1929
+ }, [open, filtered.length, state?.status])
1930
+
1931
+ useEffect(() => {
1932
+ if (!open) return undefined
1933
+ const timer = setTimeout(() => {
1934
+ if (showSearch) {
1935
+ searchRef.current?.focus()
1936
+ return
1937
+ }
1938
+ const rows = menuRef.current?.querySelectorAll('.mb-picker-row')
1939
+ const target = rows?.[active]
1940
+ if (target instanceof HTMLElement) target.focus()
1941
+ }, 0)
1942
+ return () => clearTimeout(timer)
1943
+ // Focus follows the roving cursor so arrow keys keep focus on the active row.
1944
+ }, [open, showSearch, active])
1945
+
1946
+ const loading = catalogSnap.data === null && (state === null || state.status === 'loading')
1947
+ const busy = selecting || state?.status === 'selecting'
1948
+ const currentName = currentEntry?.model.name ?? currentCatalog?.name
1949
+ const triggerModel = currentName ?? (loading ? translate('loadingModels') : translate('chooseModel'))
1950
+ const triggerAria = effortLabel === undefined ? triggerModel : `${triggerModel} · ${effortLabel}`
1951
+
1952
+ const close = (restoreFocus) => {
1953
+ setOpen(false)
1954
+ setQuery('')
1955
+ setFailure(null)
1956
+ if (restoreFocus) queueMicrotask(() => triggerRef.current?.focus())
1957
+ }
1958
+
1959
+ const submit = async (selection) => {
1960
+ if (busy) return
1961
+ setSelecting(true)
1962
+ setFailure(null)
1963
+ try {
1964
+ const result = directory !== null
1965
+ ? await directory.select(selection)
1966
+ : await requestJson('/model-billing/select', {
1967
+ method: 'POST',
1968
+ headers: { 'content-type': 'application/json' },
1969
+ body: JSON.stringify({ sessionId, ...selection }),
1970
+ })
1971
+ if (result?.ok === false) {
1972
+ setFailure(result.error?.message ?? translate('pickerEmpty'))
1973
+ return
1974
+ }
1975
+ close(true)
1976
+ } catch (error) {
1977
+ setFailure(error instanceof Error ? error.message : String(error))
1978
+ } finally {
1979
+ setSelecting(false)
1980
+ }
1981
+ }
1982
+
1983
+ const chooseModel = (entry) => {
1984
+ if (current?.provider === entry.group.id && current?.model === entry.model.id) {
1985
+ close(true)
1986
+ return
1987
+ }
1988
+ void submit({ provider: entry.group.id, model: entry.model.id })
1989
+ }
1990
+
1991
+ const chooseEffort = (effort) => {
1992
+ if (current === null) return
1993
+ if (effectiveEffort === effort) {
1994
+ close(true)
1995
+ return
1996
+ }
1997
+ void submit({
1998
+ provider: current.provider,
1999
+ model: current.model,
2000
+ ...effort === undefined ? {} : { reasoningEffort: effort },
2001
+ })
2002
+ }
2003
+
2004
+ const toggle = () => {
2005
+ if (open) {
2006
+ close(true)
2007
+ return
2008
+ }
2009
+ setFailure(null)
2010
+ // Open the cursor on the row the user is already using, when there is one.
2011
+ const selectedAt = filtered.findIndex((entry) => entry.group.id === current?.provider && entry.model.id === current?.model)
2012
+ setActiveIndex(selectedAt < 0 ? 0 : selectedAt)
2013
+ setOpen(true)
2014
+ if (directory !== null) directory.load().catch(() => {})
2015
+ }
2016
+
2017
+ const menuStyle = menuPos === null
2018
+ ? { left: 0, top: 0, width: 360, visibility: 'hidden' }
2019
+ : {
2020
+ left: menuPos.left,
2021
+ width: menuPos.width,
2022
+ maxHeight: menuPos.maxHeight,
2023
+ ...menuPos.top === undefined ? { bottom: menuPos.bottom } : { top: menuPos.top },
2024
+ }
2025
+ const errorText = failure ?? (state?.status === 'error' ? state.error : null)
2026
+
2027
+ // Arrow keys move a roving cursor through the list. Enter and Space are
2028
+ // left to the focused row itself, so a <button> keeps its native
2029
+ // activation and the menu never fires the choice twice.
2030
+ const focusRow = (index) => {
2031
+ const rows = menuRef.current?.querySelectorAll('.mb-picker-row')
2032
+ const target = rows?.[index]
2033
+ if (target instanceof HTMLElement) target.focus()
2034
+ }
2035
+ const moveActive = (delta) => {
2036
+ if (filtered.length === 0) return
2037
+ const next = Math.min(Math.max(active + delta, 0), filtered.length - 1)
2038
+ setActiveIndex(next)
2039
+ focusRow(next)
2040
+ }
2041
+ const onMenuKeyDown = (event) => {
2042
+ if (event.key === 'ArrowDown') {
2043
+ event.preventDefault()
2044
+ moveActive(1)
2045
+ return
2046
+ }
2047
+ if (event.key === 'ArrowUp') {
2048
+ event.preventDefault()
2049
+ moveActive(-1)
2050
+ return
2051
+ }
2052
+ if (event.key === 'Home') {
2053
+ event.preventDefault()
2054
+ if (filtered.length === 0) return
2055
+ setActiveIndex(0)
2056
+ focusRow(0)
2057
+ return
2058
+ }
2059
+ if (event.key === 'End') {
2060
+ event.preventDefault()
2061
+ const last = filtered.length - 1
2062
+ if (last < 0) return
2063
+ setActiveIndex(last)
2064
+ focusRow(last)
2065
+ }
2066
+ }
2067
+
2068
+ const menu = h('div', {
2069
+ ref: menuRef,
2070
+ id: `${id}-menu`,
2071
+ className: 'mb-picker-menu',
2072
+ style: menuStyle,
2073
+ role: 'dialog',
2074
+ 'aria-label': translate('pickerAria'),
2075
+ onKeyDown: onMenuKeyDown,
2076
+ },
2077
+ showSearch ? h('input', {
2078
+ ref: searchRef,
2079
+ className: 'mb-picker-search',
2080
+ type: 'search',
2081
+ value: query,
2082
+ placeholder: translate('searchModel'),
2083
+ 'aria-label': translate('searchModel'),
2084
+ onChange: (event) => {
2085
+ setQuery(event.target.value)
2086
+ // A shorter result list must not leave the cursor on a removed row.
2087
+ setActiveIndex(0)
2088
+ },
2089
+ onKeyDown: (event) => {
2090
+ // Enter picks the highlighted row; a downward arrow steps into the list.
2091
+ if (event.key === 'ArrowDown') {
2092
+ event.preventDefault()
2093
+ moveActive(1)
2094
+ return
2095
+ }
2096
+ if (event.key !== 'Enter' || filtered.length === 0 || busy) return
2097
+ event.preventDefault()
2098
+ chooseModel(filtered[active])
2099
+ },
2100
+ }) : null,
2101
+ h('div', { className: 'mb-picker-list', role: 'menu' },
2102
+ filtered.length === 0
2103
+ ? h('div', { className: 'mb-picker-empty' }, term === '' ? translate('pickerEmpty') : translate('noMatch'))
2104
+ : filtered.map((entry, index) => {
2105
+ const selected = current?.provider === entry.group.id && current?.model === entry.model.id
2106
+ const previous = filtered[index - 1]
2107
+ const showGroup = previous === undefined || previous.group.id !== entry.group.id
2108
+ const price = priceByKey.get(`${entry.group.id}${MODEL_KEY_SEPARATOR}${entry.model.id}`)
2109
+ return h(Fragment, { key: `${entry.group.id}${MODEL_KEY_SEPARATOR}${entry.model.id}` },
2110
+ showGroup ? h('div', { className: 'mb-picker-group' }, entry.group.name) : null,
2111
+ h('button', {
2112
+ type: 'button',
2113
+ role: 'menuitemradio',
2114
+ className: 'mb-picker-row',
2115
+ 'aria-checked': selected ? 'true' : 'false',
2116
+ title: entry.model.name,
2117
+ // Roving tabindex: only the cursor row is reachable by Tab.
2118
+ tabIndex: index === active ? 0 : -1,
2119
+ disabled: busy,
2120
+ onClick: () => chooseModel(entry),
2121
+ },
2122
+ h('span', { className: 'mb-picker-option-copy' },
2123
+ h('span', { className: 'mb-picker-model' }, entry.model.name),
2124
+ h(PriceLines, { pricing: price, translate })),
2125
+ h('span', { className: 'mb-picker-check' },
2126
+ selected
2127
+ ? h('svg', {
2128
+ viewBox: '0 0 16 16',
2129
+ width: 14,
2130
+ height: 14,
2131
+ fill: 'none',
2132
+ stroke: 'currentColor',
2133
+ strokeWidth: 1.7,
2134
+ 'aria-hidden': true,
2135
+ },
2136
+ h('path', { d: 'M3.5 8.5l3 3 6-7' }))
2137
+ : null)))
2138
+ })),
2139
+ effortChoices.length === 0 ? null : h(Fragment, null,
2140
+ h('div', { className: 'mb-picker-divider' }),
2141
+ h('div', { className: 'mb-picker-efforts' },
2142
+ h('span', { className: 'mb-picker-efforts-label' }, translate('reasoningEffort')),
2143
+ effortChoices.map((choice) => h('button', {
2144
+ type: 'button',
2145
+ key: choice.key,
2146
+ className: 'mb-picker-chip',
2147
+ 'aria-pressed': effectiveEffort === choice.effort ? 'true' : 'false',
2148
+ disabled: busy,
2149
+ onClick: () => chooseEffort(choice.effort),
2150
+ }, choice.label)))),
2151
+ busy ? h('div', { className: 'mb-picker-status' }, translate('switching')) : null,
2152
+ errorText === null ? null : h('div', { className: 'mb-picker-error' }, errorText),
2153
+ state?.status === 'error'
2154
+ ? h('button', {
2155
+ type: 'button',
2156
+ className: 'mb-btn mb-picker-retry',
2157
+ onClick: () => {
2158
+ setFailure(null)
2159
+ directory.load().catch(() => {})
2160
+ },
2161
+ }, translate('pickerRetry'))
2162
+ : null)
2163
+
2164
+ return h('div', {
2165
+ className: 'mb-picker',
2166
+ ref: rootRef,
2167
+ },
2168
+ h(Style),
2169
+ h('button', {
2170
+ ref: triggerRef,
2171
+ type: 'button',
2172
+ className: 'mb-picker-trigger',
2173
+ disabled: locked,
2174
+ 'aria-label': triggerAria,
2175
+ 'aria-haspopup': 'menu',
2176
+ 'aria-controls': open ? `${id}-menu` : undefined,
2177
+ 'aria-expanded': open ? 'true' : 'false',
2178
+ 'aria-busy': busy ? 'true' : undefined,
2179
+ title: triggerAria,
2180
+ onClick: toggle,
2181
+ },
2182
+ h('svg', {
2183
+ viewBox: '0 0 16 16',
2184
+ width: 14,
2185
+ height: 14,
2186
+ fill: 'none',
2187
+ stroke: 'currentColor',
2188
+ strokeWidth: 1.3,
2189
+ 'aria-hidden': true,
2190
+ className: 'mb-picker-icon',
2191
+ },
2192
+ h('rect', { x: 2, y: 3, width: 12, height: 10, rx: 2 }),
2193
+ h('path', { d: 'M2 6.5h12M6 6.5V13' })),
2194
+ h('span', { className: 'mb-picker-name' }, triggerModel),
2195
+ effortLabel === undefined ? null : h('span', { className: 'mb-picker-trigger-effort' }, effortLabel),
2196
+ h('svg', {
2197
+ className: open ? 'mb-picker-chevron mb-picker-chevron-open' : 'mb-picker-chevron',
2198
+ viewBox: '0 0 16 16',
2199
+ width: 14,
2200
+ height: 14,
2201
+ fill: 'none',
2202
+ stroke: 'currentColor',
2203
+ strokeWidth: 1.5,
2204
+ 'aria-hidden': true,
2205
+ },
2206
+ h('path', { d: 'M4 6l4 4 4-4' }))),
2207
+ open ? ReactDOM.createPortal(menu, document.body) : null)
2208
+ }
2209
+
2210
+ function ModelPickerSeat(props) {
2211
+ const catalogSnap = useCatalog()
2212
+ // Take over only while we hold a usable catalog. On a fetch error or an
2213
+ // in-flight load, return null so the built-in picker keeps working
2214
+ // instead of leaving the user with no way to change models.
2215
+ if (catalogSnap.status !== 'ready') return null
2216
+ const display = readDisplay(catalogSnap.data)
2217
+ if (!display.takeoverPicker) return null
2218
+ return h(OrderedModelPicker, props)
2219
+ }
2220
+
2221
+ return {
2222
+ inject: ['slots', 'locale'],
2223
+ apply(ctx) {
2224
+ localeService = ctx.get('locale')
2225
+ publishModelDirectories(ctx.get('modelDirectories'))
2226
+ ctx.inject(['modelDirectories'], (scope) => {
2227
+ publishModelDirectories(scope.modelDirectories)
2228
+ let seat = null
2229
+ const takeoverEnabled = () => catalog.snap.status === 'ready' && readDisplay(catalog.snap.data).takeoverPicker !== false
2230
+ const syncSeat = () => {
2231
+ if (takeoverEnabled()) {
2232
+ if (seat === null) {
2233
+ seat = scope.slots.register({
2234
+ name: 'conversation.input.model',
2235
+ priority: -1,
2236
+ }, ModelPickerSeat)
2237
+ }
2238
+ return
2239
+ }
2240
+ if (seat !== null) {
2241
+ seat()
2242
+ seat = null
2243
+ }
2244
+ }
2245
+ scope.slots.inject('conversation.input.model', () => {
2246
+ const unsubscribe = subscribeCatalog(syncSeat)
2247
+ syncSeat()
2248
+ return () => {
2249
+ unsubscribe()
2250
+ if (seat !== null) {
2251
+ seat()
2252
+ seat = null
2253
+ }
2254
+ }
2255
+ })
2256
+ })
2257
+
2258
+ void ensureCatalog()
2259
+
2260
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
2261
+ name: 'settings.section',
2262
+ id: 'model-billing',
2263
+ order: 12,
2264
+ label: () => t('nav'),
2265
+ }, SettingsSection))
2266
+
2267
+ ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
2268
+ name: 'conversation.composer.dock',
2269
+ id: 'model-billing-cost',
2270
+ order: 2,
2271
+ }, CostDock))
2272
+
2273
+ ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({
2274
+ name: 'conversation.chat.turnTail',
2275
+ id: 'model-billing-turn',
2276
+ order: 30,
2277
+ }, TurnCost))
2278
+ },
2279
+ }
2280
+ },
2281
+ })