codexmate 0.0.25 → 0.0.26

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 (135) hide show
  1. package/README.md +416 -413
  2. package/README.zh.md +349 -346
  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 +1079 -1079
  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 +997 -997
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -0
  15. package/cli/session-convert-io.js +82 -0
  16. package/cli/session-convert.js +43 -0
  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 +15218 -14736
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +379 -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 +74 -74
  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 +619 -619
  44. package/plugins/prompt-templates/overview.mjs +90 -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 -612
  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.mjs +5 -5
  54. package/web-ui/logic.runtime.mjs +128 -128
  55. package/web-ui/logic.session-convert.mjs +70 -0
  56. package/web-ui/logic.sessions.mjs +709 -614
  57. package/web-ui/modules/api.mjs +90 -90
  58. package/web-ui/modules/app.computed.dashboard.mjs +171 -128
  59. package/web-ui/modules/app.computed.index.mjs +17 -17
  60. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  61. package/web-ui/modules/app.computed.session.mjs +946 -670
  62. package/web-ui/modules/app.constants.mjs +15 -15
  63. package/web-ui/modules/app.methods.agents.mjs +632 -632
  64. package/web-ui/modules/app.methods.claude-config.mjs +179 -174
  65. package/web-ui/modules/app.methods.codex-config.mjs +860 -784
  66. package/web-ui/modules/app.methods.index.mjs +92 -92
  67. package/web-ui/modules/app.methods.install.mjs +205 -205
  68. package/web-ui/modules/app.methods.navigation.mjs +743 -695
  69. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  70. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  71. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  72. package/web-ui/modules/app.methods.providers.mjs +404 -404
  73. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  74. package/web-ui/modules/app.methods.session-actions.mjs +596 -544
  75. package/web-ui/modules/app.methods.session-browser.mjs +985 -722
  76. package/web-ui/modules/app.methods.session-timeline.mjs +479 -448
  77. package/web-ui/modules/app.methods.session-trash.mjs +424 -424
  78. package/web-ui/modules/app.methods.startup-claude.mjs +522 -417
  79. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  80. package/web-ui/modules/config-mode.computed.mjs +124 -124
  81. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  82. package/web-ui/modules/i18n.dict.mjs +2113 -2055
  83. package/web-ui/modules/i18n.mjs +56 -56
  84. package/web-ui/modules/plugins.computed.mjs +3 -3
  85. package/web-ui/modules/plugins.methods.mjs +3 -3
  86. package/web-ui/modules/plugins.storage.mjs +11 -11
  87. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  88. package/web-ui/modules/skills.computed.mjs +107 -107
  89. package/web-ui/modules/skills.methods.mjs +481 -481
  90. package/web-ui/partials/index/layout-footer.html +13 -13
  91. package/web-ui/partials/index/layout-header.html +475 -475
  92. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  93. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  94. package/web-ui/partials/index/modal-health-check.html +45 -45
  95. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  96. package/web-ui/partials/index/modal-skills.html +200 -200
  97. package/web-ui/partials/index/modals-basic.html +165 -165
  98. package/web-ui/partials/index/panel-config-claude.html +184 -179
  99. package/web-ui/partials/index/panel-config-codex.html +283 -283
  100. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  101. package/web-ui/partials/index/panel-dashboard.html +186 -186
  102. package/web-ui/partials/index/panel-docs.html +147 -147
  103. package/web-ui/partials/index/panel-market.html +177 -177
  104. package/web-ui/partials/index/panel-orchestration.html +391 -391
  105. package/web-ui/partials/index/panel-plugins.html +279 -279
  106. package/web-ui/partials/index/panel-sessions.html +326 -303
  107. package/web-ui/partials/index/panel-settings.html +258 -258
  108. package/web-ui/partials/index/panel-usage.html +342 -361
  109. package/web-ui/res/json5.min.js +1 -1
  110. package/web-ui/res/vue.global.prod.js +13 -13
  111. package/web-ui/session-helpers.mjs +576 -573
  112. package/web-ui/source-bundle.cjs +233 -233
  113. package/web-ui/styles/base-theme.css +268 -264
  114. package/web-ui/styles/controls-forms.css +423 -423
  115. package/web-ui/styles/dashboard.css +274 -274
  116. package/web-ui/styles/docs-panel.css +247 -247
  117. package/web-ui/styles/feedback.css +108 -108
  118. package/web-ui/styles/health-check-dialog.css +144 -144
  119. package/web-ui/styles/layout-shell.css +603 -603
  120. package/web-ui/styles/modals-core.css +464 -464
  121. package/web-ui/styles/navigation-panels.css +390 -390
  122. package/web-ui/styles/openclaw-structured.css +266 -266
  123. package/web-ui/styles/plugins-panel.css +523 -523
  124. package/web-ui/styles/responsive.css +454 -454
  125. package/web-ui/styles/sessions-list.css +415 -398
  126. package/web-ui/styles/sessions-preview.css +411 -411
  127. package/web-ui/styles/sessions-toolbar-trash.css +330 -268
  128. package/web-ui/styles/sessions-usage.css +945 -912
  129. package/web-ui/styles/settings-panel.css +166 -166
  130. package/web-ui/styles/skills-list.css +303 -303
  131. package/web-ui/styles/skills-market.css +406 -406
  132. package/web-ui/styles/task-orchestration.css +822 -822
  133. package/web-ui/styles/titles-cards.css +408 -408
  134. package/web-ui/styles.css +21 -21
  135. package/web-ui.html +17 -17
@@ -1,614 +1,709 @@
1
- export const DEFAULT_SESSION_LIST_LIMIT = 200;
2
- export const DEFAULT_SESSION_LIST_FAST_LIMIT = 20;
3
-
4
- function shouldUseFastSessionBrowseLimit(options = {}) {
5
- if (options.forceRefresh) {
6
- return false;
7
- }
8
- const normalizedSource = normalizeSessionSource(options.source, 'all');
9
- if (normalizedSource !== 'all') {
10
- return false;
11
- }
12
- const pathFilter = normalizeSessionPathFilter(options.pathFilter);
13
- if (pathFilter) {
14
- return false;
15
- }
16
- const query = typeof options.query === 'string' ? options.query.trim() : '';
17
- if (query) {
18
- return false;
19
- }
20
- const roleFilter = typeof options.roleFilter === 'string' ? options.roleFilter.trim().toLowerCase() : 'all';
21
- if (roleFilter && roleFilter !== 'all') {
22
- return false;
23
- }
24
- const timeRangePreset = typeof options.timeRangePreset === 'string'
25
- ? options.timeRangePreset.trim().toLowerCase()
26
- : 'all';
27
- return !timeRangePreset || timeRangePreset === 'all';
28
- }
29
-
30
- export function isSessionQueryEnabled(source) {
31
- const normalized = normalizeSessionSource(source, '');
32
- return normalized === 'codex' || normalized === 'claude' || normalized === 'gemini' || normalized === 'codebuddy' || normalized === 'all';
33
- }
34
-
35
- export function normalizeSessionSource(source, fallback = 'all') {
36
- const normalized = typeof source === 'string'
37
- ? source.trim().toLowerCase()
38
- : '';
39
- if (normalized === 'codex' || normalized === 'claude' || normalized === 'gemini' || normalized === 'codebuddy' || normalized === 'all') {
40
- return normalized;
41
- }
42
- return fallback;
43
- }
44
-
45
- export function normalizeSessionPathFilter(pathFilter) {
46
- return typeof pathFilter === 'string' ? pathFilter.trim() : '';
47
- }
48
-
49
- function isConcreteSessionModelName(value) {
50
- if (typeof value !== 'string') {
51
- return false;
52
- }
53
- const normalized = value.trim();
54
- if (!normalized) {
55
- return false;
56
- }
57
- return normalized.toLowerCase() !== '<synthetic>';
58
- }
59
-
60
- function collectSessionModelNames(session) {
61
- if (!session || typeof session !== 'object') {
62
- return [];
63
- }
64
- const values = Array.isArray(session.models)
65
- ? [...session.models, session.model, session.modelName, session.modelId]
66
- : [session.model, session.modelName, session.modelId];
67
- const models = [];
68
- for (const value of values) {
69
- if (!isConcreteSessionModelName(value)) {
70
- continue;
71
- }
72
- const normalized = value.trim();
73
- if (models.includes(normalized)) {
74
- continue;
75
- }
76
- models.push(normalized);
77
- }
78
- return models;
79
- }
80
-
81
- function readSessionTotalTokens(session) {
82
- if (!session || typeof session !== 'object') {
83
- return 0;
84
- }
85
-
86
- const rawTotalTokens = Number(session.totalTokens);
87
- const hasExplicitTotal = Number.isFinite(rawTotalTokens) && rawTotalTokens >= 0;
88
- const explicitTotal = hasExplicitTotal ? Math.max(0, Math.floor(rawTotalTokens)) : null;
89
-
90
- const inputTokens = Number.isFinite(Number(session.inputTokens))
91
- ? Math.max(0, Math.floor(Number(session.inputTokens)))
92
- : null;
93
- const outputTokens = Number.isFinite(Number(session.outputTokens))
94
- ? Math.max(0, Math.floor(Number(session.outputTokens)))
95
- : null;
96
- const reasoningOutputTokens = Number.isFinite(Number(session.reasoningOutputTokens))
97
- ? Math.max(0, Math.floor(Number(session.reasoningOutputTokens)))
98
- : 0;
99
-
100
- // 对齐 usage 口径:当总 token 缺失时,使用拆分字段回填(input + output + reasoning)。
101
- // cachedInputTokens 一般包含在 inputTokens 中,因此不在此重复相加。
102
- const hasBreakdown = !(inputTokens === null && outputTokens === null && reasoningOutputTokens === 0);
103
- const breakdownTotal = hasBreakdown
104
- ? (inputTokens || 0) + (outputTokens || 0) + reasoningOutputTokens
105
- : 0;
106
-
107
- if (breakdownTotal > 0) {
108
- return breakdownTotal;
109
- }
110
- if (explicitTotal !== null) {
111
- return explicitTotal;
112
- }
113
- return 0;
114
- }
115
-
116
- export function buildSessionFilterCacheState(source, pathFilter) {
117
- return {
118
- source: normalizeSessionSource(source, 'all'),
119
- pathFilter: normalizeSessionPathFilter(pathFilter)
120
- };
121
- }
122
-
123
- export function buildSessionListParams(options = {}) {
124
- const fallbackLimit = shouldUseFastSessionBrowseLimit(options)
125
- ? DEFAULT_SESSION_LIST_FAST_LIMIT
126
- : DEFAULT_SESSION_LIST_LIMIT;
127
- const {
128
- source = 'all',
129
- pathFilter = '',
130
- query = '',
131
- roleFilter = 'all',
132
- timeRangePreset = 'all',
133
- limit = fallbackLimit,
134
- forceRefresh = false
135
- } = options;
136
- const normalizedSource = normalizeSessionSource(source, 'all');
137
- const normalizedPathFilter = normalizeSessionPathFilter(pathFilter);
138
- const queryValue = isSessionQueryEnabled(normalizedSource) ? query : '';
139
- return {
140
- source: normalizedSource,
141
- pathFilter: normalizedPathFilter,
142
- query: queryValue,
143
- queryMode: 'and',
144
- queryScope: 'content',
145
- contentScanLimit: 50,
146
- roleFilter,
147
- timeRangePreset,
148
- limit,
149
- forceRefresh: !!forceRefresh
150
- };
151
- }
152
-
153
- export function normalizeSessionMessageRole(role) {
154
- const value = typeof role === 'string' ? role.trim().toLowerCase() : '';
155
- if (value === 'user' || value === 'assistant' || value === 'system') {
156
- return value;
157
- }
158
- return 'assistant';
159
- }
160
-
161
- function toRoleMeta(role) {
162
- if (role === 'user') {
163
- return { role: 'user', roleLabel: 'User', roleShort: 'U' };
164
- }
165
- if (role === 'assistant') {
166
- return { role: 'assistant', roleLabel: 'Assistant', roleShort: 'A' };
167
- }
168
- if (role === 'system') {
169
- return { role: 'system', roleLabel: 'System', roleShort: 'S' };
170
- }
171
- return { role: 'mixed', roleLabel: 'Mixed', roleShort: 'M' };
172
- }
173
-
174
- function clampTimelinePercent(percent) {
175
- return Math.max(6, Math.min(94, percent));
176
- }
177
-
178
- export function formatSessionTimelineTimestamp(timestamp) {
179
- const value = typeof timestamp === 'string' ? timestamp.trim() : '';
180
- if (!value) return '';
181
-
182
- const matched = value.match(/^(\d{4})-(\d{2})-(\d{2})[T\s](\d{2}):(\d{2})(?::(\d{2}))?/);
183
- if (matched) {
184
- const second = matched[6] || '00';
185
- return `${matched[2]}-${matched[3]} ${matched[4]}:${matched[5]}:${second}`;
186
- }
187
-
188
- return value;
189
- }
190
-
191
- function normalizeUsageRange(range) {
192
- const normalized = typeof range === 'string' ? range.trim().toLowerCase() : '7d';
193
- if (normalized === '30d' || normalized === 'all') {
194
- return normalized;
195
- }
196
- return '7d';
197
- }
198
-
199
- function toUtcDayStartMs(value) {
200
- const stamp = new Date(value);
201
- return Date.UTC(stamp.getUTCFullYear(), stamp.getUTCMonth(), stamp.getUTCDate());
202
- }
203
-
204
- function formatUtcDayKey(value) {
205
- const stamp = new Date(value);
206
- return `${stamp.getUTCFullYear()}-${String(stamp.getUTCMonth() + 1).padStart(2, '0')}-${String(stamp.getUTCDate()).padStart(2, '0')}`;
207
- }
208
-
209
- function buildUsageBuckets(normalizedSessions, options = {}) {
210
- const range = normalizeUsageRange(options.range);
211
- const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
212
- const dayMs = 24 * 60 * 60 * 1000;
213
- const buckets = [];
214
-
215
- if (range === 'all') {
216
- const validDayStarts = normalizedSessions
217
- .map((session) => toUtcDayStartMs(session.updatedAtMs))
218
- .filter((value) => Number.isFinite(value));
219
- const firstDayStart = validDayStarts.length ? Math.min(...validDayStarts) : toUtcDayStartMs(now);
220
- const lastDayStart = validDayStarts.length ? Math.max(...validDayStarts) : toUtcDayStartMs(now);
221
- for (let stamp = firstDayStart; stamp <= lastDayStart; stamp += dayMs) {
222
- const key = formatUtcDayKey(stamp);
223
- buckets.push({
224
- key,
225
- label: key.slice(5),
226
- codex: 0,
227
- claude: 0,
228
- totalMessages: 0,
229
- totalSessions: 0
230
- });
231
- }
232
- return { range, buckets };
233
- }
234
-
235
- const rangeDays = range === '30d' ? 30 : 7;
236
- for (let i = rangeDays - 1; i >= 0; i -= 1) {
237
- const stamp = new Date(now - (i * dayMs));
238
- const key = formatUtcDayKey(stamp);
239
- buckets.push({
240
- key,
241
- label: key.slice(5),
242
- codex: 0,
243
- claude: 0,
244
- totalMessages: 0,
245
- totalSessions: 0
246
- });
247
- }
248
- return { range, buckets };
249
- }
250
-
251
- export function buildUsageChartGroups(sessions = [], options = {}) {
252
- const list = Array.isArray(sessions) ? sessions : [];
253
- const normalizedSessions = [];
254
- for (const [sessionIndex, session] of list.entries()) {
255
- if (!session || typeof session !== 'object') continue;
256
- const source = normalizeSessionSource(session.source, '');
257
- if (source !== 'codex' && source !== 'claude') continue;
258
- const updatedAtMs = Date.parse(session.updatedAt || '');
259
- if (!Number.isFinite(updatedAtMs)) continue;
260
- const createdAtMs = Date.parse(session.createdAt || '');
261
- const sessionStartedAtMs = Number.isFinite(createdAtMs) ? createdAtMs : updatedAtMs;
262
- const sessionEndedAtMs = Math.max(updatedAtMs, sessionStartedAtMs);
263
- normalizedSessions.push({
264
- session,
265
- sessionIndex,
266
- source,
267
- updatedAtMs,
268
- createdAtMs,
269
- sessionStartedAtMs,
270
- sessionEndedAtMs,
271
- bucketKey: formatUtcDayKey(updatedAtMs)
272
- });
273
- }
274
- const { range, buckets } = buildUsageBuckets(normalizedSessions, options);
275
- const bucketMap = new Map(buckets.map((bucket) => [bucket.key, bucket]));
276
- let codexTotal = 0;
277
- let claudeTotal = 0;
278
- let messageTotal = 0;
279
- let totalTokens = 0;
280
- let totalContextWindow = 0;
281
- let activeDurationMs = 0;
282
- let earliestSessionMs = Number.POSITIVE_INFINITY;
283
- let latestSessionMs = 0;
284
- const pathMap = new Map();
285
- const modelMap = new Map();
286
- const missingModelProviderMap = new Map();
287
- const missingModelSessionMap = new Map();
288
- const sourceMessageTotals = { codex: 0, claude: 0 };
289
- const missingModelSourceTotals = { codex: 0, claude: 0 };
290
- let missingModelSessions = 0;
291
- let providerOnlySessions = 0;
292
- const hourCounts = Array.from({ length: 24 }, (_, hour) => ({
293
- key: String(hour).padStart(2, '0'),
294
- label: String(hour).padStart(2, '0'),
295
- count: 0
296
- }));
297
- const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
298
- const weekdayCounts = Array.from({ length: 7 }, (_, index) => ({
299
- key: String(index),
300
- label: weekdayLabels[index],
301
- count: 0
302
- }));
303
- const recentSessions = [];
304
- const topSessionsByMessages = [];
305
- const filteredSessions = [];
306
-
307
- for (const normalized of normalizedSessions) {
308
- const { session, sessionIndex, source, updatedAtMs, sessionStartedAtMs, sessionEndedAtMs, bucketKey } = normalized;
309
- const stamp = new Date(updatedAtMs);
310
- const bucket = bucketMap.get(bucketKey);
311
- if (!bucket) continue;
312
- const sessionModels = collectSessionModelNames(session);
313
- if (sessionModels.length === 0) continue;
314
- filteredSessions.push(session);
315
- const messageCount = Number.isFinite(Number(session.messageCount))
316
- ? Math.max(0, Math.floor(Number(session.messageCount)))
317
- : 0;
318
- const sessionTotalTokens = readSessionTotalTokens(session);
319
- const sessionContextWindow = Number.isFinite(Number(session.contextWindow))
320
- ? Math.max(0, Math.floor(Number(session.contextWindow)))
321
- : 0;
322
- bucket.totalSessions += 1;
323
- bucket.totalMessages += messageCount;
324
- if (source === 'codex') {
325
- bucket.codex += 1;
326
- codexTotal += 1;
327
- } else {
328
- bucket.claude += 1;
329
- claudeTotal += 1;
330
- }
331
- messageTotal += messageCount;
332
- totalTokens += sessionTotalTokens;
333
- totalContextWindow += sessionContextWindow;
334
- sourceMessageTotals[source] += messageCount;
335
- activeDurationMs += Math.max(0, sessionEndedAtMs - sessionStartedAtMs);
336
- earliestSessionMs = Math.min(earliestSessionMs, sessionStartedAtMs);
337
- latestSessionMs = Math.max(latestSessionMs, sessionEndedAtMs);
338
-
339
- const utcHour = stamp.getUTCHours();
340
- if (hourCounts[utcHour]) {
341
- hourCounts[utcHour].count += 1;
342
- }
343
- const dayIndex = (stamp.getUTCDay() + 6) % 7;
344
- if (weekdayCounts[dayIndex]) {
345
- weekdayCounts[dayIndex].count += 1;
346
- }
347
-
348
- const cwd = normalizeSessionPathFilter(session.cwd);
349
- if (cwd) {
350
- const prev = pathMap.get(cwd) || { count: 0, messageTotal: 0, updatedAtMs: 0 };
351
- pathMap.set(cwd, {
352
- count: prev.count + 1,
353
- messageTotal: prev.messageTotal + messageCount,
354
- updatedAtMs: Math.max(prev.updatedAtMs, updatedAtMs)
355
- });
356
- }
357
-
358
- const sourceLabel = source === 'codex' ? 'Codex' : 'Claude Code';
359
- const normalizedTitle = typeof session.title === 'string' && session.title.trim()
360
- ? session.title.trim()
361
- : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
362
- for (const modelId of sessionModels) {
363
- const prev = modelMap.get(modelId) || {
364
- count: 0,
365
- messageTotal: 0,
366
- tokenTotal: 0,
367
- sources: new Set()
368
- };
369
- prev.count += 1;
370
- prev.messageTotal += messageCount;
371
- prev.tokenTotal += sessionTotalTokens;
372
- prev.sources.add(source);
373
- modelMap.set(modelId, prev);
374
- }
375
-
376
- const sessionEntry = {
377
- key: [
378
- source,
379
- session.sessionId || '',
380
- session.filePath || normalizedTitle,
381
- String(updatedAtMs),
382
- String(messageCount),
383
- String(sessionIndex)
384
- ].join(':'),
385
- title: normalizedTitle,
386
- source,
387
- sourceLabel,
388
- cwd,
389
- messageCount,
390
- updatedAt: session.updatedAt || '',
391
- updatedAtMs,
392
- updatedAtLabel: formatSessionTimelineTimestamp(session.updatedAt || ''),
393
- hasExactMessageCount: session.__messageCountExact === true
394
- };
395
- recentSessions.push(sessionEntry);
396
- topSessionsByMessages.push({ ...sessionEntry });
397
- }
398
-
399
- const totalSessions = codexTotal + claudeTotal;
400
- const sourceShare = [
401
- { key: 'codex', label: 'Codex', value: codexTotal },
402
- { key: 'claude', label: 'Claude', value: claudeTotal }
403
- ].map((item) => ({
404
- ...item,
405
- percent: totalSessions > 0 ? Math.round((item.value / totalSessions) * 100) : 0,
406
- messageTotal: sourceMessageTotals[item.key] || 0,
407
- messagePercent: messageTotal > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / messageTotal) * 100) : 0,
408
- avgMessages: item.value > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / item.value) * 10) / 10 : 0
409
- }));
410
-
411
- const topPaths = [...pathMap.entries()]
412
- .sort((a, b) => b[1].count - a[1].count || b[1].messageTotal - a[1].messageTotal || a[0].localeCompare(b[0], 'zh-Hans-CN'))
413
- .slice(0, 5)
414
- .map(([pathValue, meta]) => ({
415
- path: pathValue,
416
- count: meta.count,
417
- messageTotal: meta.messageTotal,
418
- updatedAtLabel: meta.updatedAtMs ? formatSessionTimelineTimestamp(new Date(meta.updatedAtMs).toISOString()) : ''
419
- }));
420
-
421
- const usedModels = [...modelMap.entries()]
422
- .sort((a, b) => b[1].count - a[1].count)
423
- .map(([modelId, meta]) => {
424
- const sourceLabels = [...meta.sources]
425
- .sort((a, b) => a.localeCompare(b, 'en-US'))
426
- .map((source) => (source === 'codex' ? 'Codex' : 'Claude Code'));
427
- return {
428
- key: modelId,
429
- model: modelId,
430
- count: meta.count,
431
- messageTotal: meta.messageTotal,
432
- tokenTotal: meta.tokenTotal,
433
- sourceLabels
434
- };
435
- });
436
-
437
- const sortedRecentSessions = recentSessions
438
- .sort((a, b) => b.updatedAtMs - a.updatedAtMs || b.messageCount - a.messageCount || a.title.localeCompare(b.title, 'zh-Hans-CN'))
439
- .slice(0, 6);
440
-
441
- const missingModelProviders = [...missingModelProviderMap.values()]
442
- .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label, 'zh-Hans-CN'));
443
- const missingModelSessionsPreview = [...missingModelSessionMap.values()]
444
- .sort((a, b) => b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
445
- .slice(0, 5);
446
-
447
- const modelCoverage = {
448
- totalSessions,
449
- modeledSessions: Math.max(0, totalSessions - missingModelSessions),
450
- missingModelSessions,
451
- providerOnlySessions,
452
- missingModelSourceTotals,
453
- missingModelProviders,
454
- missingModelSessionsPreview,
455
- coveragePercent: totalSessions > 0 ? Math.round(((totalSessions - missingModelSessions) / totalSessions) * 100) : 0
456
- };
457
-
458
- const sortedTopSessionsByMessages = topSessionsByMessages
459
- .sort((a, b) => b.messageCount - a.messageCount || b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
460
- .slice(0, 6);
461
-
462
- const maxSessionBucket = buckets.reduce((max, item) => Math.max(max, item.totalSessions), 0);
463
- const maxMessageBucket = buckets.reduce((max, item) => Math.max(max, item.totalMessages), 0);
464
- const maxHourCount = hourCounts.reduce((max, item) => Math.max(max, item.count), 0);
465
- const maxWeekdayCount = weekdayCounts.reduce((max, item) => Math.max(max, item.count), 0);
466
- const busiestDay = [...buckets]
467
- .sort((a, b) => b.totalSessions - a.totalSessions || b.totalMessages - a.totalMessages || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
468
- const busiestHour = [...hourCounts]
469
- .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
470
- const activeDays = buckets.filter((item) => item.totalSessions > 0).length;
471
- const avgMessagesPerSession = totalSessions > 0 ? Math.round((messageTotal / totalSessions) * 10) / 10 : 0;
472
- const avgSessionsPerActiveDay = activeDays > 0 ? Math.round((totalSessions / activeDays) * 10) / 10 : 0;
473
- const totalDurationMs = Number.isFinite(earliestSessionMs) && latestSessionMs > 0
474
- ? Math.max(0, latestSessionMs - earliestSessionMs)
475
- : 0;
476
-
477
- return {
478
- range,
479
- buckets,
480
- filteredSessions,
481
- summary: {
482
- totalSessions,
483
- totalMessages: messageTotal,
484
- totalTokens,
485
- totalContextWindow,
486
- activeDurationMs,
487
- totalDurationMs,
488
- codexTotal,
489
- claudeTotal,
490
- activeDays,
491
- avgMessagesPerSession,
492
- avgSessionsPerActiveDay,
493
- busiestDay: busiestDay
494
- ? {
495
- key: busiestDay.key,
496
- label: busiestDay.label,
497
- totalSessions: busiestDay.totalSessions,
498
- totalMessages: busiestDay.totalMessages
499
- }
500
- : null,
501
- busiestHour: busiestHour
502
- ? {
503
- key: busiestHour.key,
504
- label: `${busiestHour.label}:00`,
505
- count: busiestHour.count
506
- }
507
- : null
508
- },
509
- sourceShare,
510
- usedModels,
511
- modelCoverage,
512
- topPaths,
513
- recentSessions: sortedRecentSessions,
514
- topSessionsByMessages: sortedTopSessionsByMessages,
515
- hourActivity: hourCounts.map((item) => ({
516
- ...item,
517
- percent: maxHourCount > 0 ? Math.round((item.count / maxHourCount) * 100) : 0
518
- })),
519
- weekdayActivity: weekdayCounts.map((item) => ({
520
- ...item,
521
- percent: maxWeekdayCount > 0 ? Math.round((item.count / maxWeekdayCount) * 100) : 0
522
- })),
523
- maxSessionBucket,
524
- maxMessageBucket,
525
- maxHourCount,
526
- maxWeekdayCount
527
- };
528
- }
529
-
530
- export function buildSessionTimelineNodes(messages = [], options = {}) {
531
- const list = Array.isArray(messages) ? messages : [];
532
- const getKey = typeof options.getKey === 'function'
533
- ? options.getKey
534
- : ((_message, index) => `msg-${index}`);
535
- const total = list.length;
536
- const rawMaxMarkers = Number(options.maxMarkers);
537
- const maxMarkers = Number.isFinite(rawMaxMarkers)
538
- ? Math.max(1, Math.min(80, Math.floor(rawMaxMarkers)))
539
- : 30;
540
-
541
- const buildSingleNode = (message, index) => {
542
- const role = normalizeSessionMessageRole(message && (message.normalizedRole || message.role));
543
- const roleMeta = toRoleMeta(role);
544
- const key = String(getKey(message, index) || `msg-${index}`);
545
- const displayTime = formatSessionTimelineTimestamp(message && message.timestamp ? message.timestamp : '');
546
- const title = displayTime
547
- ? `#${index + 1} · ${roleMeta.roleLabel} · ${displayTime}`
548
- : `#${index + 1} · ${roleMeta.roleLabel}`;
549
- const percent = total <= 1 ? 0 : (index / (total - 1)) * 100;
550
- return {
551
- key,
552
- role: roleMeta.role,
553
- roleLabel: roleMeta.roleLabel,
554
- roleShort: roleMeta.roleShort,
555
- displayTime,
556
- title,
557
- percent,
558
- safePercent: clampTimelinePercent(percent)
559
- };
560
- };
561
-
562
- if (total <= maxMarkers) {
563
- return list.map((message, index) => buildSingleNode(message, index));
564
- }
565
-
566
- const nodes = [];
567
- const bucketWidth = total / maxMarkers;
568
- for (let bucket = 0; bucket < maxMarkers; bucket += 1) {
569
- let start = Math.floor(bucket * bucketWidth);
570
- if (nodes.length && start <= nodes[nodes.length - 1].endIndex) {
571
- start = nodes[nodes.length - 1].endIndex + 1;
572
- }
573
- if (start >= total) {
574
- break;
575
- }
576
- let end = Math.floor((bucket + 1) * bucketWidth) - 1;
577
- end = Math.max(start, Math.min(total - 1, end));
578
- const targetIndex = Math.min(total - 1, start + Math.floor((end - start) / 2));
579
- const targetMessage = list[targetIndex] || null;
580
- const key = String(getKey(targetMessage, targetIndex) || `msg-${targetIndex}`);
581
- const percent = total <= 1 ? 0 : (targetIndex / (total - 1)) * 100;
582
- const messagesInGroup = end - start + 1;
583
- const roleSet = new Set();
584
- for (let i = start; i <= end; i += 1) {
585
- roleSet.add(normalizeSessionMessageRole(list[i] && (list[i].normalizedRole || list[i].role)));
586
- }
587
- const roleValue = roleSet.size === 1 ? Array.from(roleSet)[0] : 'mixed';
588
- const roleMeta = toRoleMeta(roleValue);
589
- const firstTime = formatSessionTimelineTimestamp(list[start] && list[start].timestamp ? list[start].timestamp : '');
590
- const lastTime = formatSessionTimelineTimestamp(list[end] && list[end].timestamp ? list[end].timestamp : '');
591
- let displayTime = '';
592
- if (firstTime && lastTime) {
593
- displayTime = firstTime === lastTime ? firstTime : `${firstTime} ~ ${lastTime}`;
594
- } else {
595
- displayTime = firstTime || lastTime;
596
- }
597
- const titleBase = `#${start + 1}-${end + 1} · ${messagesInGroup} msgs · ${roleMeta.roleLabel}`;
598
- const title = displayTime ? `${titleBase} · ${displayTime}` : titleBase;
599
- nodes.push({
600
- key,
601
- role: roleMeta.role,
602
- roleLabel: roleMeta.roleLabel,
603
- roleShort: roleMeta.roleShort,
604
- displayTime,
605
- title,
606
- percent,
607
- safePercent: clampTimelinePercent(percent),
608
- startIndex: start,
609
- endIndex: end,
610
- messageCount: messagesInGroup
611
- });
612
- }
613
- return nodes;
614
- }
1
+ export const DEFAULT_SESSION_LIST_LIMIT = 200;
2
+ export const DEFAULT_SESSION_LIST_FAST_LIMIT = 20;
3
+
4
+ function shouldUseFastSessionBrowseLimit(options = {}) {
5
+ if (options.forceRefresh) {
6
+ return false;
7
+ }
8
+ const normalizedSource = normalizeSessionSource(options.source, 'all');
9
+ if (normalizedSource !== 'all') {
10
+ return false;
11
+ }
12
+ const pathFilter = normalizeSessionPathFilter(options.pathFilter);
13
+ if (pathFilter) {
14
+ return false;
15
+ }
16
+ const query = typeof options.query === 'string' ? options.query.trim() : '';
17
+ if (query) {
18
+ return false;
19
+ }
20
+ const roleFilter = typeof options.roleFilter === 'string' ? options.roleFilter.trim().toLowerCase() : 'all';
21
+ if (roleFilter && roleFilter !== 'all') {
22
+ return false;
23
+ }
24
+ const timeRangePreset = typeof options.timeRangePreset === 'string'
25
+ ? options.timeRangePreset.trim().toLowerCase()
26
+ : 'all';
27
+ return !timeRangePreset || timeRangePreset === 'all';
28
+ }
29
+
30
+ export function isSessionQueryEnabled(source) {
31
+ const normalized = normalizeSessionSource(source, '');
32
+ return normalized === 'codex' || normalized === 'claude' || normalized === 'gemini' || normalized === 'codebuddy' || normalized === 'all';
33
+ }
34
+
35
+ export function normalizeSessionSource(source, fallback = 'all') {
36
+ const normalized = typeof source === 'string'
37
+ ? source.trim().toLowerCase()
38
+ : '';
39
+ if (normalized === 'codex' || normalized === 'claude' || normalized === 'gemini' || normalized === 'codebuddy' || normalized === 'all') {
40
+ return normalized;
41
+ }
42
+ return fallback;
43
+ }
44
+
45
+ export function normalizeSessionPathFilter(pathFilter) {
46
+ return typeof pathFilter === 'string' ? pathFilter.trim() : '';
47
+ }
48
+
49
+ function isConcreteSessionModelName(value) {
50
+ if (typeof value !== 'string') {
51
+ return false;
52
+ }
53
+ const normalized = value.trim();
54
+ if (!normalized) {
55
+ return false;
56
+ }
57
+ return normalized.toLowerCase() !== '<synthetic>';
58
+ }
59
+
60
+ function collectSessionModelNames(session) {
61
+ if (!session || typeof session !== 'object') {
62
+ return [];
63
+ }
64
+ const values = Array.isArray(session.models)
65
+ ? [...session.models, session.model, session.modelName, session.modelId]
66
+ : [session.model, session.modelName, session.modelId];
67
+ const models = [];
68
+ for (const value of values) {
69
+ if (!isConcreteSessionModelName(value)) {
70
+ continue;
71
+ }
72
+ const normalized = value.trim();
73
+ if (models.includes(normalized)) {
74
+ continue;
75
+ }
76
+ models.push(normalized);
77
+ }
78
+ return models;
79
+ }
80
+
81
+ function readSessionTotalTokens(session) {
82
+ if (!session || typeof session !== 'object') {
83
+ return 0;
84
+ }
85
+
86
+ const rawTotalTokens = Number(session.totalTokens);
87
+ const hasExplicitTotal = Number.isFinite(rawTotalTokens) && rawTotalTokens >= 0;
88
+ const explicitTotal = hasExplicitTotal ? Math.max(0, Math.floor(rawTotalTokens)) : null;
89
+
90
+ const inputTokens = Number.isFinite(Number(session.inputTokens))
91
+ ? Math.max(0, Math.floor(Number(session.inputTokens)))
92
+ : null;
93
+ const outputTokens = Number.isFinite(Number(session.outputTokens))
94
+ ? Math.max(0, Math.floor(Number(session.outputTokens)))
95
+ : null;
96
+ const reasoningOutputTokens = Number.isFinite(Number(session.reasoningOutputTokens))
97
+ ? Math.max(0, Math.floor(Number(session.reasoningOutputTokens)))
98
+ : 0;
99
+
100
+ // 对齐 usage 口径:当总 token 缺失时,使用拆分字段回填(input + output + reasoning)。
101
+ // cachedInputTokens 一般包含在 inputTokens 中,因此不在此重复相加。
102
+ const hasBreakdown = !(inputTokens === null && outputTokens === null && reasoningOutputTokens === 0);
103
+ const breakdownTotal = hasBreakdown
104
+ ? (inputTokens || 0) + (outputTokens || 0) + reasoningOutputTokens
105
+ : 0;
106
+
107
+ if (breakdownTotal > 0) {
108
+ return breakdownTotal;
109
+ }
110
+ if (explicitTotal !== null) {
111
+ return explicitTotal;
112
+ }
113
+ return 0;
114
+ }
115
+
116
+ export function buildSessionFilterCacheState(source, pathFilter) {
117
+ return {
118
+ source: normalizeSessionSource(source, 'all'),
119
+ pathFilter: normalizeSessionPathFilter(pathFilter)
120
+ };
121
+ }
122
+
123
+ export function buildSessionListParams(options = {}) {
124
+ const fallbackLimit = shouldUseFastSessionBrowseLimit(options)
125
+ ? DEFAULT_SESSION_LIST_FAST_LIMIT
126
+ : DEFAULT_SESSION_LIST_LIMIT;
127
+ const {
128
+ source = 'all',
129
+ pathFilter = '',
130
+ query = '',
131
+ roleFilter = 'all',
132
+ timeRangePreset = 'all',
133
+ limit = fallbackLimit,
134
+ forceRefresh = false
135
+ } = options;
136
+ const normalizedSource = normalizeSessionSource(source, 'all');
137
+ const normalizedPathFilter = normalizeSessionPathFilter(pathFilter);
138
+ const queryValue = isSessionQueryEnabled(normalizedSource) ? query : '';
139
+ return {
140
+ source: normalizedSource,
141
+ pathFilter: normalizedPathFilter,
142
+ query: queryValue,
143
+ queryMode: 'and',
144
+ queryScope: 'content',
145
+ contentScanLimit: 50,
146
+ roleFilter,
147
+ timeRangePreset,
148
+ limit,
149
+ forceRefresh: !!forceRefresh
150
+ };
151
+ }
152
+
153
+ export function normalizeSessionMessageRole(role) {
154
+ const value = typeof role === 'string' ? role.trim().toLowerCase() : '';
155
+ if (value === 'user' || value === 'assistant' || value === 'system') {
156
+ return value;
157
+ }
158
+ return 'assistant';
159
+ }
160
+
161
+ function toRoleMeta(role) {
162
+ if (role === 'user') {
163
+ return { role: 'user', roleLabel: 'User', roleShort: 'U' };
164
+ }
165
+ if (role === 'assistant') {
166
+ return { role: 'assistant', roleLabel: 'Assistant', roleShort: 'A' };
167
+ }
168
+ if (role === 'system') {
169
+ return { role: 'system', roleLabel: 'System', roleShort: 'S' };
170
+ }
171
+ return { role: 'mixed', roleLabel: 'Mixed', roleShort: 'M' };
172
+ }
173
+
174
+ function clampTimelinePercent(percent) {
175
+ return Math.max(6, Math.min(94, percent));
176
+ }
177
+
178
+ export function formatSessionTimelineTimestamp(timestamp) {
179
+ const value = typeof timestamp === 'string' ? timestamp.trim() : '';
180
+ if (!value) return '';
181
+
182
+ const matched = value.match(/^(\d{4})-(\d{2})-(\d{2})[T\s](\d{2}):(\d{2})(?::(\d{2}))?/);
183
+ if (matched) {
184
+ const second = matched[6] || '00';
185
+ return `${matched[2]}-${matched[3]} ${matched[4]}:${matched[5]}:${second}`;
186
+ }
187
+
188
+ return value;
189
+ }
190
+
191
+ function normalizeUsageRange(range) {
192
+ const normalized = typeof range === 'string' ? range.trim().toLowerCase() : '7d';
193
+ if (normalized === '30d' || normalized === 'all') {
194
+ return normalized;
195
+ }
196
+ return '7d';
197
+ }
198
+
199
+ function toUtcDayStartMs(value) {
200
+ const stamp = new Date(value);
201
+ return Date.UTC(stamp.getUTCFullYear(), stamp.getUTCMonth(), stamp.getUTCDate());
202
+ }
203
+
204
+ function formatUtcDayKey(value) {
205
+ const stamp = new Date(value);
206
+ return `${stamp.getUTCFullYear()}-${String(stamp.getUTCMonth() + 1).padStart(2, '0')}-${String(stamp.getUTCDate()).padStart(2, '0')}`;
207
+ }
208
+
209
+ export function buildUsageHeatmap(sessions = [], options = {}) {
210
+ const list = Array.isArray(sessions) ? sessions : [];
211
+ const normalized = [];
212
+ for (const session of list) {
213
+ if (!session || typeof session !== 'object') continue;
214
+ const source = normalizeSessionSource(session.source, '');
215
+ if (source !== 'codex' && source !== 'claude') continue;
216
+ const updatedAtMs = Date.parse(session.updatedAt || '');
217
+ if (!Number.isFinite(updatedAtMs)) continue;
218
+ normalized.push({
219
+ updatedAtMs,
220
+ messageCount: Number.isFinite(Number(session.messageCount))
221
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
222
+ : 0,
223
+ tokenTotal: readSessionTotalTokens(session)
224
+ });
225
+ }
226
+
227
+ const range = normalizeUsageRange(options.range);
228
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
229
+ const dayMs = 24 * 60 * 60 * 1000;
230
+ const todayStart = toUtcDayStartMs(now);
231
+ let startDay = todayStart;
232
+ let endDay = todayStart;
233
+ if (range === 'all') {
234
+ const dayStarts = normalized.map((item) => toUtcDayStartMs(item.updatedAtMs)).filter((value) => Number.isFinite(value));
235
+ if (dayStarts.length) {
236
+ startDay = Math.min(...dayStarts);
237
+ endDay = Math.max(...dayStarts);
238
+ }
239
+ } else {
240
+ const rangeDays = range === '30d' ? 30 : 7;
241
+ endDay = todayStart;
242
+ startDay = todayStart - ((rangeDays - 1) * dayMs);
243
+ }
244
+
245
+ const startDow = new Date(startDay).getUTCDay();
246
+ const startShift = (startDow + 6) % 7;
247
+ const alignedStart = startDay - (startShift * dayMs);
248
+ const endDow = new Date(endDay).getUTCDay();
249
+ const endShift = (6 - ((endDow + 6) % 7));
250
+ const alignedEnd = endDay + (endShift * dayMs);
251
+ const totalDays = Math.floor((alignedEnd - alignedStart) / dayMs) + 1;
252
+ const weekCount = Math.max(1, Math.ceil(totalDays / 7));
253
+
254
+ const byDay = new Map();
255
+ for (const item of normalized) {
256
+ const dayKey = formatUtcDayKey(item.updatedAtMs);
257
+ const existing = byDay.get(dayKey) || { sessionCount: 0, messageCount: 0, tokenTotal: 0 };
258
+ existing.sessionCount += 1;
259
+ existing.messageCount += item.messageCount;
260
+ existing.tokenTotal += item.tokenTotal;
261
+ byDay.set(dayKey, existing);
262
+ }
263
+
264
+ const weeks = Array.from({ length: weekCount }, (_, idx) => ({
265
+ key: `w-${idx}`,
266
+ weekIndex: idx,
267
+ days: Array.from({ length: 7 }, () => null)
268
+ }));
269
+
270
+ let maxSessionCount = 0;
271
+ for (let dayIndex = 0; dayIndex < totalDays; dayIndex += 1) {
272
+ const dateMs = alignedStart + (dayIndex * dayMs);
273
+ const dateKey = formatUtcDayKey(dateMs);
274
+ const isInRange = dateMs >= startDay && dateMs <= endDay;
275
+ const weekIndex = Math.floor(dayIndex / 7);
276
+ const dow = new Date(dateMs).getUTCDay();
277
+ const rowIndex = (dow + 6) % 7;
278
+ const totals = isInRange ? (byDay.get(dateKey) || { sessionCount: 0, messageCount: 0, tokenTotal: 0 }) : null;
279
+ const sessionCount = totals ? totals.sessionCount : 0;
280
+ if (isInRange) {
281
+ maxSessionCount = Math.max(maxSessionCount, sessionCount);
282
+ }
283
+ weeks[weekIndex].days[rowIndex] = {
284
+ dateKey,
285
+ dateMs,
286
+ isInRange,
287
+ sessionCount,
288
+ messageCount: totals ? totals.messageCount : 0,
289
+ tokenTotal: totals ? totals.tokenTotal : 0
290
+ };
291
+ }
292
+
293
+ return {
294
+ range,
295
+ startDay,
296
+ endDay,
297
+ alignedStart,
298
+ alignedEnd,
299
+ maxSessionCount,
300
+ weeks
301
+ };
302
+ }
303
+
304
+ function buildUsageBuckets(normalizedSessions, options = {}) {
305
+ const range = normalizeUsageRange(options.range);
306
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now();
307
+ const dayMs = 24 * 60 * 60 * 1000;
308
+ const buckets = [];
309
+
310
+ if (range === 'all') {
311
+ const validDayStarts = normalizedSessions
312
+ .map((session) => toUtcDayStartMs(session.updatedAtMs))
313
+ .filter((value) => Number.isFinite(value));
314
+ const firstDayStart = validDayStarts.length ? Math.min(...validDayStarts) : toUtcDayStartMs(now);
315
+ const lastDayStart = validDayStarts.length ? Math.max(...validDayStarts) : toUtcDayStartMs(now);
316
+ for (let stamp = firstDayStart; stamp <= lastDayStart; stamp += dayMs) {
317
+ const key = formatUtcDayKey(stamp);
318
+ buckets.push({
319
+ key,
320
+ label: key.slice(5),
321
+ codex: 0,
322
+ claude: 0,
323
+ totalMessages: 0,
324
+ totalSessions: 0
325
+ });
326
+ }
327
+ return { range, buckets };
328
+ }
329
+
330
+ const rangeDays = range === '30d' ? 30 : 7;
331
+ for (let i = rangeDays - 1; i >= 0; i -= 1) {
332
+ const stamp = new Date(now - (i * dayMs));
333
+ const key = formatUtcDayKey(stamp);
334
+ buckets.push({
335
+ key,
336
+ label: key.slice(5),
337
+ codex: 0,
338
+ claude: 0,
339
+ totalMessages: 0,
340
+ totalSessions: 0
341
+ });
342
+ }
343
+ return { range, buckets };
344
+ }
345
+
346
+ export function buildUsageChartGroups(sessions = [], options = {}) {
347
+ const list = Array.isArray(sessions) ? sessions : [];
348
+ const normalizedSessions = [];
349
+ for (const [sessionIndex, session] of list.entries()) {
350
+ if (!session || typeof session !== 'object') continue;
351
+ const source = normalizeSessionSource(session.source, '');
352
+ if (source !== 'codex' && source !== 'claude') continue;
353
+ const updatedAtMs = Date.parse(session.updatedAt || '');
354
+ if (!Number.isFinite(updatedAtMs)) continue;
355
+ const createdAtMs = Date.parse(session.createdAt || '');
356
+ const sessionStartedAtMs = Number.isFinite(createdAtMs) ? createdAtMs : updatedAtMs;
357
+ const sessionEndedAtMs = Math.max(updatedAtMs, sessionStartedAtMs);
358
+ normalizedSessions.push({
359
+ session,
360
+ sessionIndex,
361
+ source,
362
+ updatedAtMs,
363
+ createdAtMs,
364
+ sessionStartedAtMs,
365
+ sessionEndedAtMs,
366
+ bucketKey: formatUtcDayKey(updatedAtMs)
367
+ });
368
+ }
369
+ const { range, buckets } = buildUsageBuckets(normalizedSessions, options);
370
+ const bucketMap = new Map(buckets.map((bucket) => [bucket.key, bucket]));
371
+ let codexTotal = 0;
372
+ let claudeTotal = 0;
373
+ let messageTotal = 0;
374
+ let totalTokens = 0;
375
+ let totalContextWindow = 0;
376
+ let activeDurationMs = 0;
377
+ let earliestSessionMs = Number.POSITIVE_INFINITY;
378
+ let latestSessionMs = 0;
379
+ const pathMap = new Map();
380
+ const modelMap = new Map();
381
+ const missingModelProviderMap = new Map();
382
+ const missingModelSessionMap = new Map();
383
+ const sourceMessageTotals = { codex: 0, claude: 0 };
384
+ const missingModelSourceTotals = { codex: 0, claude: 0 };
385
+ let missingModelSessions = 0;
386
+ let providerOnlySessions = 0;
387
+ const hourCounts = Array.from({ length: 24 }, (_, hour) => ({
388
+ key: String(hour).padStart(2, '0'),
389
+ label: String(hour).padStart(2, '0'),
390
+ count: 0
391
+ }));
392
+ const weekdayLabels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
393
+ const weekdayCounts = Array.from({ length: 7 }, (_, index) => ({
394
+ key: String(index),
395
+ label: weekdayLabels[index],
396
+ count: 0
397
+ }));
398
+ const recentSessions = [];
399
+ const topSessionsByMessages = [];
400
+ const filteredSessions = [];
401
+
402
+ for (const normalized of normalizedSessions) {
403
+ const { session, sessionIndex, source, updatedAtMs, sessionStartedAtMs, sessionEndedAtMs, bucketKey } = normalized;
404
+ const stamp = new Date(updatedAtMs);
405
+ const bucket = bucketMap.get(bucketKey);
406
+ if (!bucket) continue;
407
+ const sessionModels = collectSessionModelNames(session);
408
+ if (sessionModels.length === 0) continue;
409
+ filteredSessions.push(session);
410
+ const messageCount = Number.isFinite(Number(session.messageCount))
411
+ ? Math.max(0, Math.floor(Number(session.messageCount)))
412
+ : 0;
413
+ const sessionTotalTokens = readSessionTotalTokens(session);
414
+ const sessionContextWindow = Number.isFinite(Number(session.contextWindow))
415
+ ? Math.max(0, Math.floor(Number(session.contextWindow)))
416
+ : 0;
417
+ bucket.totalSessions += 1;
418
+ bucket.totalMessages += messageCount;
419
+ if (source === 'codex') {
420
+ bucket.codex += 1;
421
+ codexTotal += 1;
422
+ } else {
423
+ bucket.claude += 1;
424
+ claudeTotal += 1;
425
+ }
426
+ messageTotal += messageCount;
427
+ totalTokens += sessionTotalTokens;
428
+ totalContextWindow += sessionContextWindow;
429
+ sourceMessageTotals[source] += messageCount;
430
+ activeDurationMs += Math.max(0, sessionEndedAtMs - sessionStartedAtMs);
431
+ earliestSessionMs = Math.min(earliestSessionMs, sessionStartedAtMs);
432
+ latestSessionMs = Math.max(latestSessionMs, sessionEndedAtMs);
433
+
434
+ const utcHour = stamp.getUTCHours();
435
+ if (hourCounts[utcHour]) {
436
+ hourCounts[utcHour].count += 1;
437
+ }
438
+ const dayIndex = (stamp.getUTCDay() + 6) % 7;
439
+ if (weekdayCounts[dayIndex]) {
440
+ weekdayCounts[dayIndex].count += 1;
441
+ }
442
+
443
+ const cwd = normalizeSessionPathFilter(session.cwd);
444
+ if (cwd) {
445
+ const prev = pathMap.get(cwd) || { count: 0, messageTotal: 0, updatedAtMs: 0 };
446
+ pathMap.set(cwd, {
447
+ count: prev.count + 1,
448
+ messageTotal: prev.messageTotal + messageCount,
449
+ updatedAtMs: Math.max(prev.updatedAtMs, updatedAtMs)
450
+ });
451
+ }
452
+
453
+ const sourceLabel = source === 'codex' ? 'Codex' : 'Claude Code';
454
+ const normalizedTitle = typeof session.title === 'string' && session.title.trim()
455
+ ? session.title.trim()
456
+ : (typeof session.sessionId === 'string' && session.sessionId.trim() ? session.sessionId.trim() : '未命名会话');
457
+ for (const modelId of sessionModels) {
458
+ const prev = modelMap.get(modelId) || {
459
+ count: 0,
460
+ messageTotal: 0,
461
+ tokenTotal: 0,
462
+ sources: new Set()
463
+ };
464
+ prev.count += 1;
465
+ prev.messageTotal += messageCount;
466
+ prev.tokenTotal += sessionTotalTokens;
467
+ prev.sources.add(source);
468
+ modelMap.set(modelId, prev);
469
+ }
470
+
471
+ const sessionEntry = {
472
+ key: [
473
+ source,
474
+ session.sessionId || '',
475
+ session.filePath || normalizedTitle,
476
+ String(updatedAtMs),
477
+ String(messageCount),
478
+ String(sessionIndex)
479
+ ].join(':'),
480
+ title: normalizedTitle,
481
+ source,
482
+ sourceLabel,
483
+ cwd,
484
+ messageCount,
485
+ updatedAt: session.updatedAt || '',
486
+ updatedAtMs,
487
+ updatedAtLabel: formatSessionTimelineTimestamp(session.updatedAt || ''),
488
+ hasExactMessageCount: session.__messageCountExact === true
489
+ };
490
+ recentSessions.push(sessionEntry);
491
+ topSessionsByMessages.push({ ...sessionEntry });
492
+ }
493
+
494
+ const totalSessions = codexTotal + claudeTotal;
495
+ const sourceShare = [
496
+ { key: 'codex', label: 'Codex', value: codexTotal },
497
+ { key: 'claude', label: 'Claude', value: claudeTotal }
498
+ ].map((item) => ({
499
+ ...item,
500
+ percent: totalSessions > 0 ? Math.round((item.value / totalSessions) * 100) : 0,
501
+ messageTotal: sourceMessageTotals[item.key] || 0,
502
+ messagePercent: messageTotal > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / messageTotal) * 100) : 0,
503
+ avgMessages: item.value > 0 ? Math.round(((sourceMessageTotals[item.key] || 0) / item.value) * 10) / 10 : 0
504
+ }));
505
+
506
+ const topPaths = [...pathMap.entries()]
507
+ .sort((a, b) => b[1].count - a[1].count || b[1].messageTotal - a[1].messageTotal || a[0].localeCompare(b[0], 'zh-Hans-CN'))
508
+ .slice(0, 5)
509
+ .map(([pathValue, meta]) => ({
510
+ path: pathValue,
511
+ count: meta.count,
512
+ messageTotal: meta.messageTotal,
513
+ updatedAtLabel: meta.updatedAtMs ? formatSessionTimelineTimestamp(new Date(meta.updatedAtMs).toISOString()) : ''
514
+ }));
515
+
516
+ const usedModels = [...modelMap.entries()]
517
+ .sort((a, b) => b[1].count - a[1].count)
518
+ .map(([modelId, meta]) => {
519
+ const sourceLabels = [...meta.sources]
520
+ .sort((a, b) => a.localeCompare(b, 'en-US'))
521
+ .map((source) => (source === 'codex' ? 'Codex' : 'Claude Code'));
522
+ return {
523
+ key: modelId,
524
+ model: modelId,
525
+ count: meta.count,
526
+ messageTotal: meta.messageTotal,
527
+ tokenTotal: meta.tokenTotal,
528
+ sourceLabels
529
+ };
530
+ });
531
+
532
+ const sortedRecentSessions = recentSessions
533
+ .sort((a, b) => b.updatedAtMs - a.updatedAtMs || b.messageCount - a.messageCount || a.title.localeCompare(b.title, 'zh-Hans-CN'))
534
+ .slice(0, 6);
535
+
536
+ const missingModelProviders = [...missingModelProviderMap.values()]
537
+ .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label, 'zh-Hans-CN'));
538
+ const missingModelSessionsPreview = [...missingModelSessionMap.values()]
539
+ .sort((a, b) => b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
540
+ .slice(0, 5);
541
+
542
+ const modelCoverage = {
543
+ totalSessions,
544
+ modeledSessions: Math.max(0, totalSessions - missingModelSessions),
545
+ missingModelSessions,
546
+ providerOnlySessions,
547
+ missingModelSourceTotals,
548
+ missingModelProviders,
549
+ missingModelSessionsPreview,
550
+ coveragePercent: totalSessions > 0 ? Math.round(((totalSessions - missingModelSessions) / totalSessions) * 100) : 0
551
+ };
552
+
553
+ const sortedTopSessionsByMessages = topSessionsByMessages
554
+ .sort((a, b) => b.messageCount - a.messageCount || b.updatedAtMs - a.updatedAtMs || a.title.localeCompare(b.title, 'zh-Hans-CN'))
555
+ .slice(0, 6);
556
+
557
+ const maxSessionBucket = buckets.reduce((max, item) => Math.max(max, item.totalSessions), 0);
558
+ const maxMessageBucket = buckets.reduce((max, item) => Math.max(max, item.totalMessages), 0);
559
+ const maxHourCount = hourCounts.reduce((max, item) => Math.max(max, item.count), 0);
560
+ const maxWeekdayCount = weekdayCounts.reduce((max, item) => Math.max(max, item.count), 0);
561
+ const busiestDay = [...buckets]
562
+ .sort((a, b) => b.totalSessions - a.totalSessions || b.totalMessages - a.totalMessages || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
563
+ const busiestHour = [...hourCounts]
564
+ .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key, 'zh-Hans-CN'))[0] || null;
565
+ const activeDays = buckets.filter((item) => item.totalSessions > 0).length;
566
+ const avgMessagesPerSession = totalSessions > 0 ? Math.round((messageTotal / totalSessions) * 10) / 10 : 0;
567
+ const avgSessionsPerActiveDay = activeDays > 0 ? Math.round((totalSessions / activeDays) * 10) / 10 : 0;
568
+ const totalDurationMs = Number.isFinite(earliestSessionMs) && latestSessionMs > 0
569
+ ? Math.max(0, latestSessionMs - earliestSessionMs)
570
+ : 0;
571
+
572
+ return {
573
+ range,
574
+ buckets,
575
+ filteredSessions,
576
+ summary: {
577
+ totalSessions,
578
+ totalMessages: messageTotal,
579
+ totalTokens,
580
+ totalContextWindow,
581
+ activeDurationMs,
582
+ totalDurationMs,
583
+ codexTotal,
584
+ claudeTotal,
585
+ activeDays,
586
+ avgMessagesPerSession,
587
+ avgSessionsPerActiveDay,
588
+ busiestDay: busiestDay
589
+ ? {
590
+ key: busiestDay.key,
591
+ label: busiestDay.label,
592
+ totalSessions: busiestDay.totalSessions,
593
+ totalMessages: busiestDay.totalMessages
594
+ }
595
+ : null,
596
+ busiestHour: busiestHour
597
+ ? {
598
+ key: busiestHour.key,
599
+ label: `${busiestHour.label}:00`,
600
+ count: busiestHour.count
601
+ }
602
+ : null
603
+ },
604
+ sourceShare,
605
+ usedModels,
606
+ modelCoverage,
607
+ topPaths,
608
+ recentSessions: sortedRecentSessions,
609
+ topSessionsByMessages: sortedTopSessionsByMessages,
610
+ hourActivity: hourCounts.map((item) => ({
611
+ ...item,
612
+ percent: maxHourCount > 0 ? Math.round((item.count / maxHourCount) * 100) : 0
613
+ })),
614
+ weekdayActivity: weekdayCounts.map((item) => ({
615
+ ...item,
616
+ percent: maxWeekdayCount > 0 ? Math.round((item.count / maxWeekdayCount) * 100) : 0
617
+ })),
618
+ maxSessionBucket,
619
+ maxMessageBucket,
620
+ maxHourCount,
621
+ maxWeekdayCount
622
+ };
623
+ }
624
+
625
+ export function buildSessionTimelineNodes(messages = [], options = {}) {
626
+ const list = Array.isArray(messages) ? messages : [];
627
+ const getKey = typeof options.getKey === 'function'
628
+ ? options.getKey
629
+ : ((_message, index) => `msg-${index}`);
630
+ const total = list.length;
631
+ const rawMaxMarkers = Number(options.maxMarkers);
632
+ const maxMarkers = Number.isFinite(rawMaxMarkers)
633
+ ? Math.max(1, Math.min(80, Math.floor(rawMaxMarkers)))
634
+ : 30;
635
+
636
+ const buildSingleNode = (message, index) => {
637
+ const role = normalizeSessionMessageRole(message && (message.normalizedRole || message.role));
638
+ const roleMeta = toRoleMeta(role);
639
+ const key = String(getKey(message, index) || `msg-${index}`);
640
+ const displayTime = formatSessionTimelineTimestamp(message && message.timestamp ? message.timestamp : '');
641
+ const title = displayTime
642
+ ? `#${index + 1} · ${roleMeta.roleLabel} · ${displayTime}`
643
+ : `#${index + 1} · ${roleMeta.roleLabel}`;
644
+ const percent = total <= 1 ? 0 : (index / (total - 1)) * 100;
645
+ return {
646
+ key,
647
+ role: roleMeta.role,
648
+ roleLabel: roleMeta.roleLabel,
649
+ roleShort: roleMeta.roleShort,
650
+ displayTime,
651
+ title,
652
+ percent,
653
+ safePercent: clampTimelinePercent(percent)
654
+ };
655
+ };
656
+
657
+ if (total <= maxMarkers) {
658
+ return list.map((message, index) => buildSingleNode(message, index));
659
+ }
660
+
661
+ const nodes = [];
662
+ const bucketWidth = total / maxMarkers;
663
+ for (let bucket = 0; bucket < maxMarkers; bucket += 1) {
664
+ let start = Math.floor(bucket * bucketWidth);
665
+ if (nodes.length && start <= nodes[nodes.length - 1].endIndex) {
666
+ start = nodes[nodes.length - 1].endIndex + 1;
667
+ }
668
+ if (start >= total) {
669
+ break;
670
+ }
671
+ let end = Math.floor((bucket + 1) * bucketWidth) - 1;
672
+ end = Math.max(start, Math.min(total - 1, end));
673
+ const targetIndex = Math.min(total - 1, start + Math.floor((end - start) / 2));
674
+ const targetMessage = list[targetIndex] || null;
675
+ const key = String(getKey(targetMessage, targetIndex) || `msg-${targetIndex}`);
676
+ const percent = total <= 1 ? 0 : (targetIndex / (total - 1)) * 100;
677
+ const messagesInGroup = end - start + 1;
678
+ const roleSet = new Set();
679
+ for (let i = start; i <= end; i += 1) {
680
+ roleSet.add(normalizeSessionMessageRole(list[i] && (list[i].normalizedRole || list[i].role)));
681
+ }
682
+ const roleValue = roleSet.size === 1 ? Array.from(roleSet)[0] : 'mixed';
683
+ const roleMeta = toRoleMeta(roleValue);
684
+ const firstTime = formatSessionTimelineTimestamp(list[start] && list[start].timestamp ? list[start].timestamp : '');
685
+ const lastTime = formatSessionTimelineTimestamp(list[end] && list[end].timestamp ? list[end].timestamp : '');
686
+ let displayTime = '';
687
+ if (firstTime && lastTime) {
688
+ displayTime = firstTime === lastTime ? firstTime : `${firstTime} ~ ${lastTime}`;
689
+ } else {
690
+ displayTime = firstTime || lastTime;
691
+ }
692
+ const titleBase = `#${start + 1}-${end + 1} · ${messagesInGroup} msgs · ${roleMeta.roleLabel}`;
693
+ const title = displayTime ? `${titleBase} · ${displayTime}` : titleBase;
694
+ nodes.push({
695
+ key,
696
+ role: roleMeta.role,
697
+ roleLabel: roleMeta.roleLabel,
698
+ roleShort: roleMeta.roleShort,
699
+ displayTime,
700
+ title,
701
+ percent,
702
+ safePercent: clampTimelinePercent(percent),
703
+ startIndex: start,
704
+ endIndex: end,
705
+ messageCount: messagesInGroup
706
+ });
707
+ }
708
+ return nodes;
709
+ }