codexmate 0.0.27 → 0.0.28

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