codexmate 0.0.29 → 0.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +363 -421
  2. package/README.zh.md +371 -354
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1725 -1725
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +402 -384
  9. package/cli/config-health.js +454 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/local-bridge.js +324 -0
  13. package/cli/openai-bridge.js +1653 -1576
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -65
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -43
  18. package/cli/session-usage.concurrent.js +28 -28
  19. package/cli/session-usage.js +118 -118
  20. package/cli/session-usage.models.js +176 -176
  21. package/cli/skills.js +1141 -1141
  22. package/cli/zip-commands.js +510 -510
  23. package/cli.js +15778 -15340
  24. package/lib/automation.js +404 -404
  25. package/lib/cli-file-utils.js +151 -151
  26. package/lib/cli-models-utils.js +440 -440
  27. package/lib/cli-network-utils.js +190 -190
  28. package/lib/cli-path-utils.js +85 -85
  29. package/lib/cli-session-utils.js +121 -121
  30. package/lib/cli-sessions.js +417 -417
  31. package/lib/cli-utils.js +155 -155
  32. package/lib/cli-webhook.js +126 -126
  33. package/lib/download-artifacts.js +92 -92
  34. package/lib/mcp-stdio.js +453 -453
  35. package/lib/task-orchestrator.js +869 -869
  36. package/lib/text-diff.js +303 -303
  37. package/lib/workflow-engine.js +340 -340
  38. package/package.json +76 -76
  39. package/plugins/README.md +20 -20
  40. package/plugins/README.zh-CN.md +20 -20
  41. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  42. package/plugins/prompt-templates/computed.mjs +253 -253
  43. package/plugins/prompt-templates/index.mjs +8 -8
  44. package/plugins/prompt-templates/manifest.mjs +15 -15
  45. package/plugins/prompt-templates/methods.mjs +553 -553
  46. package/plugins/prompt-templates/overview.mjs +91 -91
  47. package/plugins/prompt-templates/ownership.mjs +19 -19
  48. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  49. package/plugins/prompt-templates/storage.mjs +64 -64
  50. package/plugins/registry.mjs +16 -16
  51. package/web-ui/app.js +646 -639
  52. package/web-ui/index.html +36 -36
  53. package/web-ui/logic.agents-diff.mjs +386 -386
  54. package/web-ui/logic.claude.mjs +168 -168
  55. package/web-ui/logic.codex.mjs +69 -69
  56. package/web-ui/logic.mjs +5 -5
  57. package/web-ui/logic.runtime.mjs +128 -128
  58. package/web-ui/logic.session-convert.mjs +70 -70
  59. package/web-ui/logic.sessions.mjs +765 -765
  60. package/web-ui/modules/api.mjs +90 -90
  61. package/web-ui/modules/app.computed.dashboard.mjs +248 -225
  62. package/web-ui/modules/app.computed.index.mjs +17 -17
  63. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  64. package/web-ui/modules/app.computed.session.mjs +999 -999
  65. package/web-ui/modules/app.constants.mjs +15 -15
  66. package/web-ui/modules/app.methods.agents.mjs +632 -632
  67. package/web-ui/modules/app.methods.claude-config.mjs +200 -200
  68. package/web-ui/modules/app.methods.codex-config.mjs +841 -892
  69. package/web-ui/modules/app.methods.index.mjs +94 -94
  70. package/web-ui/modules/app.methods.install.mjs +205 -205
  71. package/web-ui/modules/app.methods.navigation.mjs +774 -761
  72. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  73. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  74. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  75. package/web-ui/modules/app.methods.providers.mjs +529 -493
  76. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  77. package/web-ui/modules/app.methods.session-actions.mjs +591 -593
  78. package/web-ui/modules/app.methods.session-browser.mjs +984 -984
  79. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  80. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  81. package/web-ui/modules/app.methods.startup-claude.mjs +534 -533
  82. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  83. package/web-ui/modules/app.methods.webhook.mjs +79 -79
  84. package/web-ui/modules/config-mode.computed.mjs +124 -124
  85. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  86. package/web-ui/modules/i18n.dict.mjs +3174 -3131
  87. package/web-ui/modules/i18n.mjs +62 -62
  88. package/web-ui/modules/plugins.computed.mjs +3 -3
  89. package/web-ui/modules/plugins.methods.mjs +3 -3
  90. package/web-ui/modules/plugins.storage.mjs +11 -11
  91. package/web-ui/modules/provider-url-display.mjs +17 -17
  92. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  93. package/web-ui/modules/skills.computed.mjs +107 -107
  94. package/web-ui/modules/skills.methods.mjs +482 -481
  95. package/web-ui/partials/index/layout-footer.html +13 -13
  96. package/web-ui/partials/index/layout-header.html +500 -500
  97. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  98. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  99. package/web-ui/partials/index/modal-health-check.html +45 -45
  100. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  101. package/web-ui/partials/index/modal-skills.html +200 -200
  102. package/web-ui/partials/index/modals-basic.html +162 -162
  103. package/web-ui/partials/index/panel-config-claude.html +194 -194
  104. package/web-ui/partials/index/panel-config-codex.html +357 -323
  105. package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
  106. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  107. package/web-ui/partials/index/panel-dashboard.html +219 -186
  108. package/web-ui/partials/index/panel-docs.html +147 -147
  109. package/web-ui/partials/index/panel-market.html +177 -177
  110. package/web-ui/partials/index/panel-orchestration.html +391 -391
  111. package/web-ui/partials/index/panel-plugins.html +253 -253
  112. package/web-ui/partials/index/panel-sessions.html +302 -316
  113. package/web-ui/partials/index/panel-settings.html +190 -190
  114. package/web-ui/partials/index/panel-trash.html +88 -88
  115. package/web-ui/partials/index/panel-usage.html +371 -371
  116. package/web-ui/res/json5.min.js +1 -1
  117. package/web-ui/res/vue.global.prod.js +13 -13
  118. package/web-ui/session-helpers.mjs +591 -576
  119. package/web-ui/source-bundle.cjs +233 -233
  120. package/web-ui/styles/base-theme.css +281 -281
  121. package/web-ui/styles/bridge-pool.css +197 -0
  122. package/web-ui/styles/controls-forms.css +422 -422
  123. package/web-ui/styles/dashboard.css +406 -274
  124. package/web-ui/styles/docs-panel.css +271 -271
  125. package/web-ui/styles/feedback.css +108 -108
  126. package/web-ui/styles/health-check-dialog.css +144 -144
  127. package/web-ui/styles/layout-shell.css +626 -626
  128. package/web-ui/styles/modals-core.css +466 -466
  129. package/web-ui/styles/navigation-panels.css +391 -391
  130. package/web-ui/styles/openclaw-structured.css +266 -266
  131. package/web-ui/styles/plugins-panel.css +564 -523
  132. package/web-ui/styles/responsive.css +454 -454
  133. package/web-ui/styles/sessions-list.css +417 -419
  134. package/web-ui/styles/sessions-preview.css +407 -411
  135. package/web-ui/styles/sessions-toolbar-trash.css +348 -330
  136. package/web-ui/styles/sessions-usage.css +1040 -1040
  137. package/web-ui/styles/settings-panel.css +349 -349
  138. package/web-ui/styles/skills-list.css +305 -303
  139. package/web-ui/styles/skills-market.css +429 -406
  140. package/web-ui/styles/task-orchestration.css +822 -822
  141. package/web-ui/styles/titles-cards.css +472 -472
  142. package/web-ui/styles/trash-panel.css +90 -90
  143. package/web-ui/styles/webhook.css +81 -81
  144. package/web-ui/styles.css +24 -23
  145. package/web-ui.html +17 -17
@@ -1,999 +1,999 @@
1
- import {
2
- buildSessionTimelineNodes,
3
- buildUsageChartGroups,
4
- buildUsageHeatmap,
5
- buildUsageHourlyHeatmap,
6
- isSessionQueryEnabled
7
- } from '../logic.mjs';
8
- import { SESSION_TRASH_PAGE_SIZE } from './app.constants.mjs';
9
-
10
- function formatUsageSummaryNumber(value) {
11
- const numeric = Number(value);
12
- if (!Number.isFinite(numeric) || numeric < 0) {
13
- return '0';
14
- }
15
- return Math.floor(numeric).toLocaleString('en-US');
16
- }
17
-
18
- function formatCompactUsageSummaryNumber(value) {
19
- const numeric = Number(value);
20
- if (!Number.isFinite(numeric) || numeric < 0) {
21
- return '0';
22
- }
23
- return new Intl.NumberFormat('en-US', {
24
- notation: 'compact',
25
- compactDisplay: 'short',
26
- maximumFractionDigits: 1
27
- }).format(Math.floor(numeric));
28
- }
29
-
30
- function readUsageCostNumber(value) {
31
- const numeric = Number(value);
32
- if (!Number.isFinite(numeric) || numeric < 0) {
33
- return null;
34
- }
35
- return numeric;
36
- }
37
-
38
- function formatUsageEstimatedCost(value, options = {}) {
39
- const numeric = Number(value);
40
- if (!Number.isFinite(numeric) || numeric <= 0) {
41
- return '$0.00';
42
- }
43
- const precise = options && options.precise === true;
44
- if (numeric < 0.0001) {
45
- return '<$0.0001';
46
- }
47
- let fractionDigits = 2;
48
- if (numeric < 1) {
49
- fractionDigits = precise ? 6 : 4;
50
- } else if (numeric >= 100) {
51
- fractionDigits = 0;
52
- }
53
- return new Intl.NumberFormat('en-US', {
54
- style: 'currency',
55
- currency: 'USD',
56
- minimumFractionDigits: fractionDigits,
57
- maximumFractionDigits: fractionDigits
58
- }).format(numeric);
59
- }
60
-
61
- function formatSignedUsageSummaryNumber(value) {
62
- const numeric = Number(value);
63
- if (!Number.isFinite(numeric) || numeric === 0) {
64
- return '0';
65
- }
66
- const sign = numeric > 0 ? '+' : '-';
67
- return `${sign}${formatUsageSummaryNumber(Math.abs(numeric))}`;
68
- }
69
-
70
- function formatSignedUsageEstimatedCost(value, options = {}) {
71
- const numeric = Number(value);
72
- if (!Number.isFinite(numeric) || numeric === 0) {
73
- return '$0.00';
74
- }
75
- const sign = numeric > 0 ? '+' : '-';
76
- return `${sign}${formatUsageEstimatedCost(Math.abs(numeric), options)}`;
77
- }
78
-
79
- function formatUsageRangeLabel(range, t) {
80
- const normalized = typeof range === 'string' ? range.trim().toLowerCase() : '7d';
81
- if (typeof t === 'function') {
82
- if (normalized === '30d') return t('usage.range.30d');
83
- if (normalized === 'all') return t('usage.range.all');
84
- return t('usage.range.7d');
85
- }
86
- if (normalized === '30d') return '近 30 天';
87
- if (normalized === 'all') return '全部';
88
- return '近 7 天';
89
- }
90
-
91
- function formatUsageDuration(value, options = {}) {
92
- const normalizedLang = typeof options.lang === 'string' ? options.lang.trim().toLowerCase() : '';
93
- const isEn = normalizedLang === 'en';
94
- const numeric = Number(value);
95
- if (!Number.isFinite(numeric) || numeric <= 0) {
96
- return isEn ? '0m' : '0分';
97
- }
98
- const totalMinutes = Math.floor(numeric / 60000);
99
- if (totalMinutes <= 0) {
100
- return isEn ? '<1m' : '<1分';
101
- }
102
- const maxParts = Number.isFinite(Number(options.maxParts))
103
- ? Math.max(1, Math.floor(Number(options.maxParts)))
104
- : 2;
105
- const compact = options.compact !== false;
106
- const units = compact
107
- ? (
108
- isEn
109
- ? [
110
- { label: 'd', value: 24 * 60 },
111
- { label: 'h', value: 60 },
112
- { label: 'm', value: 1 }
113
- ]
114
- : [
115
- { label: '天', value: 24 * 60 },
116
- { label: '时', value: 60 },
117
- { label: '分', value: 1 }
118
- ]
119
- )
120
- : (
121
- isEn
122
- ? [
123
- { label: 'day', value: 24 * 60 },
124
- { label: 'hr', value: 60 },
125
- { label: 'min', value: 1 }
126
- ]
127
- : [
128
- { label: '天', value: 24 * 60 },
129
- { label: '小时', value: 60 },
130
- { label: '分', value: 1 }
131
- ]
132
- );
133
- let remainingMinutes = totalMinutes;
134
- const parts = [];
135
- for (const unit of units) {
136
- if (remainingMinutes < unit.value && unit.value !== 1) {
137
- continue;
138
- }
139
- const count = unit.value === 1 ? remainingMinutes : Math.floor(remainingMinutes / unit.value);
140
- if (count <= 0) {
141
- continue;
142
- }
143
- parts.push(compact ? `${count}${unit.label}` : (isEn ? `${count} ${unit.label}` : `${count}${unit.label}`));
144
- remainingMinutes -= count * unit.value;
145
- if (parts.length >= maxParts) {
146
- break;
147
- }
148
- }
149
- return parts.length ? parts.join(compact ? '' : ' ') : (isEn ? '0m' : '0分');
150
- }
151
-
152
- const KNOWN_USAGE_MODEL_PRICING = Object.freeze({
153
- 'gpt-5.4': Object.freeze({ input: 2.5, output: 15, cacheRead: 0.25, cacheWrite: 0 }),
154
- 'gpt-5.4-mini': Object.freeze({ input: 0.75, output: 4.5, cacheRead: 0.075, cacheWrite: 0 }),
155
- 'gpt-5.3-codex': Object.freeze({ input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 }),
156
- 'gpt-5.2-codex': Object.freeze({ input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 }),
157
- 'claude-opus-4-6': Object.freeze({ input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75, reasoningOutput: 75 }),
158
- 'claude-opus-4-7': Object.freeze({ input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75, reasoningOutput: 75 }),
159
- 'claude-sonnet-4-6': Object.freeze({ input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75, reasoningOutput: 15 }),
160
- 'claude-haiku-4-5': Object.freeze({ input: 0.8, output: 4, cacheRead: 0.08, cacheWrite: 1, reasoningOutput: 4 }),
161
- 'claude-3-5-sonnet': Object.freeze({ input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75, reasoningOutput: 15 }),
162
- 'claude-3-5-haiku': Object.freeze({ input: 0.8, output: 4, cacheRead: 0.08, cacheWrite: 1, reasoningOutput: 4 }),
163
- 'claude-3-opus': Object.freeze({ input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75, reasoningOutput: 75 })
164
- });
165
-
166
- function createUsagePricingEntry(pricing, source) {
167
- const resolvedSource = typeof source === 'string' && source.trim() ? source.trim() : 'provider-config';
168
- return {
169
- input: readUsageCostNumber(pricing && pricing.input),
170
- output: readUsageCostNumber(pricing && pricing.output),
171
- reasoningOutput: readUsageCostNumber(
172
- pricing && (pricing.reasoningOutput != null ? pricing.reasoningOutput : pricing.reasoning)
173
- ),
174
- cacheRead: readUsageCostNumber(pricing && pricing.cacheRead),
175
- cacheWrite: readUsageCostNumber(pricing && pricing.cacheWrite),
176
- source: resolvedSource
177
- };
178
- }
179
-
180
- function buildUsagePricingIndex(providersList = []) {
181
- const byProvider = new Map();
182
- const byModel = new Map();
183
- const knownByModel = new Map();
184
- const list = Array.isArray(providersList) ? providersList : [];
185
- for (const provider of list) {
186
- if (!provider || typeof provider !== 'object') continue;
187
- const providerName = typeof provider.name === 'string' ? provider.name.trim() : '';
188
- const models = Array.isArray(provider.models) ? provider.models : [];
189
- const providerMap = new Map();
190
- for (const model of models) {
191
- if (!model || typeof model !== 'object') continue;
192
- const modelId = typeof model.id === 'string' ? model.id.trim() : '';
193
- if (!modelId) continue;
194
- const pricing = createUsagePricingEntry(
195
- model.cost && typeof model.cost === 'object' && !Array.isArray(model.cost)
196
- ? model.cost
197
- : null,
198
- 'provider-config'
199
- );
200
- const hasKnownRate = [pricing.input, pricing.output, pricing.reasoningOutput, pricing.cacheRead, pricing.cacheWrite]
201
- .some((value) => value !== null);
202
- if (!hasKnownRate) continue;
203
- providerMap.set(modelId, pricing);
204
- const modelMatches = byModel.get(modelId) || [];
205
- modelMatches.push({ provider: providerName, pricing });
206
- byModel.set(modelId, modelMatches);
207
- }
208
- if (providerName && providerMap.size) {
209
- byProvider.set(providerName, providerMap);
210
- }
211
- }
212
- for (const [modelId, pricing] of Object.entries(KNOWN_USAGE_MODEL_PRICING)) {
213
- const normalizedModelId = typeof modelId === 'string' ? modelId.trim() : '';
214
- if (!normalizedModelId || byModel.has(normalizedModelId)) {
215
- continue;
216
- }
217
- knownByModel.set(normalizedModelId, createUsagePricingEntry(pricing, 'public-catalog'));
218
- }
219
- return { byProvider, byModel, knownByModel };
220
- }
221
-
222
- function resolveUsagePricingForSession(session, pricingIndex, fallbackProvider = '') {
223
- if (!session || typeof session !== 'object' || !pricingIndex || typeof pricingIndex !== 'object') {
224
- return null;
225
- }
226
- const model = typeof session.model === 'string' ? session.model.trim() : '';
227
- if (!model) return null;
228
- const provider = typeof session.provider === 'string' ? session.provider.trim() : '';
229
- const effectiveProvider = provider || fallbackProvider;
230
- if (effectiveProvider) {
231
- const providerMap = pricingIndex.byProvider instanceof Map ? pricingIndex.byProvider.get(effectiveProvider) : null;
232
- if (providerMap instanceof Map && providerMap.has(model)) {
233
- return providerMap.get(model);
234
- }
235
- }
236
- const modelMatches = pricingIndex.byModel instanceof Map ? pricingIndex.byModel.get(model) : null;
237
- if (Array.isArray(modelMatches) && modelMatches.length === 1) {
238
- return modelMatches[0].pricing;
239
- }
240
- const knownPricing = pricingIndex.knownByModel instanceof Map ? pricingIndex.knownByModel.get(model) : null;
241
- if (knownPricing) {
242
- return knownPricing;
243
- }
244
- const strippedModel = model.replace(/-\d{8}(?=[-_]|$)/, '');
245
- if (strippedModel !== model) {
246
- const strippedKnown = pricingIndex.knownByModel instanceof Map ? pricingIndex.knownByModel.get(strippedModel) : null;
247
- if (strippedKnown) {
248
- return strippedKnown;
249
- }
250
- }
251
- return null;
252
- }
253
-
254
- function shouldEstimateUsageCostForSession() {
255
- return true;
256
- }
257
-
258
- function estimateUsageCostSummary(sessions, providersList, currentProvider) {
259
- const list = Array.isArray(sessions) ? sessions : [];
260
- const pricingIndex = buildUsagePricingIndex(providersList);
261
- let totalCostUsd = 0;
262
- let estimatedSessions = 0;
263
- let totalTokens = 0;
264
- let estimatedTokens = 0;
265
- let configuredSessions = 0;
266
- let catalogSessions = 0;
267
- let missingPricingSessions = 0;
268
- let missingTokenSessions = 0;
269
- let supportedSessions = 0;
270
- let skippedUnsupportedSessions = 0;
271
-
272
- for (const session of list) {
273
- if (!session || typeof session !== 'object') continue;
274
- if (!shouldEstimateUsageCostForSession(session)) {
275
- skippedUnsupportedSessions += 1;
276
- continue;
277
- }
278
- supportedSessions += 1;
279
- const cost = estimateUsageCostForSession(session, pricingIndex, currentProvider);
280
- totalTokens += cost.totalSessionTokens;
281
- if (!cost.pricing) {
282
- missingPricingSessions += 1;
283
- continue;
284
- }
285
- if (!cost.hasTokenBreakdown) {
286
- missingTokenSessions += 1;
287
- continue;
288
- }
289
- totalCostUsd += cost.estimatedUsd;
290
- estimatedSessions += 1;
291
- estimatedTokens += cost.totalSessionTokens;
292
- if (cost.pricing.source === 'public-catalog') catalogSessions += 1;
293
- else configuredSessions += 1;
294
- }
295
-
296
- const coveragePercent = totalTokens > 0
297
- ? Math.round((estimatedTokens / totalTokens) * 100)
298
- : (estimatedSessions > 0 ? 100 : 0);
299
- return {
300
- totalCostUsd,
301
- estimatedSessions,
302
- totalSessions: supportedSessions,
303
- estimatedTokens,
304
- totalTokens,
305
- coveragePercent,
306
- hasEstimate: estimatedSessions > 0,
307
- configuredSessions,
308
- catalogSessions,
309
- missingPricingSessions,
310
- missingTokenSessions,
311
- skippedUnsupportedSessions
312
- };
313
- }
314
-
315
- function estimateUsageCostForSession(session, pricingIndex, currentProvider) {
316
- const inputTokens = Number.isFinite(Number(session.inputTokens)) ? Math.max(0, Math.floor(Number(session.inputTokens))) : null;
317
- const cachedInputTokens = Number.isFinite(Number(session.cachedInputTokens)) ? Math.max(0, Math.floor(Number(session.cachedInputTokens))) : 0;
318
- const cacheCreationInputTokens = Number.isFinite(Number(session.cacheCreationInputTokens)) ? Math.max(0, Math.floor(Number(session.cacheCreationInputTokens))) : 0;
319
- const outputTokens = Number.isFinite(Number(session.outputTokens)) ? Math.max(0, Math.floor(Number(session.outputTokens))) : null;
320
- const reasoningOutputTokens = Number.isFinite(Number(session.reasoningOutputTokens)) ? Math.max(0, Math.floor(Number(session.reasoningOutputTokens))) : 0;
321
- const billableInputTokens = Math.max(0, (inputTokens || 0) - cachedInputTokens - cacheCreationInputTokens);
322
- const fallbackSessionTokens = billableInputTokens + cachedInputTokens + cacheCreationInputTokens + (outputTokens || 0) + reasoningOutputTokens;
323
- const totalSessionTokens = Number.isFinite(Number(session.totalTokens))
324
- ? Math.max(0, Math.floor(Number(session.totalTokens)))
325
- : fallbackSessionTokens;
326
- const pricing = resolveUsagePricingForSession(session, pricingIndex, currentProvider);
327
- const hasTokenBreakdown = !(inputTokens === null && outputTokens === null && reasoningOutputTokens === 0);
328
- const reasoningRate = pricing
329
- ? ((pricing.reasoningOutput != null ? pricing.reasoningOutput : pricing.output) || 0)
330
- : 0;
331
- const visibleOutputTokens = Math.max(0, (outputTokens || 0) - reasoningOutputTokens);
332
- const estimatedUsd = pricing && hasTokenBreakdown
333
- ? (
334
- ((pricing.input || 0) * billableInputTokens)
335
- + ((pricing.cacheRead || 0) * cachedInputTokens)
336
- + ((pricing.cacheWrite || 0) * cacheCreationInputTokens)
337
- + (reasoningRate * reasoningOutputTokens)
338
- + ((pricing.output || 0) * visibleOutputTokens)
339
- ) / 1000000
340
- : 0;
341
- return {
342
- pricing,
343
- hasTokenBreakdown,
344
- totalSessionTokens,
345
- estimatedUsd
346
- };
347
- }
348
-
349
- export function createSessionComputed() {
350
- return {
351
- isSessionQueryEnabled() {
352
- return isSessionQueryEnabled(this.sessionFilterSource);
353
- },
354
- activeSessionExportKey() {
355
- return this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
356
- },
357
- sortedSessionsList() {
358
- const list = Array.isArray(this.sessionsList) ? this.sessionsList : [];
359
- if (list.length === 0) return [];
360
- const pinnedMap = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
361
- ? this.sessionPinnedMap
362
- : {};
363
- const sortMode = typeof this.sessionSortMode === 'string'
364
- ? this.sessionSortMode.trim().toLowerCase()
365
- : 'time';
366
- if (sortMode !== 'hot' && Object.keys(pinnedMap).length === 0) {
367
- return list;
368
- }
369
- const now = Date.now();
370
- let hasPinned = false;
371
- const decorated = list.map((session, index) => {
372
- const key = session ? this.getSessionExportKey(session) : '';
373
- const rawPinnedAt = key ? pinnedMap[key] : 0;
374
- const pinnedAt = Number.isFinite(Number(rawPinnedAt))
375
- ? Math.floor(Number(rawPinnedAt))
376
- : 0;
377
- const isPinned = pinnedAt > 0;
378
- if (isPinned) {
379
- hasPinned = true;
380
- }
381
- const updatedAtMs = session ? Date.parse(session.updatedAt || '') : NaN;
382
- const safeUpdatedAtMs = Number.isFinite(updatedAtMs) ? updatedAtMs : 0;
383
- const messageCount = session && Number.isFinite(Number(session.messageCount))
384
- ? Math.max(0, Math.floor(Number(session.messageCount)))
385
- : 0;
386
- const totalTokens = session && Number.isFinite(Number(session.totalTokens))
387
- ? Math.max(0, Math.floor(Number(session.totalTokens)))
388
- : 0;
389
- const ageHours = safeUpdatedAtMs > 0 ? Math.max(0, (now - safeUpdatedAtMs) / 3600000) : 1e9;
390
- const activity = Math.sqrt(Math.max(1, totalTokens || (messageCount * 120)));
391
- const hotScore = activity / (1 + (ageHours / 24));
392
- return { session, index, pinnedAt, isPinned, safeUpdatedAtMs, hotScore };
393
- });
394
- if (!hasPinned && sortMode !== 'hot') {
395
- return list;
396
- }
397
- decorated.sort((a, b) => {
398
- if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;
399
- if (a.isPinned && a.pinnedAt !== b.pinnedAt) return b.pinnedAt - a.pinnedAt;
400
- if (sortMode === 'hot') {
401
- if (a.hotScore !== b.hotScore) return b.hotScore - a.hotScore;
402
- }
403
- return a.index - b.index;
404
- });
405
- return decorated.map(item => item.session);
406
- },
407
- visibleSessionsList() {
408
- if (!this.sessionListRenderEnabled) {
409
- return [];
410
- }
411
- const list = Array.isArray(this.sortedSessionsList) ? this.sortedSessionsList : [];
412
- if (list.length === 0) {
413
- return [];
414
- }
415
- const rawVisibleCount = Number(this.sessionListVisibleCount);
416
- const visibleCount = Number.isFinite(rawVisibleCount)
417
- ? Math.max(0, Math.floor(rawVisibleCount))
418
- : 0;
419
- let targetCount = visibleCount > 0 ? Math.min(visibleCount, list.length) : Math.min(list.length, 1);
420
- const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
421
- if (activeKey) {
422
- const activeIndex = list.findIndex((session) => this.getSessionExportKey(session) === activeKey);
423
- if (activeIndex >= 0) {
424
- targetCount = Math.max(targetCount, activeIndex + 1);
425
- }
426
- }
427
- if (targetCount >= list.length) {
428
- return list;
429
- }
430
- return list.slice(0, targetCount);
431
- },
432
- activeSessionVisibleMessages() {
433
- if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
434
- return [];
435
- }
436
- const list = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
437
- const rawCount = Number(this.sessionPreviewVisibleCount);
438
- const visibleCount = Number.isFinite(rawCount)
439
- ? Math.max(0, Math.floor(rawCount))
440
- : 0;
441
- if (visibleCount <= 0) {
442
- const initialBatchSize = Number.isFinite(this.sessionPreviewInitialBatchSize)
443
- ? Math.max(1, Math.floor(this.sessionPreviewInitialBatchSize))
444
- : 12;
445
- return list.slice(0, Math.min(initialBatchSize, list.length));
446
- }
447
- if (visibleCount >= list.length) return list;
448
- return list.slice(0, visibleCount);
449
- },
450
- canLoadMoreSessionMessages() {
451
- if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
452
- return false;
453
- }
454
- const total = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages.length : 0;
455
- const visible = Array.isArray(this.activeSessionVisibleMessages) ? this.activeSessionVisibleMessages.length : 0;
456
- return total > visible;
457
- },
458
- sessionPreviewRemainingCount() {
459
- const total = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages.length : 0;
460
- const visible = Array.isArray(this.activeSessionVisibleMessages) ? this.activeSessionVisibleMessages.length : 0;
461
- return Math.max(0, total - visible);
462
- },
463
- sessionTimelineNodes() {
464
- if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
465
- return [];
466
- }
467
- return buildSessionTimelineNodes(this.activeSessionVisibleMessages, {
468
- getKey: (message, index) => this.getRecordRenderKey(message, index)
469
- });
470
- },
471
- sessionTimelineNodeKeyMap() {
472
- const nodes = Array.isArray(this.sessionTimelineNodes) ? this.sessionTimelineNodes : [];
473
- if (!nodes.length) {
474
- return Object.create(null);
475
- }
476
- const map = Object.create(null);
477
- for (const node of nodes) {
478
- if (!node || !node.key) continue;
479
- map[node.key] = true;
480
- }
481
- return map;
482
- },
483
- sessionTimelineActiveTitle() {
484
- if (!this.sessionTimelineActiveKey) return '';
485
- const nodes = Array.isArray(this.sessionTimelineNodes) ? this.sessionTimelineNodes : [];
486
- const matched = nodes.find(node => node.key === this.sessionTimelineActiveKey);
487
- return matched ? matched.title : '';
488
- },
489
- sessionQueryPlaceholder() {
490
- if (this.isSessionQueryEnabled) {
491
- return typeof this.t === 'function'
492
- ? this.t('sessions.query.placeholder.enabled')
493
- : '关键词检索(支持 Codex/Claude,例:claude code)';
494
- }
495
- return typeof this.t === 'function'
496
- ? this.t('sessions.query.placeholder.disabled')
497
- : '当前来源暂不支持关键词检索';
498
- },
499
- sessionUsageCharts() {
500
- return buildUsageChartGroups(this.sessionsUsageList, {
501
- range: this.sessionsUsageTimeRange
502
- });
503
- },
504
- sessionUsageHeatmap() {
505
- const sessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
506
- ? this.sessionUsageCharts.filteredSessions
507
- : this.sessionsUsageList;
508
- const heatmap = buildUsageHeatmap(sessions, { range: this.sessionsUsageTimeRange });
509
- const t = typeof this.t === 'function' ? this.t : null;
510
- const lang = typeof this.lang === 'string' ? this.lang.trim().toLowerCase() : '';
511
- const weekdayAxis = lang === 'en'
512
- ? ['Mon', '', 'Wed', '', 'Fri', '', '']
513
- : ['周一', '', '周三', '', '周五', '', ''];
514
- const months = lang === 'en'
515
- ? ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
516
- : ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
517
- const windowWeeks = 52;
518
- const allWeeks = Array.isArray(heatmap.weeks) ? heatmap.weeks : [];
519
- const safeWindowWeeks = Math.max(1, Math.min(windowWeeks, allWeeks.length));
520
- const startIndex = Math.max(0, allWeeks.length - safeWindowWeeks);
521
- const displayWeeksRaw = allWeeks.slice(startIndex);
522
- let max = 0;
523
- for (const week of displayWeeksRaw) {
524
- const days = Array.isArray(week.days) ? week.days : [];
525
- for (const cell of days) {
526
- if (cell && cell.isInRange) {
527
- max = Math.max(max, cell.sessionCount || 0);
528
- }
529
- }
530
- }
531
- max = Math.max(1, max);
532
- const dayMs = 24 * 60 * 60 * 1000;
533
- let lastMonth = -1;
534
- const weeks = displayWeeksRaw.map((week) => {
535
- const idx = Number.isFinite(Number(week.weekIndex)) ? Number(week.weekIndex) : 0;
536
- const weekStartMs = (Number.isFinite(Number(heatmap.alignedStart)) ? Number(heatmap.alignedStart) : 0) + (idx * 7 * dayMs);
537
- const month = Number.isFinite(weekStartMs) ? new Date(weekStartMs).getUTCMonth() : -1;
538
- const monthLabel = (month >= 0 && month <= 11 && month !== lastMonth) ? months[month] : '';
539
- if (month >= 0 && month <= 11) {
540
- lastMonth = month;
541
- }
542
- return {
543
- ...week,
544
- monthLabel,
545
- days: (Array.isArray(week.days) ? week.days : []).map((cell) => {
546
- if (!cell) return null;
547
- if (!cell.isInRange) {
548
- return {
549
- ...cell,
550
- level: -1,
551
- title: '',
552
- ariaLabel: ''
553
- };
554
- }
555
- const ratio = cell.sessionCount > 0 ? (cell.sessionCount / max) : 0;
556
- const level = cell.sessionCount <= 0
557
- ? 0
558
- : (ratio <= 0.25 ? 1 : (ratio <= 0.5 ? 2 : (ratio <= 0.75 ? 3 : 4)));
559
- const tokensTitle = formatUsageSummaryNumber(cell.tokenTotal || 0);
560
- const title = t
561
- ? t('usage.heatmap.tooltip', {
562
- date: cell.dateKey,
563
- sessions: cell.sessionCount,
564
- messages: cell.messageCount,
565
- tokens: tokensTitle
566
- })
567
- : `${cell.dateKey} · sessions ${cell.sessionCount} · messages ${cell.messageCount} · tokens ${tokensTitle}`;
568
- const ariaLabel = t
569
- ? t('usage.heatmap.aria', {
570
- date: cell.dateKey,
571
- sessions: cell.sessionCount
572
- })
573
- : `${cell.dateKey} sessions ${cell.sessionCount}`;
574
- return {
575
- ...cell,
576
- level,
577
- title,
578
- ariaLabel
579
- };
580
- })
581
- };
582
- });
583
- return {
584
- ...heatmap,
585
- weeks,
586
- weekdayAxis
587
- };
588
- },
589
- sessionUsageHourlyHeatmap() {
590
- const sessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
591
- ? this.sessionUsageCharts.filteredSessions
592
- : this.sessionsUsageList;
593
- const result = buildUsageHourlyHeatmap(sessions, { range: this.sessionsUsageTimeRange });
594
- const t = typeof this.t === 'function' ? this.t : null;
595
- const lang = typeof this.lang === 'string' ? this.lang.trim().toLowerCase() : '';
596
- const weekdayLabelsZh = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
597
- const weekdayLabelsEn = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
598
- const weekdayLabels = lang === 'en' ? weekdayLabelsEn : weekdayLabelsZh;
599
- const max = Math.max(1, result.maxSessionCount);
600
- const grid = Array.isArray(result.grid) ? result.grid : [];
601
- const rows = grid.map((cells, dayIndex) => ({
602
- weekday: weekdayLabels[dayIndex] || '',
603
- cells: cells.map((cell, hourIndex) => {
604
- const ratio = cell.sessionCount > 0 ? (cell.sessionCount / max) : 0;
605
- const level = cell.sessionCount <= 0
606
- ? 0
607
- : (ratio <= 0.25 ? 1 : (ratio <= 0.5 ? 2 : (ratio <= 0.75 ? 3 : 4)));
608
- const hourLabel = String(hourIndex).padStart(2, '0');
609
- const tooltipText = t
610
- ? t('usage.hourlyHeatmap.tooltip', {
611
- weekday: weekdayLabels[dayIndex],
612
- hour: hourLabel,
613
- sessions: cell.sessionCount,
614
- messages: cell.messageCount,
615
- tokens: (cell.tokenTotal || 0).toLocaleString('en-US')
616
- })
617
- : `${weekdayLabels[dayIndex] || ''} ${hourLabel}:00 · ${cell.sessionCount} sessions · ${cell.messageCount} messages · ${(cell.tokenTotal || 0).toLocaleString('en-US')} tokens`;
618
- return {
619
- hour: hourIndex,
620
- hourLabel,
621
- sessionCount: cell.sessionCount,
622
- messageCount: cell.messageCount,
623
- tokenTotal: cell.tokenTotal,
624
- level,
625
- tooltip: tooltipText
626
- };
627
- })
628
- }));
629
- return {
630
- range: result.range,
631
- rows,
632
- hourLabels: result.hourLabels,
633
- maxSessionCount: result.maxSessionCount
634
- };
635
- },
636
- sessionUsageSummaryCards() {
637
- const summary = this.sessionUsageCharts && this.sessionUsageCharts.summary
638
- ? this.sessionUsageCharts.summary
639
- : { totalSessions: 0, totalMessages: 0, totalTokens: 0, totalContextWindow: 0, activeDurationMs: 0, totalDurationMs: 0, activeDays: 0, avgMessagesPerSession: 0, busiestDay: null, busiestHour: null };
640
- const filteredUsageSessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
641
- ? this.sessionUsageCharts.filteredSessions
642
- : this.sessionsUsageList;
643
- const t = typeof this.t === 'function' ? this.t : null;
644
- const usageRangeLabel = formatUsageRangeLabel(this.sessionsUsageTimeRange, t);
645
- const estimatedCost = estimateUsageCostSummary(
646
- filteredUsageSessions,
647
- this.providersList,
648
- this.currentProvider
649
- );
650
- const noneLabel = t ? t('common.none') : '暂无';
651
- const estimatedCostPrefix = estimatedCost.skippedUnsupportedSessions > 0
652
- ? (t ? t('usage.estimatedCost.note.excludesClaudePrefix') : '暂不含 Claude,')
653
- : '';
654
- const estimatedCostMethod = estimatedCost.catalogSessions > 0
655
- ? (estimatedCost.configuredSessions > 0
656
- ? (t ? t('usage.estimatedCost.method.configuredAndCatalog') : '按已配置单价 + 公开模型目录估算')
657
- : (t ? t('usage.estimatedCost.method.catalog') : '按公开模型目录估算'))
658
- : (t ? t('usage.estimatedCost.method.configured') : '按已配置单价估算');
659
- const estimatedCostTitle = estimatedCost.hasEstimate
660
- ? (t ? t('usage.estimatedCost.detail.estimate', {
661
- prefix: estimatedCostPrefix,
662
- method: estimatedCostMethod,
663
- estimate: formatUsageEstimatedCost(estimatedCost.totalCostUsd, { precise: true }),
664
- covered: estimatedCost.estimatedSessions,
665
- total: estimatedCost.totalSessions,
666
- percent: estimatedCost.coveragePercent
667
- }) : `${estimatedCostPrefix}${estimatedCostMethod},估算 ${formatUsageEstimatedCost(estimatedCost.totalCostUsd, { precise: true })},覆盖 ${estimatedCost.estimatedSessions}/${estimatedCost.totalSessions} 个会话,约 ${estimatedCost.coveragePercent}% token`)
668
- : (t ? t('usage.estimatedCost.detail.missing', { prefix: estimatedCostPrefix }) : `${estimatedCostPrefix}缺少可匹配的模型单价或 token 拆分。请先补 models.cost,或确认会话已记录 input/output token。`);
669
- return [
670
- { key: 'sessions', label: t ? t('usage.summary.sessions') : '总会话数', value: formatUsageSummaryNumber(summary.totalSessions || 0) },
671
- { key: 'messages', label: t ? t('usage.summary.messages') : '总消息数', value: formatUsageSummaryNumber(summary.totalMessages || 0) },
672
- {
673
- key: 'tokens',
674
- label: t ? t('usage.summary.tokens') : '总 token 数',
675
- value: formatCompactUsageSummaryNumber(summary.totalTokens || 0),
676
- title: formatUsageSummaryNumber(summary.totalTokens || 0)
677
- },
678
- {
679
- key: 'context-window',
680
- label: t ? t('usage.summary.contextWindow') : '总上下文数',
681
- value: formatCompactUsageSummaryNumber(summary.totalContextWindow || 0),
682
- title: formatUsageSummaryNumber(summary.totalContextWindow || 0)
683
- },
684
- {
685
- key: 'estimated-cost',
686
- label: t ? t('usage.summary.estimatedCost', { range: usageRangeLabel }) : `预估费用 · ${usageRangeLabel}`,
687
- value: estimatedCost.hasEstimate ? formatUsageEstimatedCost(estimatedCost.totalCostUsd) : '0',
688
- title: estimatedCostTitle
689
- },
690
- {
691
- key: 'active-duration',
692
- label: t ? t('usage.summary.activeDuration') : '活跃时长',
693
- value: formatUsageDuration(summary.activeDurationMs || 0, { compact: true, lang: this.lang }),
694
- title: t
695
- ? t('usage.summary.activeDuration.title', {
696
- value: formatUsageDuration(summary.activeDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })
697
- })
698
- : `累计会话跨度 ${formatUsageDuration(summary.activeDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })}`
699
- },
700
- {
701
- key: 'total-duration',
702
- label: t ? t('usage.summary.totalDuration') : '总时长',
703
- value: formatUsageDuration(summary.totalDurationMs || 0, { compact: true, lang: this.lang }),
704
- title: t
705
- ? t('usage.summary.totalDuration.title', {
706
- value: formatUsageDuration(summary.totalDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })
707
- })
708
- : `整体时间跨度 ${formatUsageDuration(summary.totalDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })}`
709
- },
710
- { key: 'days', label: t ? t('usage.summary.activeDays') : '活跃天数', value: formatUsageSummaryNumber(summary.activeDays || 0) },
711
- { key: 'avg-messages', label: t ? t('usage.summary.avgMessagesPerSession') : '平均每会话消息', value: summary.avgMessagesPerSession || 0 },
712
- {
713
- key: 'busiest-day',
714
- label: t ? t('usage.summary.busiestDay') : '最忙日',
715
- value: summary.busiestDay && summary.busiestDay.totalSessions > 0
716
- ? `${summary.busiestDay.label} · ${summary.busiestDay.totalSessions}`
717
- : noneLabel
718
- },
719
- {
720
- key: 'busiest-hour',
721
- label: t ? t('usage.summary.busiestHour') : '高峰时段',
722
- value: summary.busiestHour && summary.busiestHour.count > 0
723
- ? `${summary.busiestHour.label} · ${summary.busiestHour.count}`
724
- : noneLabel
725
- }
726
- ];
727
- },
728
-
729
- usageCurrentSessionStats() {
730
- const summary = this.sessionUsageCharts && this.sessionUsageCharts.summary
731
- ? this.sessionUsageCharts.summary
732
- : null;
733
- if (!summary) return null;
734
- const t = typeof this.t === 'function' ? this.t : null;
735
- return {
736
- apiDurationLabel: formatUsageDuration(summary.activeDurationMs || 0, { compact: true, lang: this.lang }),
737
- totalDurationLabel: formatUsageDuration(summary.totalDurationMs || 0, { compact: true, lang: this.lang }),
738
- tokenLabel: formatCompactUsageSummaryNumber(summary.totalTokens || 0),
739
- label: t ? t('usage.currentSession.title') : '当前会话',
740
- apiDurationText: t ? t('usage.currentSession.apiDuration') : 'API时长',
741
- totalDurationText: t ? t('usage.currentSession.totalDuration') : '总时长',
742
- tokenText: t ? t('usage.currentSession.tokens') : 'Token'
743
- };
744
- },
745
-
746
- sessionUsageDaily() {
747
- const baseBuckets = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.buckets)
748
- ? this.sessionUsageCharts.buckets
749
- : [];
750
- const pricingIndex = buildUsagePricingIndex(this.providersList);
751
- const compareEnabled = this.sessionsUsageCompareEnabled === true && this.sessionsUsageTimeRange !== 'all';
752
- const sessions = compareEnabled
753
- ? this.sessionsUsageList
754
- : (this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
755
- ? this.sessionUsageCharts.filteredSessions
756
- : this.sessionsUsageList);
757
- const rangeDays = this.sessionsUsageTimeRange === '30d' ? 30 : 7;
758
- const dayMs = 24 * 60 * 60 * 1000;
759
- const byDay = new Map();
760
-
761
- for (const bucket of baseBuckets) {
762
- if (!bucket || !bucket.key) continue;
763
- byDay.set(bucket.key, {
764
- key: bucket.key,
765
- label: bucket.label || bucket.key.slice(5),
766
- sessionCount: 0,
767
- messageCount: 0,
768
- tokenTotal: 0,
769
- estimatedCostUsd: 0,
770
- estimatedSessions: 0,
771
- hasCostEstimate: false
772
- });
773
- if (compareEnabled) {
774
- const baseMs = Date.parse(`${bucket.key}T00:00:00.000Z`);
775
- if (Number.isFinite(baseMs)) {
776
- const prevKey = new Date(baseMs - (rangeDays * dayMs)).toISOString().slice(0, 10);
777
- if (!byDay.has(prevKey)) {
778
- byDay.set(prevKey, {
779
- key: prevKey,
780
- label: prevKey.slice(5),
781
- sessionCount: 0,
782
- messageCount: 0,
783
- tokenTotal: 0,
784
- estimatedCostUsd: 0,
785
- estimatedSessions: 0,
786
- hasCostEstimate: false
787
- });
788
- }
789
- }
790
- }
791
- }
792
-
793
- for (const session of (Array.isArray(sessions) ? sessions : [])) {
794
- if (!session || typeof session !== 'object') continue;
795
- const updatedAtMs = Date.parse(session.updatedAt || '');
796
- if (!Number.isFinite(updatedAtMs)) continue;
797
- const dayKey = new Date(updatedAtMs).toISOString().slice(0, 10);
798
- const row = byDay.get(dayKey);
799
- if (!row) continue;
800
-
801
- const messageCount = Number.isFinite(Number(session.messageCount))
802
- ? Math.max(0, Math.floor(Number(session.messageCount)))
803
- : 0;
804
- const tokenTotal = Number.isFinite(Number(session.totalTokens))
805
- ? Math.max(0, Math.floor(Number(session.totalTokens)))
806
- : 0;
807
- row.sessionCount += 1;
808
- row.messageCount += messageCount;
809
- row.tokenTotal += tokenTotal;
810
-
811
- if (shouldEstimateUsageCostForSession(session)) {
812
- const cost = estimateUsageCostForSession(session, pricingIndex, this.currentProvider);
813
- if (cost.pricing && cost.hasTokenBreakdown) {
814
- row.estimatedCostUsd += cost.estimatedUsd;
815
- row.estimatedSessions += 1;
816
- row.hasCostEstimate = true;
817
- }
818
- }
819
- }
820
-
821
- const currentKeys = baseBuckets.map((bucket) => bucket && bucket.key).filter(Boolean);
822
- const rows = currentKeys
823
- .map((key) => byDay.get(key))
824
- .filter(Boolean)
825
- .sort((a, b) => b.key.localeCompare(a.key, 'en-US'));
826
- const rowsWithCompare = rows.map((row) => {
827
- if (!compareEnabled) {
828
- return { ...row, compareEnabled: false, prevKey: '', prevTokenTotal: 0, prevCostUsd: 0 };
829
- }
830
- const baseMs = Date.parse(`${row.key}T00:00:00.000Z`);
831
- const prevKey = Number.isFinite(baseMs)
832
- ? new Date(baseMs - (rangeDays * dayMs)).toISOString().slice(0, 10)
833
- : '';
834
- const prevRow = prevKey ? byDay.get(prevKey) : null;
835
- return {
836
- ...row,
837
- compareEnabled: true,
838
- prevKey,
839
- prevTokenTotal: prevRow ? prevRow.tokenTotal : 0,
840
- prevCostUsd: prevRow ? prevRow.estimatedCostUsd : 0
841
- };
842
- });
843
- const maxTokens = rowsWithCompare.reduce((max, item) => Math.max(max, item.tokenTotal, item.prevTokenTotal || 0), 0);
844
- const maxCost = rowsWithCompare.reduce((max, item) => Math.max(max, item.estimatedCostUsd, item.prevCostUsd || 0), 0);
845
-
846
- return {
847
- rows: rowsWithCompare.map((row) => ({
848
- ...row,
849
- tokenLabel: formatCompactUsageSummaryNumber(row.tokenTotal),
850
- tokenTitle: formatUsageSummaryNumber(row.tokenTotal),
851
- tokenPercent: maxTokens > 0 ? Math.round((row.tokenTotal / maxTokens) * 1000) / 10 : 0,
852
- prevTokenPercent: row.compareEnabled && maxTokens > 0 ? Math.round(((row.prevTokenTotal || 0) / maxTokens) * 1000) / 10 : 0,
853
- prevTokenTitle: row.compareEnabled ? formatUsageSummaryNumber(row.prevTokenTotal || 0) : '',
854
- costLabel: row.hasCostEstimate ? formatUsageEstimatedCost(row.estimatedCostUsd) : '0',
855
- costTitle: row.hasCostEstimate ? formatUsageEstimatedCost(row.estimatedCostUsd, { precise: true }) : '0',
856
- costPercent: maxCost > 0 ? Math.round((row.estimatedCostUsd / maxCost) * 1000) / 10 : 0,
857
- prevCostPercent: row.compareEnabled && maxCost > 0 ? Math.round(((row.prevCostUsd || 0) / maxCost) * 1000) / 10 : 0,
858
- prevCostTitle: row.compareEnabled ? formatUsageEstimatedCost(row.prevCostUsd || 0, { precise: true }) : ''
859
- })),
860
- maxTokens,
861
- maxCost
862
- };
863
- },
864
-
865
- sessionUsageDailyTableRows() {
866
- const daily = this.sessionUsageDaily && typeof this.sessionUsageDaily === 'object'
867
- ? this.sessionUsageDaily
868
- : null;
869
- return daily && Array.isArray(daily.rows) ? daily.rows : [];
870
- },
871
-
872
- sessionsUsageSelectedDaySummary() {
873
- const dayKey = typeof this.sessionsUsageSelectedDayKey === 'string' ? this.sessionsUsageSelectedDayKey.trim() : '';
874
- if (!dayKey) return null;
875
- const sessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
876
- ? this.sessionUsageCharts.filteredSessions
877
- : this.sessionsUsageList;
878
- const pricingIndex = buildUsagePricingIndex(this.providersList);
879
- const compareEnabled = this.sessionsUsageCompareEnabled === true && this.sessionsUsageTimeRange !== 'all';
880
- const rangeDays = this.sessionsUsageTimeRange === '30d' ? 30 : 7;
881
- const dayMs = 24 * 60 * 60 * 1000;
882
- const baseMs = Date.parse(`${dayKey}T00:00:00.000Z`);
883
- const prevKey = compareEnabled && Number.isFinite(baseMs)
884
- ? new Date(baseMs - (rangeDays * dayMs)).toISOString().slice(0, 10)
885
- : '';
886
- let sessionCount = 0;
887
- let messageCount = 0;
888
- let tokenTotal = 0;
889
- let estimatedCostUsd = 0;
890
- let hasCostEstimate = false;
891
- let prevTokenTotal = 0;
892
- let prevEstimatedCostUsd = 0;
893
- let prevHasCostEstimate = false;
894
- const modelMap = new Map();
895
- const sessionRows = [];
896
- for (const session of (Array.isArray(sessions) ? sessions : [])) {
897
- if (!session || typeof session !== 'object') continue;
898
- const updatedAtMs = Date.parse(session.updatedAt || '');
899
- if (!Number.isFinite(updatedAtMs)) continue;
900
- const key = new Date(updatedAtMs).toISOString().slice(0, 10);
901
- const isCurrent = key === dayKey;
902
- const isPrev = !!prevKey && key === prevKey;
903
- if (!isCurrent && !isPrev) continue;
904
- const msgCount = Number.isFinite(Number(session.messageCount))
905
- ? Math.max(0, Math.floor(Number(session.messageCount)))
906
- : 0;
907
- const sessionTokens = Number.isFinite(Number(session.totalTokens))
908
- ? Math.max(0, Math.floor(Number(session.totalTokens)))
909
- : 0;
910
- if (isCurrent) {
911
- sessionCount += 1;
912
- messageCount += msgCount;
913
- tokenTotal += sessionTokens;
914
- } else if (isPrev) {
915
- prevTokenTotal += sessionTokens;
916
- }
917
- if (shouldEstimateUsageCostForSession(session)) {
918
- const cost = estimateUsageCostForSession(session, pricingIndex, this.currentProvider);
919
- if (cost.pricing && cost.hasTokenBreakdown) {
920
- if (isCurrent) {
921
- estimatedCostUsd += cost.estimatedUsd;
922
- hasCostEstimate = true;
923
- } else if (isPrev) {
924
- prevEstimatedCostUsd += cost.estimatedUsd;
925
- prevHasCostEstimate = true;
926
- }
927
- }
928
- }
929
- const model = typeof session.model === 'string' ? session.model.trim() : '';
930
- if (isCurrent && model) {
931
- modelMap.set(model, (modelMap.get(model) || 0) + 1);
932
- }
933
- const title = typeof session.title === 'string' && session.title.trim()
934
- ? session.title.trim()
935
- : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
936
- if (isCurrent) {
937
- sessionRows.push({
938
- key: this.getSessionExportKey(session) || `${title}:${sessionCount}`,
939
- title,
940
- messageCount: msgCount
941
- });
942
- }
943
- }
944
- sessionRows.sort((a, b) => b.messageCount - a.messageCount);
945
- const lang = typeof this.lang === 'string' ? this.lang.trim().toLowerCase() : '';
946
- const suffix = lang === 'en' ? 'msgs' : '条';
947
- const topSessions = sessionRows.slice(0, 8).map((item) => ({
948
- ...item,
949
- messageCountLabel: `${item.messageCount} ${suffix}`
950
- }));
951
- const topModels = [...modelMap.entries()]
952
- .sort((a, b) => b[1] - a[1])
953
- .slice(0, 6)
954
- .map(([model, count]) => ({
955
- key: model,
956
- label: `${model} · ${count}`
957
- }));
958
- return {
959
- dayKey,
960
- compareEnabled,
961
- prevKey,
962
- sessionCount,
963
- messageCount,
964
- tokenTotal,
965
- tokenLabel: formatUsageSummaryNumber(tokenTotal),
966
- costLabel: hasCostEstimate ? formatUsageEstimatedCost(estimatedCostUsd) : '0',
967
- prevTokenTotal,
968
- prevTokenLabel: compareEnabled ? formatUsageSummaryNumber(prevTokenTotal) : '0',
969
- deltaTokenLabel: compareEnabled ? formatSignedUsageSummaryNumber(tokenTotal - prevTokenTotal) : '0',
970
- prevCostLabel: compareEnabled ? (prevHasCostEstimate ? formatUsageEstimatedCost(prevEstimatedCostUsd) : '0') : '0',
971
- deltaCostLabel: compareEnabled ? formatSignedUsageEstimatedCost(estimatedCostUsd - prevEstimatedCostUsd, { precise: true }) : '0',
972
- topSessions,
973
- topModels
974
- };
975
- },
976
-
977
- visibleSessionTrashItems() {
978
- const items = Array.isArray(this.sessionTrashItems) ? this.sessionTrashItems : [];
979
- const visibleCount = Number(this.sessionTrashVisibleCount);
980
- const safeVisibleCount = Number.isFinite(visibleCount) && visibleCount > 0
981
- ? Math.floor(visibleCount)
982
- : SESSION_TRASH_PAGE_SIZE;
983
- return items.slice(0, safeVisibleCount);
984
- },
985
- sessionTrashHasMoreItems() {
986
- return this.visibleSessionTrashItems.length < this.sessionTrashCount;
987
- },
988
- sessionTrashHiddenCount() {
989
- return Math.max(0, this.sessionTrashCount - this.visibleSessionTrashItems.length);
990
- },
991
- sessionTrashCount() {
992
- const totalCount = Number(this.sessionTrashTotalCount);
993
- if (Number.isFinite(totalCount) && totalCount >= 0) {
994
- return Math.max(0, Math.floor(totalCount));
995
- }
996
- return Array.isArray(this.sessionTrashItems) ? this.sessionTrashItems.length : 0;
997
- }
998
- };
999
- }
1
+ import {
2
+ buildSessionTimelineNodes,
3
+ buildUsageChartGroups,
4
+ buildUsageHeatmap,
5
+ buildUsageHourlyHeatmap,
6
+ isSessionQueryEnabled
7
+ } from '../logic.mjs';
8
+ import { SESSION_TRASH_PAGE_SIZE } from './app.constants.mjs';
9
+
10
+ function formatUsageSummaryNumber(value) {
11
+ const numeric = Number(value);
12
+ if (!Number.isFinite(numeric) || numeric < 0) {
13
+ return '0';
14
+ }
15
+ return Math.floor(numeric).toLocaleString('en-US');
16
+ }
17
+
18
+ function formatCompactUsageSummaryNumber(value) {
19
+ const numeric = Number(value);
20
+ if (!Number.isFinite(numeric) || numeric < 0) {
21
+ return '0';
22
+ }
23
+ return new Intl.NumberFormat('en-US', {
24
+ notation: 'compact',
25
+ compactDisplay: 'short',
26
+ maximumFractionDigits: 1
27
+ }).format(Math.floor(numeric));
28
+ }
29
+
30
+ function readUsageCostNumber(value) {
31
+ const numeric = Number(value);
32
+ if (!Number.isFinite(numeric) || numeric < 0) {
33
+ return null;
34
+ }
35
+ return numeric;
36
+ }
37
+
38
+ function formatUsageEstimatedCost(value, options = {}) {
39
+ const numeric = Number(value);
40
+ if (!Number.isFinite(numeric) || numeric <= 0) {
41
+ return '$0.00';
42
+ }
43
+ const precise = options && options.precise === true;
44
+ if (numeric < 0.0001) {
45
+ return '<$0.0001';
46
+ }
47
+ let fractionDigits = 2;
48
+ if (numeric < 1) {
49
+ fractionDigits = precise ? 6 : 4;
50
+ } else if (numeric >= 100) {
51
+ fractionDigits = 0;
52
+ }
53
+ return new Intl.NumberFormat('en-US', {
54
+ style: 'currency',
55
+ currency: 'USD',
56
+ minimumFractionDigits: fractionDigits,
57
+ maximumFractionDigits: fractionDigits
58
+ }).format(numeric);
59
+ }
60
+
61
+ function formatSignedUsageSummaryNumber(value) {
62
+ const numeric = Number(value);
63
+ if (!Number.isFinite(numeric) || numeric === 0) {
64
+ return '0';
65
+ }
66
+ const sign = numeric > 0 ? '+' : '-';
67
+ return `${sign}${formatUsageSummaryNumber(Math.abs(numeric))}`;
68
+ }
69
+
70
+ function formatSignedUsageEstimatedCost(value, options = {}) {
71
+ const numeric = Number(value);
72
+ if (!Number.isFinite(numeric) || numeric === 0) {
73
+ return '$0.00';
74
+ }
75
+ const sign = numeric > 0 ? '+' : '-';
76
+ return `${sign}${formatUsageEstimatedCost(Math.abs(numeric), options)}`;
77
+ }
78
+
79
+ function formatUsageRangeLabel(range, t) {
80
+ const normalized = typeof range === 'string' ? range.trim().toLowerCase() : '7d';
81
+ if (typeof t === 'function') {
82
+ if (normalized === '30d') return t('usage.range.30d');
83
+ if (normalized === 'all') return t('usage.range.all');
84
+ return t('usage.range.7d');
85
+ }
86
+ if (normalized === '30d') return '近 30 天';
87
+ if (normalized === 'all') return '全部';
88
+ return '近 7 天';
89
+ }
90
+
91
+ function formatUsageDuration(value, options = {}) {
92
+ const normalizedLang = typeof options.lang === 'string' ? options.lang.trim().toLowerCase() : '';
93
+ const isEn = normalizedLang === 'en';
94
+ const numeric = Number(value);
95
+ if (!Number.isFinite(numeric) || numeric <= 0) {
96
+ return isEn ? '0m' : '0分';
97
+ }
98
+ const totalMinutes = Math.floor(numeric / 60000);
99
+ if (totalMinutes <= 0) {
100
+ return isEn ? '<1m' : '<1分';
101
+ }
102
+ const maxParts = Number.isFinite(Number(options.maxParts))
103
+ ? Math.max(1, Math.floor(Number(options.maxParts)))
104
+ : 2;
105
+ const compact = options.compact !== false;
106
+ const units = compact
107
+ ? (
108
+ isEn
109
+ ? [
110
+ { label: 'd', value: 24 * 60 },
111
+ { label: 'h', value: 60 },
112
+ { label: 'm', value: 1 }
113
+ ]
114
+ : [
115
+ { label: '天', value: 24 * 60 },
116
+ { label: '时', value: 60 },
117
+ { label: '分', value: 1 }
118
+ ]
119
+ )
120
+ : (
121
+ isEn
122
+ ? [
123
+ { label: 'day', value: 24 * 60 },
124
+ { label: 'hr', value: 60 },
125
+ { label: 'min', value: 1 }
126
+ ]
127
+ : [
128
+ { label: '天', value: 24 * 60 },
129
+ { label: '小时', value: 60 },
130
+ { label: '分', value: 1 }
131
+ ]
132
+ );
133
+ let remainingMinutes = totalMinutes;
134
+ const parts = [];
135
+ for (const unit of units) {
136
+ if (remainingMinutes < unit.value && unit.value !== 1) {
137
+ continue;
138
+ }
139
+ const count = unit.value === 1 ? remainingMinutes : Math.floor(remainingMinutes / unit.value);
140
+ if (count <= 0) {
141
+ continue;
142
+ }
143
+ parts.push(compact ? `${count}${unit.label}` : (isEn ? `${count} ${unit.label}` : `${count}${unit.label}`));
144
+ remainingMinutes -= count * unit.value;
145
+ if (parts.length >= maxParts) {
146
+ break;
147
+ }
148
+ }
149
+ return parts.length ? parts.join(compact ? '' : ' ') : (isEn ? '0m' : '0分');
150
+ }
151
+
152
+ const KNOWN_USAGE_MODEL_PRICING = Object.freeze({
153
+ 'gpt-5.4': Object.freeze({ input: 2.5, output: 15, cacheRead: 0.25, cacheWrite: 0 }),
154
+ 'gpt-5.4-mini': Object.freeze({ input: 0.75, output: 4.5, cacheRead: 0.075, cacheWrite: 0 }),
155
+ 'gpt-5.3-codex': Object.freeze({ input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 }),
156
+ 'gpt-5.2-codex': Object.freeze({ input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 }),
157
+ 'claude-opus-4-6': Object.freeze({ input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75, reasoningOutput: 75 }),
158
+ 'claude-opus-4-7': Object.freeze({ input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75, reasoningOutput: 75 }),
159
+ 'claude-sonnet-4-6': Object.freeze({ input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75, reasoningOutput: 15 }),
160
+ 'claude-haiku-4-5': Object.freeze({ input: 0.8, output: 4, cacheRead: 0.08, cacheWrite: 1, reasoningOutput: 4 }),
161
+ 'claude-3-5-sonnet': Object.freeze({ input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75, reasoningOutput: 15 }),
162
+ 'claude-3-5-haiku': Object.freeze({ input: 0.8, output: 4, cacheRead: 0.08, cacheWrite: 1, reasoningOutput: 4 }),
163
+ 'claude-3-opus': Object.freeze({ input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75, reasoningOutput: 75 })
164
+ });
165
+
166
+ function createUsagePricingEntry(pricing, source) {
167
+ const resolvedSource = typeof source === 'string' && source.trim() ? source.trim() : 'provider-config';
168
+ return {
169
+ input: readUsageCostNumber(pricing && pricing.input),
170
+ output: readUsageCostNumber(pricing && pricing.output),
171
+ reasoningOutput: readUsageCostNumber(
172
+ pricing && (pricing.reasoningOutput != null ? pricing.reasoningOutput : pricing.reasoning)
173
+ ),
174
+ cacheRead: readUsageCostNumber(pricing && pricing.cacheRead),
175
+ cacheWrite: readUsageCostNumber(pricing && pricing.cacheWrite),
176
+ source: resolvedSource
177
+ };
178
+ }
179
+
180
+ function buildUsagePricingIndex(providersList = []) {
181
+ const byProvider = new Map();
182
+ const byModel = new Map();
183
+ const knownByModel = new Map();
184
+ const list = Array.isArray(providersList) ? providersList : [];
185
+ for (const provider of list) {
186
+ if (!provider || typeof provider !== 'object') continue;
187
+ const providerName = typeof provider.name === 'string' ? provider.name.trim() : '';
188
+ const models = Array.isArray(provider.models) ? provider.models : [];
189
+ const providerMap = new Map();
190
+ for (const model of models) {
191
+ if (!model || typeof model !== 'object') continue;
192
+ const modelId = typeof model.id === 'string' ? model.id.trim() : '';
193
+ if (!modelId) continue;
194
+ const pricing = createUsagePricingEntry(
195
+ model.cost && typeof model.cost === 'object' && !Array.isArray(model.cost)
196
+ ? model.cost
197
+ : null,
198
+ 'provider-config'
199
+ );
200
+ const hasKnownRate = [pricing.input, pricing.output, pricing.reasoningOutput, pricing.cacheRead, pricing.cacheWrite]
201
+ .some((value) => value !== null);
202
+ if (!hasKnownRate) continue;
203
+ providerMap.set(modelId, pricing);
204
+ const modelMatches = byModel.get(modelId) || [];
205
+ modelMatches.push({ provider: providerName, pricing });
206
+ byModel.set(modelId, modelMatches);
207
+ }
208
+ if (providerName && providerMap.size) {
209
+ byProvider.set(providerName, providerMap);
210
+ }
211
+ }
212
+ for (const [modelId, pricing] of Object.entries(KNOWN_USAGE_MODEL_PRICING)) {
213
+ const normalizedModelId = typeof modelId === 'string' ? modelId.trim() : '';
214
+ if (!normalizedModelId || byModel.has(normalizedModelId)) {
215
+ continue;
216
+ }
217
+ knownByModel.set(normalizedModelId, createUsagePricingEntry(pricing, 'public-catalog'));
218
+ }
219
+ return { byProvider, byModel, knownByModel };
220
+ }
221
+
222
+ function resolveUsagePricingForSession(session, pricingIndex, fallbackProvider = '') {
223
+ if (!session || typeof session !== 'object' || !pricingIndex || typeof pricingIndex !== 'object') {
224
+ return null;
225
+ }
226
+ const model = typeof session.model === 'string' ? session.model.trim() : '';
227
+ if (!model) return null;
228
+ const provider = typeof session.provider === 'string' ? session.provider.trim() : '';
229
+ const effectiveProvider = provider || fallbackProvider;
230
+ if (effectiveProvider) {
231
+ const providerMap = pricingIndex.byProvider instanceof Map ? pricingIndex.byProvider.get(effectiveProvider) : null;
232
+ if (providerMap instanceof Map && providerMap.has(model)) {
233
+ return providerMap.get(model);
234
+ }
235
+ }
236
+ const modelMatches = pricingIndex.byModel instanceof Map ? pricingIndex.byModel.get(model) : null;
237
+ if (Array.isArray(modelMatches) && modelMatches.length === 1) {
238
+ return modelMatches[0].pricing;
239
+ }
240
+ const knownPricing = pricingIndex.knownByModel instanceof Map ? pricingIndex.knownByModel.get(model) : null;
241
+ if (knownPricing) {
242
+ return knownPricing;
243
+ }
244
+ const strippedModel = model.replace(/-\d{8}(?=[-_]|$)/, '');
245
+ if (strippedModel !== model) {
246
+ const strippedKnown = pricingIndex.knownByModel instanceof Map ? pricingIndex.knownByModel.get(strippedModel) : null;
247
+ if (strippedKnown) {
248
+ return strippedKnown;
249
+ }
250
+ }
251
+ return null;
252
+ }
253
+
254
+ function shouldEstimateUsageCostForSession() {
255
+ return true;
256
+ }
257
+
258
+ function estimateUsageCostSummary(sessions, providersList, currentProvider) {
259
+ const list = Array.isArray(sessions) ? sessions : [];
260
+ const pricingIndex = buildUsagePricingIndex(providersList);
261
+ let totalCostUsd = 0;
262
+ let estimatedSessions = 0;
263
+ let totalTokens = 0;
264
+ let estimatedTokens = 0;
265
+ let configuredSessions = 0;
266
+ let catalogSessions = 0;
267
+ let missingPricingSessions = 0;
268
+ let missingTokenSessions = 0;
269
+ let supportedSessions = 0;
270
+ let skippedUnsupportedSessions = 0;
271
+
272
+ for (const session of list) {
273
+ if (!session || typeof session !== 'object') continue;
274
+ if (!shouldEstimateUsageCostForSession(session)) {
275
+ skippedUnsupportedSessions += 1;
276
+ continue;
277
+ }
278
+ supportedSessions += 1;
279
+ const cost = estimateUsageCostForSession(session, pricingIndex, currentProvider);
280
+ totalTokens += cost.totalSessionTokens;
281
+ if (!cost.pricing) {
282
+ missingPricingSessions += 1;
283
+ continue;
284
+ }
285
+ if (!cost.hasTokenBreakdown) {
286
+ missingTokenSessions += 1;
287
+ continue;
288
+ }
289
+ totalCostUsd += cost.estimatedUsd;
290
+ estimatedSessions += 1;
291
+ estimatedTokens += cost.totalSessionTokens;
292
+ if (cost.pricing.source === 'public-catalog') catalogSessions += 1;
293
+ else configuredSessions += 1;
294
+ }
295
+
296
+ const coveragePercent = totalTokens > 0
297
+ ? Math.round((estimatedTokens / totalTokens) * 100)
298
+ : (estimatedSessions > 0 ? 100 : 0);
299
+ return {
300
+ totalCostUsd,
301
+ estimatedSessions,
302
+ totalSessions: supportedSessions,
303
+ estimatedTokens,
304
+ totalTokens,
305
+ coveragePercent,
306
+ hasEstimate: estimatedSessions > 0,
307
+ configuredSessions,
308
+ catalogSessions,
309
+ missingPricingSessions,
310
+ missingTokenSessions,
311
+ skippedUnsupportedSessions
312
+ };
313
+ }
314
+
315
+ function estimateUsageCostForSession(session, pricingIndex, currentProvider) {
316
+ const inputTokens = Number.isFinite(Number(session.inputTokens)) ? Math.max(0, Math.floor(Number(session.inputTokens))) : null;
317
+ const cachedInputTokens = Number.isFinite(Number(session.cachedInputTokens)) ? Math.max(0, Math.floor(Number(session.cachedInputTokens))) : 0;
318
+ const cacheCreationInputTokens = Number.isFinite(Number(session.cacheCreationInputTokens)) ? Math.max(0, Math.floor(Number(session.cacheCreationInputTokens))) : 0;
319
+ const outputTokens = Number.isFinite(Number(session.outputTokens)) ? Math.max(0, Math.floor(Number(session.outputTokens))) : null;
320
+ const reasoningOutputTokens = Number.isFinite(Number(session.reasoningOutputTokens)) ? Math.max(0, Math.floor(Number(session.reasoningOutputTokens))) : 0;
321
+ const billableInputTokens = Math.max(0, (inputTokens || 0) - cachedInputTokens - cacheCreationInputTokens);
322
+ const fallbackSessionTokens = billableInputTokens + cachedInputTokens + cacheCreationInputTokens + (outputTokens || 0) + reasoningOutputTokens;
323
+ const totalSessionTokens = Number.isFinite(Number(session.totalTokens))
324
+ ? Math.max(0, Math.floor(Number(session.totalTokens)))
325
+ : fallbackSessionTokens;
326
+ const pricing = resolveUsagePricingForSession(session, pricingIndex, currentProvider);
327
+ const hasTokenBreakdown = !(inputTokens === null && outputTokens === null && reasoningOutputTokens === 0);
328
+ const reasoningRate = pricing
329
+ ? ((pricing.reasoningOutput != null ? pricing.reasoningOutput : pricing.output) || 0)
330
+ : 0;
331
+ const visibleOutputTokens = Math.max(0, (outputTokens || 0) - reasoningOutputTokens);
332
+ const estimatedUsd = pricing && hasTokenBreakdown
333
+ ? (
334
+ ((pricing.input || 0) * billableInputTokens)
335
+ + ((pricing.cacheRead || 0) * cachedInputTokens)
336
+ + ((pricing.cacheWrite || 0) * cacheCreationInputTokens)
337
+ + (reasoningRate * reasoningOutputTokens)
338
+ + ((pricing.output || 0) * visibleOutputTokens)
339
+ ) / 1000000
340
+ : 0;
341
+ return {
342
+ pricing,
343
+ hasTokenBreakdown,
344
+ totalSessionTokens,
345
+ estimatedUsd
346
+ };
347
+ }
348
+
349
+ export function createSessionComputed() {
350
+ return {
351
+ isSessionQueryEnabled() {
352
+ return isSessionQueryEnabled(this.sessionFilterSource);
353
+ },
354
+ activeSessionExportKey() {
355
+ return this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
356
+ },
357
+ sortedSessionsList() {
358
+ const list = Array.isArray(this.sessionsList) ? this.sessionsList : [];
359
+ if (list.length === 0) return [];
360
+ const pinnedMap = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
361
+ ? this.sessionPinnedMap
362
+ : {};
363
+ const sortMode = typeof this.sessionSortMode === 'string'
364
+ ? this.sessionSortMode.trim().toLowerCase()
365
+ : 'time';
366
+ if (sortMode !== 'hot' && Object.keys(pinnedMap).length === 0) {
367
+ return list;
368
+ }
369
+ const now = Date.now();
370
+ let hasPinned = false;
371
+ const decorated = list.map((session, index) => {
372
+ const key = session ? this.getSessionExportKey(session) : '';
373
+ const rawPinnedAt = key ? pinnedMap[key] : 0;
374
+ const pinnedAt = Number.isFinite(Number(rawPinnedAt))
375
+ ? Math.floor(Number(rawPinnedAt))
376
+ : 0;
377
+ const isPinned = pinnedAt > 0;
378
+ if (isPinned) {
379
+ hasPinned = true;
380
+ }
381
+ const updatedAtMs = session ? Date.parse(session.updatedAt || '') : NaN;
382
+ const safeUpdatedAtMs = Number.isFinite(updatedAtMs) ? updatedAtMs : 0;
383
+ const messageCount = session && Number.isFinite(Number(session.messageCount))
384
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
385
+ : 0;
386
+ const totalTokens = session && Number.isFinite(Number(session.totalTokens))
387
+ ? Math.max(0, Math.floor(Number(session.totalTokens)))
388
+ : 0;
389
+ const ageHours = safeUpdatedAtMs > 0 ? Math.max(0, (now - safeUpdatedAtMs) / 3600000) : 1e9;
390
+ const activity = Math.sqrt(Math.max(1, totalTokens || (messageCount * 120)));
391
+ const hotScore = activity / (1 + (ageHours / 24));
392
+ return { session, index, pinnedAt, isPinned, safeUpdatedAtMs, hotScore };
393
+ });
394
+ if (!hasPinned && sortMode !== 'hot') {
395
+ return list;
396
+ }
397
+ decorated.sort((a, b) => {
398
+ if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;
399
+ if (a.isPinned && a.pinnedAt !== b.pinnedAt) return b.pinnedAt - a.pinnedAt;
400
+ if (sortMode === 'hot') {
401
+ if (a.hotScore !== b.hotScore) return b.hotScore - a.hotScore;
402
+ }
403
+ return a.index - b.index;
404
+ });
405
+ return decorated.map(item => item.session);
406
+ },
407
+ visibleSessionsList() {
408
+ if (!this.sessionListRenderEnabled) {
409
+ return [];
410
+ }
411
+ const list = Array.isArray(this.sortedSessionsList) ? this.sortedSessionsList : [];
412
+ if (list.length === 0) {
413
+ return [];
414
+ }
415
+ const rawVisibleCount = Number(this.sessionListVisibleCount);
416
+ const visibleCount = Number.isFinite(rawVisibleCount)
417
+ ? Math.max(0, Math.floor(rawVisibleCount))
418
+ : 0;
419
+ let targetCount = visibleCount > 0 ? Math.min(visibleCount, list.length) : Math.min(list.length, 1);
420
+ const activeKey = this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
421
+ if (activeKey) {
422
+ const activeIndex = list.findIndex((session) => this.getSessionExportKey(session) === activeKey);
423
+ if (activeIndex >= 0) {
424
+ targetCount = Math.max(targetCount, activeIndex + 1);
425
+ }
426
+ }
427
+ if (targetCount >= list.length) {
428
+ return list;
429
+ }
430
+ return list.slice(0, targetCount);
431
+ },
432
+ activeSessionVisibleMessages() {
433
+ if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
434
+ return [];
435
+ }
436
+ const list = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
437
+ const rawCount = Number(this.sessionPreviewVisibleCount);
438
+ const visibleCount = Number.isFinite(rawCount)
439
+ ? Math.max(0, Math.floor(rawCount))
440
+ : 0;
441
+ if (visibleCount <= 0) {
442
+ const initialBatchSize = Number.isFinite(this.sessionPreviewInitialBatchSize)
443
+ ? Math.max(1, Math.floor(this.sessionPreviewInitialBatchSize))
444
+ : 12;
445
+ return list.slice(0, Math.min(initialBatchSize, list.length));
446
+ }
447
+ if (visibleCount >= list.length) return list;
448
+ return list.slice(0, visibleCount);
449
+ },
450
+ canLoadMoreSessionMessages() {
451
+ if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
452
+ return false;
453
+ }
454
+ const total = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages.length : 0;
455
+ const visible = Array.isArray(this.activeSessionVisibleMessages) ? this.activeSessionVisibleMessages.length : 0;
456
+ return total > visible;
457
+ },
458
+ sessionPreviewRemainingCount() {
459
+ const total = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages.length : 0;
460
+ const visible = Array.isArray(this.activeSessionVisibleMessages) ? this.activeSessionVisibleMessages.length : 0;
461
+ return Math.max(0, total - visible);
462
+ },
463
+ sessionTimelineNodes() {
464
+ if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
465
+ return [];
466
+ }
467
+ return buildSessionTimelineNodes(this.activeSessionVisibleMessages, {
468
+ getKey: (message, index) => this.getRecordRenderKey(message, index)
469
+ });
470
+ },
471
+ sessionTimelineNodeKeyMap() {
472
+ const nodes = Array.isArray(this.sessionTimelineNodes) ? this.sessionTimelineNodes : [];
473
+ if (!nodes.length) {
474
+ return Object.create(null);
475
+ }
476
+ const map = Object.create(null);
477
+ for (const node of nodes) {
478
+ if (!node || !node.key) continue;
479
+ map[node.key] = true;
480
+ }
481
+ return map;
482
+ },
483
+ sessionTimelineActiveTitle() {
484
+ if (!this.sessionTimelineActiveKey) return '';
485
+ const nodes = Array.isArray(this.sessionTimelineNodes) ? this.sessionTimelineNodes : [];
486
+ const matched = nodes.find(node => node.key === this.sessionTimelineActiveKey);
487
+ return matched ? matched.title : '';
488
+ },
489
+ sessionQueryPlaceholder() {
490
+ if (this.isSessionQueryEnabled) {
491
+ return typeof this.t === 'function'
492
+ ? this.t('sessions.query.placeholder.enabled')
493
+ : '关键词检索(支持 Codex/Claude,例:claude code)';
494
+ }
495
+ return typeof this.t === 'function'
496
+ ? this.t('sessions.query.placeholder.disabled')
497
+ : '当前来源暂不支持关键词检索';
498
+ },
499
+ sessionUsageCharts() {
500
+ return buildUsageChartGroups(this.sessionsUsageList, {
501
+ range: this.sessionsUsageTimeRange
502
+ });
503
+ },
504
+ sessionUsageHeatmap() {
505
+ const sessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
506
+ ? this.sessionUsageCharts.filteredSessions
507
+ : this.sessionsUsageList;
508
+ const heatmap = buildUsageHeatmap(sessions, { range: this.sessionsUsageTimeRange });
509
+ const t = typeof this.t === 'function' ? this.t : null;
510
+ const lang = typeof this.lang === 'string' ? this.lang.trim().toLowerCase() : '';
511
+ const weekdayAxis = lang === 'en'
512
+ ? ['Mon', '', 'Wed', '', 'Fri', '', '']
513
+ : ['周一', '', '周三', '', '周五', '', ''];
514
+ const months = lang === 'en'
515
+ ? ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
516
+ : ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
517
+ const windowWeeks = 52;
518
+ const allWeeks = Array.isArray(heatmap.weeks) ? heatmap.weeks : [];
519
+ const safeWindowWeeks = Math.max(1, Math.min(windowWeeks, allWeeks.length));
520
+ const startIndex = Math.max(0, allWeeks.length - safeWindowWeeks);
521
+ const displayWeeksRaw = allWeeks.slice(startIndex);
522
+ let max = 0;
523
+ for (const week of displayWeeksRaw) {
524
+ const days = Array.isArray(week.days) ? week.days : [];
525
+ for (const cell of days) {
526
+ if (cell && cell.isInRange) {
527
+ max = Math.max(max, cell.sessionCount || 0);
528
+ }
529
+ }
530
+ }
531
+ max = Math.max(1, max);
532
+ const dayMs = 24 * 60 * 60 * 1000;
533
+ let lastMonth = -1;
534
+ const weeks = displayWeeksRaw.map((week) => {
535
+ const idx = Number.isFinite(Number(week.weekIndex)) ? Number(week.weekIndex) : 0;
536
+ const weekStartMs = (Number.isFinite(Number(heatmap.alignedStart)) ? Number(heatmap.alignedStart) : 0) + (idx * 7 * dayMs);
537
+ const month = Number.isFinite(weekStartMs) ? new Date(weekStartMs).getUTCMonth() : -1;
538
+ const monthLabel = (month >= 0 && month <= 11 && month !== lastMonth) ? months[month] : '';
539
+ if (month >= 0 && month <= 11) {
540
+ lastMonth = month;
541
+ }
542
+ return {
543
+ ...week,
544
+ monthLabel,
545
+ days: (Array.isArray(week.days) ? week.days : []).map((cell) => {
546
+ if (!cell) return null;
547
+ if (!cell.isInRange) {
548
+ return {
549
+ ...cell,
550
+ level: -1,
551
+ title: '',
552
+ ariaLabel: ''
553
+ };
554
+ }
555
+ const ratio = cell.sessionCount > 0 ? (cell.sessionCount / max) : 0;
556
+ const level = cell.sessionCount <= 0
557
+ ? 0
558
+ : (ratio <= 0.25 ? 1 : (ratio <= 0.5 ? 2 : (ratio <= 0.75 ? 3 : 4)));
559
+ const tokensTitle = formatUsageSummaryNumber(cell.tokenTotal || 0);
560
+ const title = t
561
+ ? t('usage.heatmap.tooltip', {
562
+ date: cell.dateKey,
563
+ sessions: cell.sessionCount,
564
+ messages: cell.messageCount,
565
+ tokens: tokensTitle
566
+ })
567
+ : `${cell.dateKey} · sessions ${cell.sessionCount} · messages ${cell.messageCount} · tokens ${tokensTitle}`;
568
+ const ariaLabel = t
569
+ ? t('usage.heatmap.aria', {
570
+ date: cell.dateKey,
571
+ sessions: cell.sessionCount
572
+ })
573
+ : `${cell.dateKey} sessions ${cell.sessionCount}`;
574
+ return {
575
+ ...cell,
576
+ level,
577
+ title,
578
+ ariaLabel
579
+ };
580
+ })
581
+ };
582
+ });
583
+ return {
584
+ ...heatmap,
585
+ weeks,
586
+ weekdayAxis
587
+ };
588
+ },
589
+ sessionUsageHourlyHeatmap() {
590
+ const sessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
591
+ ? this.sessionUsageCharts.filteredSessions
592
+ : this.sessionsUsageList;
593
+ const result = buildUsageHourlyHeatmap(sessions, { range: this.sessionsUsageTimeRange });
594
+ const t = typeof this.t === 'function' ? this.t : null;
595
+ const lang = typeof this.lang === 'string' ? this.lang.trim().toLowerCase() : '';
596
+ const weekdayLabelsZh = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
597
+ const weekdayLabelsEn = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
598
+ const weekdayLabels = lang === 'en' ? weekdayLabelsEn : weekdayLabelsZh;
599
+ const max = Math.max(1, result.maxSessionCount);
600
+ const grid = Array.isArray(result.grid) ? result.grid : [];
601
+ const rows = grid.map((cells, dayIndex) => ({
602
+ weekday: weekdayLabels[dayIndex] || '',
603
+ cells: cells.map((cell, hourIndex) => {
604
+ const ratio = cell.sessionCount > 0 ? (cell.sessionCount / max) : 0;
605
+ const level = cell.sessionCount <= 0
606
+ ? 0
607
+ : (ratio <= 0.25 ? 1 : (ratio <= 0.5 ? 2 : (ratio <= 0.75 ? 3 : 4)));
608
+ const hourLabel = String(hourIndex).padStart(2, '0');
609
+ const tooltipText = t
610
+ ? t('usage.hourlyHeatmap.tooltip', {
611
+ weekday: weekdayLabels[dayIndex],
612
+ hour: hourLabel,
613
+ sessions: cell.sessionCount,
614
+ messages: cell.messageCount,
615
+ tokens: (cell.tokenTotal || 0).toLocaleString('en-US')
616
+ })
617
+ : `${weekdayLabels[dayIndex] || ''} ${hourLabel}:00 · ${cell.sessionCount} sessions · ${cell.messageCount} messages · ${(cell.tokenTotal || 0).toLocaleString('en-US')} tokens`;
618
+ return {
619
+ hour: hourIndex,
620
+ hourLabel,
621
+ sessionCount: cell.sessionCount,
622
+ messageCount: cell.messageCount,
623
+ tokenTotal: cell.tokenTotal,
624
+ level,
625
+ tooltip: tooltipText
626
+ };
627
+ })
628
+ }));
629
+ return {
630
+ range: result.range,
631
+ rows,
632
+ hourLabels: result.hourLabels,
633
+ maxSessionCount: result.maxSessionCount
634
+ };
635
+ },
636
+ sessionUsageSummaryCards() {
637
+ const summary = this.sessionUsageCharts && this.sessionUsageCharts.summary
638
+ ? this.sessionUsageCharts.summary
639
+ : { totalSessions: 0, totalMessages: 0, totalTokens: 0, totalContextWindow: 0, activeDurationMs: 0, totalDurationMs: 0, activeDays: 0, avgMessagesPerSession: 0, busiestDay: null, busiestHour: null };
640
+ const filteredUsageSessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
641
+ ? this.sessionUsageCharts.filteredSessions
642
+ : this.sessionsUsageList;
643
+ const t = typeof this.t === 'function' ? this.t : null;
644
+ const usageRangeLabel = formatUsageRangeLabel(this.sessionsUsageTimeRange, t);
645
+ const estimatedCost = estimateUsageCostSummary(
646
+ filteredUsageSessions,
647
+ this.providersList,
648
+ this.currentProvider
649
+ );
650
+ const noneLabel = t ? t('common.none') : '暂无';
651
+ const estimatedCostPrefix = estimatedCost.skippedUnsupportedSessions > 0
652
+ ? (t ? t('usage.estimatedCost.note.excludesClaudePrefix') : '暂不含 Claude,')
653
+ : '';
654
+ const estimatedCostMethod = estimatedCost.catalogSessions > 0
655
+ ? (estimatedCost.configuredSessions > 0
656
+ ? (t ? t('usage.estimatedCost.method.configuredAndCatalog') : '按已配置单价 + 公开模型目录估算')
657
+ : (t ? t('usage.estimatedCost.method.catalog') : '按公开模型目录估算'))
658
+ : (t ? t('usage.estimatedCost.method.configured') : '按已配置单价估算');
659
+ const estimatedCostTitle = estimatedCost.hasEstimate
660
+ ? (t ? t('usage.estimatedCost.detail.estimate', {
661
+ prefix: estimatedCostPrefix,
662
+ method: estimatedCostMethod,
663
+ estimate: formatUsageEstimatedCost(estimatedCost.totalCostUsd, { precise: true }),
664
+ covered: estimatedCost.estimatedSessions,
665
+ total: estimatedCost.totalSessions,
666
+ percent: estimatedCost.coveragePercent
667
+ }) : `${estimatedCostPrefix}${estimatedCostMethod},估算 ${formatUsageEstimatedCost(estimatedCost.totalCostUsd, { precise: true })},覆盖 ${estimatedCost.estimatedSessions}/${estimatedCost.totalSessions} 个会话,约 ${estimatedCost.coveragePercent}% token`)
668
+ : (t ? t('usage.estimatedCost.detail.missing', { prefix: estimatedCostPrefix }) : `${estimatedCostPrefix}缺少可匹配的模型单价或 token 拆分。请先补 models.cost,或确认会话已记录 input/output token。`);
669
+ return [
670
+ { key: 'sessions', label: t ? t('usage.summary.sessions') : '总会话数', value: formatUsageSummaryNumber(summary.totalSessions || 0) },
671
+ { key: 'messages', label: t ? t('usage.summary.messages') : '总消息数', value: formatUsageSummaryNumber(summary.totalMessages || 0) },
672
+ {
673
+ key: 'tokens',
674
+ label: t ? t('usage.summary.tokens') : '总 token 数',
675
+ value: formatCompactUsageSummaryNumber(summary.totalTokens || 0),
676
+ title: formatUsageSummaryNumber(summary.totalTokens || 0)
677
+ },
678
+ {
679
+ key: 'context-window',
680
+ label: t ? t('usage.summary.contextWindow') : '总上下文数',
681
+ value: formatCompactUsageSummaryNumber(summary.totalContextWindow || 0),
682
+ title: formatUsageSummaryNumber(summary.totalContextWindow || 0)
683
+ },
684
+ {
685
+ key: 'estimated-cost',
686
+ label: t ? t('usage.summary.estimatedCost', { range: usageRangeLabel }) : `预估费用 · ${usageRangeLabel}`,
687
+ value: estimatedCost.hasEstimate ? formatUsageEstimatedCost(estimatedCost.totalCostUsd) : '0',
688
+ title: estimatedCostTitle
689
+ },
690
+ {
691
+ key: 'active-duration',
692
+ label: t ? t('usage.summary.activeDuration') : '活跃时长',
693
+ value: formatUsageDuration(summary.activeDurationMs || 0, { compact: true, lang: this.lang }),
694
+ title: t
695
+ ? t('usage.summary.activeDuration.title', {
696
+ value: formatUsageDuration(summary.activeDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })
697
+ })
698
+ : `累计会话跨度 ${formatUsageDuration(summary.activeDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })}`
699
+ },
700
+ {
701
+ key: 'total-duration',
702
+ label: t ? t('usage.summary.totalDuration') : '总时长',
703
+ value: formatUsageDuration(summary.totalDurationMs || 0, { compact: true, lang: this.lang }),
704
+ title: t
705
+ ? t('usage.summary.totalDuration.title', {
706
+ value: formatUsageDuration(summary.totalDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })
707
+ })
708
+ : `整体时间跨度 ${formatUsageDuration(summary.totalDurationMs || 0, { maxParts: 3, compact: false, lang: this.lang })}`
709
+ },
710
+ { key: 'days', label: t ? t('usage.summary.activeDays') : '活跃天数', value: formatUsageSummaryNumber(summary.activeDays || 0) },
711
+ { key: 'avg-messages', label: t ? t('usage.summary.avgMessagesPerSession') : '平均每会话消息', value: summary.avgMessagesPerSession || 0 },
712
+ {
713
+ key: 'busiest-day',
714
+ label: t ? t('usage.summary.busiestDay') : '最忙日',
715
+ value: summary.busiestDay && summary.busiestDay.totalSessions > 0
716
+ ? `${summary.busiestDay.label} · ${summary.busiestDay.totalSessions}`
717
+ : noneLabel
718
+ },
719
+ {
720
+ key: 'busiest-hour',
721
+ label: t ? t('usage.summary.busiestHour') : '高峰时段',
722
+ value: summary.busiestHour && summary.busiestHour.count > 0
723
+ ? `${summary.busiestHour.label} · ${summary.busiestHour.count}`
724
+ : noneLabel
725
+ }
726
+ ];
727
+ },
728
+
729
+ usageCurrentSessionStats() {
730
+ const summary = this.sessionUsageCharts && this.sessionUsageCharts.summary
731
+ ? this.sessionUsageCharts.summary
732
+ : null;
733
+ if (!summary) return null;
734
+ const t = typeof this.t === 'function' ? this.t : null;
735
+ return {
736
+ apiDurationLabel: formatUsageDuration(summary.activeDurationMs || 0, { compact: true, lang: this.lang }),
737
+ totalDurationLabel: formatUsageDuration(summary.totalDurationMs || 0, { compact: true, lang: this.lang }),
738
+ tokenLabel: formatCompactUsageSummaryNumber(summary.totalTokens || 0),
739
+ label: t ? t('usage.currentSession.title') : '当前会话',
740
+ apiDurationText: t ? t('usage.currentSession.apiDuration') : 'API时长',
741
+ totalDurationText: t ? t('usage.currentSession.totalDuration') : '总时长',
742
+ tokenText: t ? t('usage.currentSession.tokens') : 'Token'
743
+ };
744
+ },
745
+
746
+ sessionUsageDaily() {
747
+ const baseBuckets = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.buckets)
748
+ ? this.sessionUsageCharts.buckets
749
+ : [];
750
+ const pricingIndex = buildUsagePricingIndex(this.providersList);
751
+ const compareEnabled = this.sessionsUsageCompareEnabled === true && this.sessionsUsageTimeRange !== 'all';
752
+ const sessions = compareEnabled
753
+ ? this.sessionsUsageList
754
+ : (this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
755
+ ? this.sessionUsageCharts.filteredSessions
756
+ : this.sessionsUsageList);
757
+ const rangeDays = this.sessionsUsageTimeRange === '30d' ? 30 : 7;
758
+ const dayMs = 24 * 60 * 60 * 1000;
759
+ const byDay = new Map();
760
+
761
+ for (const bucket of baseBuckets) {
762
+ if (!bucket || !bucket.key) continue;
763
+ byDay.set(bucket.key, {
764
+ key: bucket.key,
765
+ label: bucket.label || bucket.key.slice(5),
766
+ sessionCount: 0,
767
+ messageCount: 0,
768
+ tokenTotal: 0,
769
+ estimatedCostUsd: 0,
770
+ estimatedSessions: 0,
771
+ hasCostEstimate: false
772
+ });
773
+ if (compareEnabled) {
774
+ const baseMs = Date.parse(`${bucket.key}T00:00:00.000Z`);
775
+ if (Number.isFinite(baseMs)) {
776
+ const prevKey = new Date(baseMs - (rangeDays * dayMs)).toISOString().slice(0, 10);
777
+ if (!byDay.has(prevKey)) {
778
+ byDay.set(prevKey, {
779
+ key: prevKey,
780
+ label: prevKey.slice(5),
781
+ sessionCount: 0,
782
+ messageCount: 0,
783
+ tokenTotal: 0,
784
+ estimatedCostUsd: 0,
785
+ estimatedSessions: 0,
786
+ hasCostEstimate: false
787
+ });
788
+ }
789
+ }
790
+ }
791
+ }
792
+
793
+ for (const session of (Array.isArray(sessions) ? sessions : [])) {
794
+ if (!session || typeof session !== 'object') continue;
795
+ const updatedAtMs = Date.parse(session.updatedAt || '');
796
+ if (!Number.isFinite(updatedAtMs)) continue;
797
+ const dayKey = new Date(updatedAtMs).toISOString().slice(0, 10);
798
+ const row = byDay.get(dayKey);
799
+ if (!row) continue;
800
+
801
+ const messageCount = Number.isFinite(Number(session.messageCount))
802
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
803
+ : 0;
804
+ const tokenTotal = Number.isFinite(Number(session.totalTokens))
805
+ ? Math.max(0, Math.floor(Number(session.totalTokens)))
806
+ : 0;
807
+ row.sessionCount += 1;
808
+ row.messageCount += messageCount;
809
+ row.tokenTotal += tokenTotal;
810
+
811
+ if (shouldEstimateUsageCostForSession(session)) {
812
+ const cost = estimateUsageCostForSession(session, pricingIndex, this.currentProvider);
813
+ if (cost.pricing && cost.hasTokenBreakdown) {
814
+ row.estimatedCostUsd += cost.estimatedUsd;
815
+ row.estimatedSessions += 1;
816
+ row.hasCostEstimate = true;
817
+ }
818
+ }
819
+ }
820
+
821
+ const currentKeys = baseBuckets.map((bucket) => bucket && bucket.key).filter(Boolean);
822
+ const rows = currentKeys
823
+ .map((key) => byDay.get(key))
824
+ .filter(Boolean)
825
+ .sort((a, b) => b.key.localeCompare(a.key, 'en-US'));
826
+ const rowsWithCompare = rows.map((row) => {
827
+ if (!compareEnabled) {
828
+ return { ...row, compareEnabled: false, prevKey: '', prevTokenTotal: 0, prevCostUsd: 0 };
829
+ }
830
+ const baseMs = Date.parse(`${row.key}T00:00:00.000Z`);
831
+ const prevKey = Number.isFinite(baseMs)
832
+ ? new Date(baseMs - (rangeDays * dayMs)).toISOString().slice(0, 10)
833
+ : '';
834
+ const prevRow = prevKey ? byDay.get(prevKey) : null;
835
+ return {
836
+ ...row,
837
+ compareEnabled: true,
838
+ prevKey,
839
+ prevTokenTotal: prevRow ? prevRow.tokenTotal : 0,
840
+ prevCostUsd: prevRow ? prevRow.estimatedCostUsd : 0
841
+ };
842
+ });
843
+ const maxTokens = rowsWithCompare.reduce((max, item) => Math.max(max, item.tokenTotal, item.prevTokenTotal || 0), 0);
844
+ const maxCost = rowsWithCompare.reduce((max, item) => Math.max(max, item.estimatedCostUsd, item.prevCostUsd || 0), 0);
845
+
846
+ return {
847
+ rows: rowsWithCompare.map((row) => ({
848
+ ...row,
849
+ tokenLabel: formatCompactUsageSummaryNumber(row.tokenTotal),
850
+ tokenTitle: formatUsageSummaryNumber(row.tokenTotal),
851
+ tokenPercent: maxTokens > 0 ? Math.round((row.tokenTotal / maxTokens) * 1000) / 10 : 0,
852
+ prevTokenPercent: row.compareEnabled && maxTokens > 0 ? Math.round(((row.prevTokenTotal || 0) / maxTokens) * 1000) / 10 : 0,
853
+ prevTokenTitle: row.compareEnabled ? formatUsageSummaryNumber(row.prevTokenTotal || 0) : '',
854
+ costLabel: row.hasCostEstimate ? formatUsageEstimatedCost(row.estimatedCostUsd) : '0',
855
+ costTitle: row.hasCostEstimate ? formatUsageEstimatedCost(row.estimatedCostUsd, { precise: true }) : '0',
856
+ costPercent: maxCost > 0 ? Math.round((row.estimatedCostUsd / maxCost) * 1000) / 10 : 0,
857
+ prevCostPercent: row.compareEnabled && maxCost > 0 ? Math.round(((row.prevCostUsd || 0) / maxCost) * 1000) / 10 : 0,
858
+ prevCostTitle: row.compareEnabled ? formatUsageEstimatedCost(row.prevCostUsd || 0, { precise: true }) : ''
859
+ })),
860
+ maxTokens,
861
+ maxCost
862
+ };
863
+ },
864
+
865
+ sessionUsageDailyTableRows() {
866
+ const daily = this.sessionUsageDaily && typeof this.sessionUsageDaily === 'object'
867
+ ? this.sessionUsageDaily
868
+ : null;
869
+ return daily && Array.isArray(daily.rows) ? daily.rows : [];
870
+ },
871
+
872
+ sessionsUsageSelectedDaySummary() {
873
+ const dayKey = typeof this.sessionsUsageSelectedDayKey === 'string' ? this.sessionsUsageSelectedDayKey.trim() : '';
874
+ if (!dayKey) return null;
875
+ const sessions = this.sessionUsageCharts && Array.isArray(this.sessionUsageCharts.filteredSessions)
876
+ ? this.sessionUsageCharts.filteredSessions
877
+ : this.sessionsUsageList;
878
+ const pricingIndex = buildUsagePricingIndex(this.providersList);
879
+ const compareEnabled = this.sessionsUsageCompareEnabled === true && this.sessionsUsageTimeRange !== 'all';
880
+ const rangeDays = this.sessionsUsageTimeRange === '30d' ? 30 : 7;
881
+ const dayMs = 24 * 60 * 60 * 1000;
882
+ const baseMs = Date.parse(`${dayKey}T00:00:00.000Z`);
883
+ const prevKey = compareEnabled && Number.isFinite(baseMs)
884
+ ? new Date(baseMs - (rangeDays * dayMs)).toISOString().slice(0, 10)
885
+ : '';
886
+ let sessionCount = 0;
887
+ let messageCount = 0;
888
+ let tokenTotal = 0;
889
+ let estimatedCostUsd = 0;
890
+ let hasCostEstimate = false;
891
+ let prevTokenTotal = 0;
892
+ let prevEstimatedCostUsd = 0;
893
+ let prevHasCostEstimate = false;
894
+ const modelMap = new Map();
895
+ const sessionRows = [];
896
+ for (const session of (Array.isArray(sessions) ? sessions : [])) {
897
+ if (!session || typeof session !== 'object') continue;
898
+ const updatedAtMs = Date.parse(session.updatedAt || '');
899
+ if (!Number.isFinite(updatedAtMs)) continue;
900
+ const key = new Date(updatedAtMs).toISOString().slice(0, 10);
901
+ const isCurrent = key === dayKey;
902
+ const isPrev = !!prevKey && key === prevKey;
903
+ if (!isCurrent && !isPrev) continue;
904
+ const msgCount = Number.isFinite(Number(session.messageCount))
905
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
906
+ : 0;
907
+ const sessionTokens = Number.isFinite(Number(session.totalTokens))
908
+ ? Math.max(0, Math.floor(Number(session.totalTokens)))
909
+ : 0;
910
+ if (isCurrent) {
911
+ sessionCount += 1;
912
+ messageCount += msgCount;
913
+ tokenTotal += sessionTokens;
914
+ } else if (isPrev) {
915
+ prevTokenTotal += sessionTokens;
916
+ }
917
+ if (shouldEstimateUsageCostForSession(session)) {
918
+ const cost = estimateUsageCostForSession(session, pricingIndex, this.currentProvider);
919
+ if (cost.pricing && cost.hasTokenBreakdown) {
920
+ if (isCurrent) {
921
+ estimatedCostUsd += cost.estimatedUsd;
922
+ hasCostEstimate = true;
923
+ } else if (isPrev) {
924
+ prevEstimatedCostUsd += cost.estimatedUsd;
925
+ prevHasCostEstimate = true;
926
+ }
927
+ }
928
+ }
929
+ const model = typeof session.model === 'string' ? session.model.trim() : '';
930
+ if (isCurrent && model) {
931
+ modelMap.set(model, (modelMap.get(model) || 0) + 1);
932
+ }
933
+ const title = typeof session.title === 'string' && session.title.trim()
934
+ ? session.title.trim()
935
+ : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
936
+ if (isCurrent) {
937
+ sessionRows.push({
938
+ key: this.getSessionExportKey(session) || `${title}:${sessionCount}`,
939
+ title,
940
+ messageCount: msgCount
941
+ });
942
+ }
943
+ }
944
+ sessionRows.sort((a, b) => b.messageCount - a.messageCount);
945
+ const lang = typeof this.lang === 'string' ? this.lang.trim().toLowerCase() : '';
946
+ const suffix = lang === 'en' ? 'msgs' : '条';
947
+ const topSessions = sessionRows.slice(0, 8).map((item) => ({
948
+ ...item,
949
+ messageCountLabel: `${item.messageCount} ${suffix}`
950
+ }));
951
+ const topModels = [...modelMap.entries()]
952
+ .sort((a, b) => b[1] - a[1])
953
+ .slice(0, 6)
954
+ .map(([model, count]) => ({
955
+ key: model,
956
+ label: `${model} · ${count}`
957
+ }));
958
+ return {
959
+ dayKey,
960
+ compareEnabled,
961
+ prevKey,
962
+ sessionCount,
963
+ messageCount,
964
+ tokenTotal,
965
+ tokenLabel: formatUsageSummaryNumber(tokenTotal),
966
+ costLabel: hasCostEstimate ? formatUsageEstimatedCost(estimatedCostUsd) : '0',
967
+ prevTokenTotal,
968
+ prevTokenLabel: compareEnabled ? formatUsageSummaryNumber(prevTokenTotal) : '0',
969
+ deltaTokenLabel: compareEnabled ? formatSignedUsageSummaryNumber(tokenTotal - prevTokenTotal) : '0',
970
+ prevCostLabel: compareEnabled ? (prevHasCostEstimate ? formatUsageEstimatedCost(prevEstimatedCostUsd) : '0') : '0',
971
+ deltaCostLabel: compareEnabled ? formatSignedUsageEstimatedCost(estimatedCostUsd - prevEstimatedCostUsd, { precise: true }) : '0',
972
+ topSessions,
973
+ topModels
974
+ };
975
+ },
976
+
977
+ visibleSessionTrashItems() {
978
+ const items = Array.isArray(this.sessionTrashItems) ? this.sessionTrashItems : [];
979
+ const visibleCount = Number(this.sessionTrashVisibleCount);
980
+ const safeVisibleCount = Number.isFinite(visibleCount) && visibleCount > 0
981
+ ? Math.floor(visibleCount)
982
+ : SESSION_TRASH_PAGE_SIZE;
983
+ return items.slice(0, safeVisibleCount);
984
+ },
985
+ sessionTrashHasMoreItems() {
986
+ return this.visibleSessionTrashItems.length < this.sessionTrashCount;
987
+ },
988
+ sessionTrashHiddenCount() {
989
+ return Math.max(0, this.sessionTrashCount - this.visibleSessionTrashItems.length);
990
+ },
991
+ sessionTrashCount() {
992
+ const totalCount = Number(this.sessionTrashTotalCount);
993
+ if (Number.isFinite(totalCount) && totalCount >= 0) {
994
+ return Math.max(0, Math.floor(totalCount));
995
+ }
996
+ return Array.isArray(this.sessionTrashItems) ? this.sessionTrashItems.length : 0;
997
+ }
998
+ };
999
+ }